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:
lasio.reader.open_with_codecs()
- manage issues relate to character encodingslasio.las.LASFile.read()
- control how NULL values and errors are handled during parsing
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:
lasio.reader.open_with_codecs()
- manage issues relate to character encodingslasio.las.LASFile.read()
- control how NULL values and errors are handled during parsing
-
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: - 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)
- 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”
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 tolasio.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
ifopenpyxl
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 iflineterminator
is not specified here, then it will be sent tocsv.writer
aslineterminator='\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.
- re_func (str) – either “match” or “search”, see python
-
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)
-
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 arrayKeyword 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.- names (list, optional) – used to replace the names of the existing
-
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: 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.
-
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) –
-
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:
-
insert_curve
(ix, mnemonic, data, unit='', descr='', value='')[source]¶ Insert a curve.
Parameters: Keyword Arguments:
-
delete_curve
(mnemonic=None, ix=None)[source]¶ Delete a curve.
Keyword Arguments: 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 aTypeError
).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: 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.
-
-
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.
-
-
class
lasio.las_items.
SectionItems
(*args, **kwargs)[source]¶ Bases:
list
Variant of a
list
which is used to represent a LAS section.-
__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
-
__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 alasio.las_items.HeaderItem
then the existing item will be replaced. Otherwise the existing item’svalue
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()
andlasio.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.
-
__weakref__
¶ list of weak references to the object (if defined)
-
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 eithercchardet
orchardet
needs to be installed, or else anImportError
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()
.- encoding (str) – character encoding to open file_ref with, using
-
lasio.reader.
get_encoding
(auto, raw)[source]¶ Automatically detect character encoding.
Parameters: 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: 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: - sectdict (dict) – object returned from
lasio.reader.read_file_contents()
- version (float) – either 1.2 or 2.0
Keyword Arguments: - ignore_header_errors (bool) – if True, issue HeaderItem parse errors
as
logging.warning()
calls instead of alasio.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: - sectdict (dict) – object returned from
-
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.
-
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_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 usefmt='%.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.- las (
-
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: 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: 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: - section_name (str) – either ‘version’, ‘well’, ‘curves’, or ‘params’
- items (SectionItems) – section items
- version (float) – either 1.2 or 2.0
- order_func (func) – see
lasio.writer.get_section_order_function()