Docstrings for the lasio package

Module contents

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 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:

Submodules

lasio.las module

class lasio.las.LASFile(file_ref=None, **read_kwargs)[source]

Bases: object

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
read(file_ref, ignore_data=False, read_policy='default', null_policy='strict', ignore_header_errors=False, mnemonic_case='upper', index_unit=None, **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:
 

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

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
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) –
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'.
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.

get_curve(mnemonic)[source]

Return CurveItem object.

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

Return curve mnemonics.

values()[source]

Return data for each curve.

items()[source]

Return mnemonics and data for all curves.

iterkeys()[source]
itervalues()[source]
iteritems()[source]
version

Header information from the Version (~V) section.

Returns:lasio.las_items.SectionItems object.
well

Header information from the Well (~W) section.

Returns:lasio.las_items.SectionItems object.
curves

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

Returns:lasio.las_items.SectionItems object.
curvesdict

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

Returns:dict
params

Header information from the Parameter (~P) section.

Returns:lasio.las_items.SectionItems object.
other

Header information from the Other (~O) section.

Returns:str
metadata

All header information joined together.

Returns:lasio.las_items.SectionItems object.
header

All header information

Returns:dict
df()[source]

Return data as a pandas.DataFrame structure.

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

data
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.las_items.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.

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.las.LASFile.set_data().

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

index

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

depth_m

Return the index as metres.

depth_ft

Return the index as feet.

add_curve_raw(mnemonic, data, unit='', descr='', value='')[source]

Deprecated. Use append_curve_item() or insert_curve_item() instead.

append_curve_item(curve_item)[source]

Add a CurveItem.

Parameters:curve_item (lasio.CurveItem) –
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) –
add_curve(*args, **kwargs)[source]

Deprecated. Use append_curve() or insert_curve() instead.

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.
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.
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.

json

Return object contents as a JSON string.

class lasio.las.Las(file_ref=None, **read_kwargs)[source]

Bases: lasio.las.LASFile

LAS file object.

Retained for backwards compatibility.

class lasio.las.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.encoder.JSONEncoder

default(obj)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)

lasio.las_items module

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

Bases: collections.OrderedDict

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.

__init__(mnemonic='', unit='', value='', descr='', data=None)[source]

Initialize self. See help(type(self)) for accurate signature.

set_session_mnemonic_only(value)[source]

Set the mnemonic for session use.

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

__getitem__(key)[source]

Provide item dictionary-like access.

__setattr__(key, value)[source]

Implement setattr(self, name, value).

__repr__()[source]

Return repr(self).

__reduce__()[source]

Return state information for pickling

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

Bases: lasio.las_items.HeaderItem

Dictionary/namedtuple-style object for a LAS curve.

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

Keyword Arguments:
 data (array-like, 1-D) – the curve’s data.
__init__(mnemonic='', unit='', value='', descr='', data=None)[source]

Initialize self. See help(type(self)) for accurate signature.

API_code

Equivalent to the value attribute.

__repr__()[source]

Return repr(self).

class lasio.las_items.SectionItems(*args, **kwargs)[source]

Bases: list

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

__init__(*args, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

__str__()[source]

Return str(self).

__contains__(testitem)[source]

Check whether a header item or mnemonic is in the section.

Parameters:testitem (HeaderItem, CurveItem, str) – either an item or a mnemonic
Returns:bool
keys()[source]

Return mnemonics of all the HeaderItems in the section.

values()[source]

Return HeaderItems in the section.

items()[source]

Return pairs of (mnemonic, HeaderItem) from the section.

__getslice__(i0, i1)[source]

For Python 2.7 compatibility.

__getitem__(key)[source]

Item-style access by either mnemonic or index.

Parameters:key (str, int, slice) – either a mnemonic or the index to the list.
Returns:item from the list (either HeaderItem or CurveItem)
__delitem__(key)[source]

Delete item by either mnemonic or index.

Parameters:key (str, int) – either a mnemonic or the index to the list.
__setitem__(key, newitem)[source]

Either replace the item or its value.

Parameters:
  • key (int, str) – either the mnemonic or the index.
  • newitem (HeaderItem or str/float/int) – the thing to be set.

If newitem is a lasio.las_items.HeaderItem then the existing item will be replaced. Otherwise the existing item’s value attribute will be replaced.

i.e. this allows us to do

>>> from lasio import SectionItems, HeaderItem
>>> section = SectionItems(
...     [HeaderItem(mnemonic="OPERATOR", value="John")]
... )
>>> section.OPERATOR
HeaderItem(mnemonic=OPERATOR, unit=, value=John, descr=)
>>> section.OPERATOR = 'Kent'
>>> section.OPERATOR
HeaderItem(mnemonic=OPERATOR, unit=, value=Kent, descr=)

See lasio.las_items.SectionItems.set_item() and lasio.las_items.SectionItems.set_item_value().

__getattr__(key)[source]

Provide attribute access via __contains__ e.g.

>>> from lasio import SectionItems, HeaderItem
>>> section = SectionItems(
...     [HeaderItem(mnemonic="VERS", value=1.2)]
... )
>>> section['VERS']
HeaderItem(mnemonic=VERS, unit=, value=1.2, descr=)
>>> 'VERS' in section
True
>>> section.VERS
HeaderItem(mnemonic=VERS, unit=, value=1.2, descr=)
__setattr__(key, value)[source]

Allow access to lasio.las_items.SectionItems.__setitem__() via attribute access.

set_item(key, newitem)[source]

Replace an item by comparison of session mnemonics.

Parameters:
  • key (str) – the item mnemonic (or HeaderItem with mnemonic) you want to replace.
  • newitem (HeaderItem) – the new item

If key is not present, it appends newitem.

set_item_value(key, value)[source]

Set the value attribute of an item.

Parameters:
  • key (str) – the mnemonic of the item (or HeaderItem with the mnemonic) you want to edit
  • value (str, int, float) – the new value.
append(newitem)[source]

Append a new HeaderItem to the object.

insert(i, newitem)[source]

Insert a new HeaderItem to the object.

__weakref__

list of weak references to the object (if defined)

assign_duplicate_suffixes(test_mnemonic=None)[source]

Check and re-assign suffixes for duplicate mnemonics.

Parameters:test_mnemonic (str, optional) – check for duplicates of this mnemonic. If it is None, check all mnemonics.
dictview()[source]

View of mnemonics and values as a dict.

Returns:dict - keys are the mnemonics and the values are the value attributes.

lasio.reader module

lasio.reader.check_for_path_obj(file_ref)[source]

Check if file_ref is a pathlib.Path object.

If file_ref is a pathlib.Path object, then return its absolute file path as a string so it will get processed as other string filenames.

If pathlib is not available, do nothing and return file_ref.

lasio.reader.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 codecs.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.adhoc_test_encoding(filename)[source]
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)[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
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,
 }
lasio.reader.read_data_section_iterative(file_obj, regexp_subs, value_null_subs)[source]

Read data section into memory.

Parameters:
  • file_obj (open file-like object) – should be positioned in line-by-line reading mode, with the last line read being the title of the ~ASCII data section.
  • 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.
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.

lasio.reader.parse_header_section(sectdict, version, ignore_header_errors=False, mnemonic_case='preserve')[source]

Parse a header section dict into a SectionItems containing HeaderItems.

Parameters:
Keyword Arguments:
 
  • ignore_header_errors (bool) – if True, issue HeaderItem parse errors as logging.warning() calls instead of a lasio.exceptions.LASHeaderError exception.
  • mnemonic_case (str) – ‘preserve’: keep the case of HeaderItem mnemonics ‘upper’: convert all HeaderItem mnemonics to uppercase ‘lower’: convert all HeaderItem mnemonics to lowercase
Returns:

lasio.las_items.SectionItems

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

Bases: object

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.
num(x, default=None)[source]

Attempt to parse a number.

Parameters:
Returns:

int, float, or default - from most to least preferred types.

strip_brackets(x)[source]
metadata(**keys)[source]

Return HeaderItem correctly formatted according to the order prescribed for LAS v 1.2 or 2.0 for the ~W section.

Keyword arguments should be the key:value pairs returned by lasio.reader.read_header_line().

curves(**keys)[source]

Return CurveItem.

Keyword arguments should be the key:value pairs returned by lasio.reader.read_header_line().

params(**keys)[source]

Return HeaderItem for ~P section (the same between 1.2 and 2.0 specs)

Keyword arguments should be the key:value pairs returned by lasio.reader.read_header_line().

lasio.reader.read_line(*args, **kwargs)[source]

Retained for backwards-compatibility.

See lasio.reader.read_header_line().

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
Returns:A dictionary with keys ‘name’, ‘unit’, ‘value’, and ‘descr’, each containing a string as value.

lasio.writer module

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.las.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.

You should avoid calling this function directly - instead use the lasio.las.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.las_items.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'])]}, 2.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:

lasio.excel module

lasio.defaults module

lasio.defaults.get_default_items()[source]

lasio.exceptions module

exception lasio.exceptions.LASDataError[source]

Bases: Exception

Error during reading of numerical data from LAS file.

exception lasio.exceptions.LASHeaderError[source]

Bases: Exception

Error during reading of header data from LAS file.

exception lasio.exceptions.LASUnknownUnitError[source]

Bases: Exception

Error of unknown unit in LAS file.