Difference between revisions of "Python PDS4 Tools"

From The SBN Wiki
Jump to navigation Jump to search
m (Add which PDS4 data standards are supported)
m (Update user manual URL)
 
(41 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 +
<div style="clear: {{{clear|right}}}; margin-bottom: .5em; float: right; padding: .5em 0 .8em 1.4em; background: none; width: {{{width|{{{1|auto}}}}}};" {{#if:{{{limit|}}}|class="toclimit-{{{limit}}}"}}>__TOC__</div><noinclude></noinclude>
  
== Introduction ==
+
'''Python and PDS4'''
  
This document describes the current status and usage of Python tools developed at PDS-SBN to read and visualize PDS4 data in Python. Please note that a more feature-complete [http://pds-smallbodies.astro.umd.edu/tools/tools_readPDS.shtml PDS4 reader and visualizer for IDL] is also available.
+
This document describes the current status and usage of Python tools developed at PDS-SBN to read and visualize PDS4 data in Python. Please note that a [http://pds-smallbodies.astro.umd.edu/tools/tools_readPDS.shtml PDS4 reader and visualizer for IDL] is also available.
  
== Reading PDS4 Images ==
+
== Reading and Displaying PDS4 Data ==
  
This section describes an example Python module that can read and display an image from a BOPPS/BIRC PDS4 data product. The code will read the data based on the label keywords, but does not otherwise validate the label. If the user wants to display the image, the code will consider the label's <tt>Display_Settings</tt>, and provide a copy of the image in the correct orientation for drawing with the origin in the lower left corner (which can then be displayed with Matplotlib).
+
=== Introduction ===
 +
 
 +
This section describes a Python package that can read and display PDS4 data and meta data. In the future this tool is expected to support all PDS4 data structures, currently support is limited to structures given in the [[#Supported Data Structures|Supported Data Structures]] section. The package expects valid PDS4 labels formatted according to the PDS4 Standard.
  
The code below is specifically designed for reading BOPPS/BIRC images, but can be used as an example for other limited problems.  A more general solution may use a different approach, and will be developed by SBN in the future.
+
Contact [[User:lnagdi1|Lev Nagdimunov]] with questions or comments regarding this code or its description.
  
Contact [[User:Kelley|Mike Kelley]] with questions or comments regarding this code or its description.
+
=== Requirements ===
 +
 
 +
Python 2.6+ or 3.3+
 +
 
 +
pds4_read: [http://www.numpy.org/ NumPy] <br>
 +
pds4_viewer: [http://www.numpy.org/ NumPy], [http://www.matplotlib.org/ matplotlib]
 +
 
 +
=== Supported Data Structures ===
 +
 
 +
PDS4 Data Standards >= v1.0 are supported.<br>
 +
PDS3 Data Standards are not supported.
 +
 
 +
The table below lists the main [[Filling_Out_the_File_Area_Observational_Classes#Data_Structures|PDS4 data structures]] and the current status. <br><br>
 +
Read-in column indicates support by <tt>pds4_tools.read()</tt> <br>
 +
Display columns indicate support by <tt>pds4_tools.view()</tt>.
 +
 
 +
{| class="wikitable" style="text-align: center; width: 800px; "
 +
|-
 +
! Structure
 +
! Read-in
 +
! Display as Table
 +
! Display as Image
 +
! Display Columns as Plot
 +
|-
 +
| style="text-align: left;" | Header
 +
| Yes
 +
| No
 +
| No
 +
| No
 +
|-
 +
| style="text-align: left;" | Array
 +
| Yes
 +
| Yes
 +
| Yes, N-dims
 +
| Yes, 1-D only
 +
|-
 +
| style="text-align: left;" | Array_2D
 +
| Yes
 +
| Yes
 +
| Yes
 +
| No
 +
|-
 +
| style="text-align: left;" | Array_2D_*
 +
| Yes
 +
| Yes
 +
| Yes
 +
| No
 +
|-
 +
| style="text-align: left;" | Array_3D
 +
| Yes
 +
| Yes
 +
| Yes
 +
| No
 +
|-
 +
| style="text-align: left;" | Array_3D_*
 +
| Yes
 +
| Yes
 +
| Yes
 +
| No
 +
|-
 +
| style="text-align: left;" | Table_Character
 +
| Yes
 +
| Yes
 +
| No
 +
| Yes
 +
|-
 +
| style="text-align: left;" | Table_Binary
 +
| Yes, except BitFields
 +
| Yes
 +
| No
 +
| Yes
 +
|-
 +
| style="text-align: left;" | Table_Delimited
 +
| Yes
 +
| Yes
 +
| No
 +
| Yes
 +
|-
 +
| style="text-align: left;" | Composite_Structure
 +
| No
 +
| No
 +
| No
 +
| No
 +
|}
 +
 
 +
=== User Manual ===
 +
 
 +
Online [https://pdssbn.astro.umd.edu/tools/pds4_tools_docs/current/ usage documentation], both for scientists and for developers, is available.
  
 
=== Download ===
 
=== Download ===
  
[[File:Birc_example_reader.zip]]
+
Download the ZIP file <span class="plainlinks">[https://pdssbn.astro.umd.edu/toolsrc/readpds_python/1.3/PDS4_tools-1.3.zip File:PDS4 tools-1.3.zip]</span>. Released on October 10, 2021.
  
=== Requirements ===
+
Note: A distributable version of the viewer only, which does not require Python, is [[PDS4 Viewer|available]].
 +
 
 +
=== Installation ===
 +
 
 +
==== Option 1 ====
 +
 
 +
Use "<tt>pip install PDS4_tools-1.3.zip</tt>"
  
This example assumes the user is running Python 2.7, with a recent [http://www.numpy.org/ NumPy] package installed.  The visualization example uses [http://www.matplotlib.org/ matplotlib].
+
==== Option 2 ====
  
=== Goal and Method ===
+
Extract the downloaded file to a directory Python can find. To use it follow the instructions in [[Python_PDS4_Tools#Example_Usage|Example Usage]] except with the following lines first,
  
The goal is to read in an image from a BOPPS/BIRC data product into a Numpy array, providing the correct orientation for display.  We will provide a function with the name of the label, the function will then
+
<pre>
# Open the label.
+
import sys
# Find the data product file name.
+
sys.path.extend([r'/path/to/extraction_directory/'])
# Determine the Array_2D_Image data type and shape.
 
# Read in the data array.
 
# Return the array and meta data in a single object.
 
  
The object will have two attributes that allow access to the data
+
import pds4_tools
# the data with the axis order and orientation as provided in the file, and
+
</pre>
# the data with the axis order and orientation reconfigured according to the label's <tt>Display_Settings</tt> class, so that it will have the correct orientation if drawn with the origin in the lower left corner.
 
  
=== Implementation Details ===
+
=== Example Usage ===
  
For this basic example, we designed the reader as a function in a module named <tt>birc_example_reader</tt>.  The user calls a single function, <tt>read_image()</tt>, passing the name of the label as the first argument.  The function will load the label using the [https://docs.python.org/2.7/library/xml.etree.elementtree.html ElementTree] module and find the first <tt>Array_2D_Image</tt> element to read in.  A second function, <tt>read_pds4_array()</tt>, determines the correct data type and shape, then reads the data from the file.  A class specifically designed for PDS4 <tt>Array_2D_Image</tt> objects, aptly named <tt>PDS4_Array_2D_Image</tt>, is initialized with the data, the label describing the data, and the <tt>local_identifier</tt> of the array.  The <tt>local_identifier</tt> is not normally required in PDS4 array objects, but it must be present when the image display orientation is provided via <tt>Display_Settings</tt>.  Since these are present in the BIRC labels, our class assumes <tt>local_identifier</tt> is included.  The class then determines the image orientation.  The image is stored as a class attribute <tt>data</tt>.  The class attribute <tt>display_data</tt> is also provided, which can be used for displaying with Matplotlib.
+
'''See also the [https://pdssbn.astro.umd.edu/tools/pds4_tools_docs/current/ User Manual].'''
  
=== Examples ===
+
==== pds4_read ====
  
To read and display a BOPPS/BIRC image:
+
Import via "<tt>import pds4_tools</tt>". You may then call <tt>pds4_tools.read()</tt> from your own code.  The following is the docstring for <tt>pds4_tools.read()</tt>:
  
 
<pre>
 
<pre>
import birc_example_reader as birc
+
        Reads PDS4 compliant data into a `StructureList`.
import matplotlib.pyplot as plt
+
 
 +
        Given a PDS4 label, reads the PDS4 data described in the label and
 +
        associated label meta data into a `StructureList`, with each PDS4 data
 +
        structure (e.g. Array_2D, Table_Binary, etc) as its own `Structure`. By
 +
        default all data structures described in the label are immediately
 +
        read into memory.
  
# array is im.data
+
        Notes
# array for displaying is im.display_data
+
        -----
im = birc.read_image('cerh2_1_010000_rb_n169_n011.xml')
+
        Python 2 v. Python 3: Non-data strings (label, meta data, etc)  in
 +
        Python 2 will be decoded to ``unicode`` and in Python 3 they will
 +
        be decoded to ``str``. The return type of all data strings is
 +
        controlled by *decode_strings*.
  
plt.clf()
+
        Remote URLs are downloaded into an on-disk cache which is cleared on
plt.imshow(im.display_data, origin='lower')
+
        Python interpreter exit.
plt.draw()
 
</pre>
 
  
==== Minimal Working Example ====
+
        Parameters
 +
        ----------
 +
        filename : str or unicode
 +
            The filename, including full or relative path, or a remote
 +
            URL to the PDS4 label describing the data.
 +
        quiet : bool, int or str, optional
 +
            If True, suppresses all info/warnings from being output to stdout.
 +
            Supports log-level style options for more fine grained control.
 +
            Defaults to False.
 +
        lazy_load : bool, optional
 +
            If True, then the data of each PDS4 data structure will not be
 +
            read-in to memory until the first attempt to access it. Additionally,
 +
            for remote URLs, the data is not downloaded until first access.
 +
            Defaults to False.
 +
        no_scale : bool, optional
 +
            If True, returned data will be exactly as written in the data file,
 +
            ignoring offset or scaling values. Defaults to False.
 +
        decode_strings : bool, optional
 +
            If True, strings data types contained in the returned data will be
 +
            decoded to the a unicode in Python 2, and to the str type in
 +
            Python 3. If False, leaves string types as byte strings.
 +
            Defaults to True.
  
Below we provide a minimal working example with the same basic functionality. The example is a flat script with extensive comments, which may more clearly illustrate some of the methods for working with PDS4 image labels.
+
        Returns
 +
        -------
 +
        StructureList
 +
            Contains PDS4 data `Structure`'s, each of which contains the data,
 +
            the meta data and the label portion describing that data structure.
 +
            `StructureList` can be treated/accessed/used like a ``dict`` or
 +
            ``list``.
  
[[File:birc_mwe.zip]]
+
        Examples
 +
        --------
  
 +
        Below we document how to read data described by an example label
 +
        which has two data structures, an Array_2D_Image and a Table_Binary.
 +
        An outline of the label, including the array and a table with 3
 +
        fields, is given.
  
 +
        >>> # Local file
 +
        >>> struct_list = pds4_tools.read('/path/to/Example_Label.xml')
  
== Reading PDS4 Tables ==
+
        >>> # Remote URL
 +
        >>> struct_list = pds4_tools.read('https://url.com/Example_Label.xml')
  
=== Introduction ===
+
        Example Label Outline::
  
This section describes a Python package that can read and display PDS4 table data. In the future this tool is expected to support all PDS4 objects. The package expects labels that pass PDS4 Schema and Schematron validation.
+
          Array_2D_Image: unnamed
 +
          Table_Binary: Observations
 +
              Field: order
 +
              Field: wavelength
 +
              Group: unnamed
 +
                  Field: pos_vector
  
Contact [[User:lnagdi1|Lev Nagdimunov]] with questions or comments regarding this code or its description.
+
        All below documentation assumes that the above outlined label,
 +
        containing an array that does not have a name indicated in the label,
 +
        and a table that has the name 'Observations' with 3 fields as shown,
 +
        has been read-in.
  
=== Requirements ===
+
        Accessing Example Structures:
  
Python 2.6 or 2.7.
+
            To access the data structures in `StructureList`, which is returned
 +
            by `pds4_read()`, you may use any combination of ``dict``-like or
 +
            ``list``-like access.
  
pds4_read: None <br>
+
            >>> unnamed_array = struct_list[0]
pds4_viewer: [http://www.numpy.org/ NumPy]
+
            >>>              or struct_list['ARRAY_0']
  
You may use <tt>pds4_read</tt> to read-in data without any extra packages; <tt>pds4_viewer</tt> requires additional packages.
+
            >>> obs_table = struct_list[1]
 +
            >>>          or struct_list['Observations']
  
==== Optional Features ====
+
        Label or Structure Overview:
  
pds4_read: [http://www.numpy.org/ NumPy]<br>
+
            To see a summary of the data structures, which for Arrays shows the
Recommended for Arrays and Tables containing GROUP fields to allow for multi-dimensional indexing.<br>
+
            type and dimensions of the array, and for Tables shows the type
 +
            and number of fields, you may use the `StructureList.info()` method.
 +
            Calling `Structure.info()` on a specific ``Structure`` instead will
 +
            provide a more detailed summary, including all Fields for a table.
  
pds4_viewer: None
+
            >>> struct_list.info()
 +
            >>> unnamed_array.info()
 +
            >>> obs_table.info()
  
=== Supported Objects ===
+
        Accessing Example Label data:
  
PDS4 Data Standards < v1.3 are not officially supported but may work.<br>
+
            To access the read-in data, as an array-like (subclass of ``ndarray``),
PDS4 Data Standards >= v1.3 are supported.
+
            you can use the data attribute for a PDS4 Array data structure, or
 +
            list-like and the field() method to access a field for a table.
  
The following is a list of supported PDS4 data objects:
+
            >>> # PDS4 Arrays
 +
            >>> unnamed_array.data
  
Table_Character: Full <br>
+
            >>> # PDS4 Table fields
Table_Binary: Full, except BitFields
+
            >>> obs_table['wavelength']
 +
            >>> obs_table.field('wavelength')
  
No other PDS4 data objects are currently supported.
+
            >>> # PDS4 Table records
 +
            >>> obs_table[0:1000]
  
=== Download ===
+
        Accessing Example Label meta data:
  
Download the ZIP file [[File:PDS4_tools-0.2.zip]]
+
            You can access all meta data in the label for a given PDS4 data
 +
            structure or field via the ``OrderedDict`` meta_data attribute. The
 +
            below examples use the 'description' element.
  
=== Installation ===
+
            >>> unnamed_array.meta_data['description']
  
==== Option 1 ====
+
            >>> obs_table.field('wavelength').meta_data['description']
 +
            >>> obs_table.field('pos_vector').meta_data['description']
  
Extract the downloaded file to a directory Python can find. To use it follow the instructions in [[Python_PDS4_Tools#Example_Usage|Example Usage]] except with the following lines first,
+
        Accessing Example Label:
  
<pre>
+
            The XML for a label is also accessible via the label attribute,
import sys
+
            either the entire label or for each PDS4 data structure.
sys.path.extend(['/path/to/your/extraction/directory'])
 
  
# On a windows machine use backslashes (/) instead of windows' normal forward slashes to specify paths
+
            Entire label:
</pre>
+
                >>> struct_list.label
  
==== Option 2 ====
+
            Part of label describing Observations table:
 +
                >>> struct_list['Observations'].label
 +
                >>> struct_list[1].label
  
Use "<tt>pip install PDS4_tools-0.2.zip</tt>" or "<tt>easy_install PDS4_tools-0.2.zip</tt>". You can also extract the ZIP file and use "<tt>python /path/to/extracted/setup.py install</tt>". Note that there is no uninstall script provided (although "<tt>pip uninstall pds4_tools</tt>" should work), and that this tool currently has many missing features and will be updated in the future.  
+
            The returned object is similar to an ElementTree instance. It is
 +
            searchable via `Label.find()` and `Label.findall()` methods and XPATH.
 +
            Consult ``ElementTree`` manual for more details. For example,
  
=== Example Usage ===
+
            >>> struct_list.label.findall('.//disp:Display_Settings')
  
==== pds4_read ====
+
            Will find all elements in the entire label named 'Display_Settings'
 +
            which are in the 'disp' prefix's namespace. You can additionally use the
 +
            `Label.to_dict()` and `Label.to_string()` methods.
 +
</pre>
  
You may call <tt>pds4_read</tt> from command line or from your own script. Typing the shell command <tt>python pds4_read.py -h</tt> prints out the help text:
+
Usage is described above. A basic usage example is as follows:
  
 
<pre>
 
<pre>
usage: pds4_read.py [-h] [--quiet] [--use_numpy] [--object_num OBJECT_NUM]
+
""" Basic Reader example """
                    [--object_name OBJECT_NAME] [--object_lid OBJECT_LID]
+
 
                    filename
+
import pds4_tools
  
positional arguments:
+
structures = pds4_tools.read('/path/to/label.xml')
  filename              Filename, including full path, of the label
 
  
optional arguments:
+
structures.info()
  -h, --help            show this help message and exit
 
  --quiet              Suppresses all info/warnings
 
  --use_numpy          Returned data will be a numpy array and use numpy data types
 
  --object_num OBJECT_NUM
 
                        Only reads the data object specified by zero-based order (integer)
 
  --object_name OBJECT_NAME
 
                        Only reads the data object specified by name
 
  --object_lid OBJECT_LID
 
                        Only reads the data object specified by local identifier
 
</pre>
 
  
If called from another module or a script, all of the above optional arguments would be available as optional named parameters of the function <tt>pds4_read()</tt>. Basic example usage is as follows:
+
0 - Array_3D_Spectrum 'table_name' (3 axes, 21 x 10 x 36)
 +
1 - Table_Binary 'array_name' (5 fields x 1000 records)
  
<pre>
+
# Table data access
""" Basic pds4_read example """
+
table = structures['table_name'] # or
 +
table = structures[0]
  
from pds4_tools import pds4_read
+
table.info()
  
obj_list = pds4_read('/path/to/label.xml')
+
field_data = table.field('field_name') # or
 +
field_data = table.fields[0]
  
table = obj_list['table_name'] # or
+
record_data = table[0:50]
table = obj_list[0]
 
  
# Dictionary-like access
+
# Array data access
column = table.data['field_name']
+
array = structures['array_name'] # or
row_1_to_100 = column[0:100]
+
array = structures[1]
  
# List-like access
+
array_data = array.data
column = table.data[0]
 
row_1_to_100 = column[0:100]
 
  
 
# Meta-data access
 
# Meta-data access
column_meta = table.data.meta_data('field_name')
+
field_meta = table.field('field_name').meta_data # or
column_meta = table.data.meta_data(0)
+
field_meta = table.fields[0].meta_data
 +
array_meta = array.meta_data
 +
 
 +
print field_meta['description']
 +
print field_meta['unit']
 +
print array_meta['local_identifier']
 +
 
 +
# Label access
 +
label = structures.label # Full label
 +
label = table.label      # Label section describing the table object
 +
 
 +
display_settings = label.findall('.//disp:Display_Settings')
  
print column_meta['description']
+
display_dict = display_settings.to_dict()
print column_meta['unit']
+
label_dict = label.to_dict()
 +
label_string = label.to_string()
  
# Label access, provides ElementTree object
 
label = obj_list.label # Full label
 
label = table.label # Label section describing the table object
 
 
</pre>
 
</pre>
  
 
==== pds4_viewer ====
 
==== pds4_viewer ====
  
To display the objects in a label you may call <tt>pds4_viewer</tt> from the command line:
+
Import via "<tt>import pds4_tools</tt>". To display the data structures (such as images, spectra, or tables) in a label you may then call <tt>pds4_tools.view()</tt> from the Python interpreter, with or without any arguments:
  
 
<pre>
 
<pre>
usage: pds4_viewer.py [-h] [--quiet] [--object_num OBJECT_NUM]
+
    Displays PDS4 compliant data in a GUI.
                    [--object_name OBJECT_NAME] [--object_lid OBJECT_LID]
 
                    [filename]
 
  
positional arguments:
+
    Given a PDS4 label, displays PDS4 data described in the label and
  filename              Filename, including full path, of the label
+
    associated label meta data in a GUI. By default all data structures described
 +
    in the label are read-in and displayed. Can be called without any
 +
    parameters, opening a GUI that has a File->Open function to select
 +
    desired label to be read-in and displayed.
  
optional arguments:
+
    Parameters
  -h, --help            show this help message and exit
+
    ----------
  --quiet              Suppresses all info/warnings
+
    filename : str or unicode, optional
  --object_num OBJECT_NUM
+
        The filename, including full or relative path if necessary, of
                        Only reads the data object specified by zero-based order (integer)
+
        the PDS4 label describing the data to be viewed.
  --object_name OBJECT_NAME
+
    from_existing_structures : StructureList, optional
                        Only reads the data object specified by name
+
        An existing StructureList, as returned by pds4_read(), to view. Takes
  --object_lid OBJECT_LID
+
        precedence if given together with filename.
                        Only reads the data object specified by local identifier
+
    lazy_load : bool, optional
 +
        Do not read-in data of each data structure until attempt to view said
 +
        data structure. Defaults to True.
 +
    quiet : bool, int or str, optional
 +
        Suppresses all info/warnings from being output and displayed. Supports
 +
        log-level style options for more fine grained control. Defaults to False.
 
</pre>
 
</pre>
  
It is not necessary to include the filename parameter for <tt>pds4_viewer</tt>, you may simplify call it without any options or arguments and a GUI will open from which you can open labels.  
+
It is not necessary to include the filename parameter for <tt>pds4_tools.view</tt>, you may simplify call it without any options or arguments and a GUI will open from which you can open labels.  
  
You may also call <tt>pds4_viewer</tt> from another module or script. All the above optional arguments are available as optional named parameters. A basic example usage is as follows:
+
You may also call <tt>pds4_tools.view</tt> from another module or script. All the above arguments are available as optional named parameters. A basic example usage is as follows:
  
 
<pre>
 
<pre>
""" Basic pds4_viewer example """
+
""" Basic Viewer example """
  
from pds4_tools import pds4_read, pds4_viewer
+
import pds4_tools
  
pds4_viewer()
+
pds4_tools.view()
  
 
# or
 
# or
  
pds4_viewer('label.xml')
+
pds4_tools.view('/path/to/label.xml')
  
 
# or  
 
# or  
  
obj_list = pds4_read('label.xml')
+
struct_list = pds4_tools.view('label.xml')
pds4_viewer('label.xml', from_existing_objects=obj_list) # Won't re-read the data
+
pds4_tools.view(from_existing_structures=struct_list) # Won't re-read the data
 
</pre>
 
</pre>
 +
 +
 +
 +
[[Category:Python]]
 +
[[Category:Tools]]

Latest revision as of 06:28, 7 November 2021

Python and PDS4

This document describes the current status and usage of Python tools developed at PDS-SBN to read and visualize PDS4 data in Python. Please note that a PDS4 reader and visualizer for IDL is also available.

Reading and Displaying PDS4 Data

Introduction

This section describes a Python package that can read and display PDS4 data and meta data. In the future this tool is expected to support all PDS4 data structures, currently support is limited to structures given in the Supported Data Structures section. The package expects valid PDS4 labels formatted according to the PDS4 Standard.

Contact Lev Nagdimunov with questions or comments regarding this code or its description.

Requirements

Python 2.6+ or 3.3+

pds4_read: NumPy
pds4_viewer: NumPy, matplotlib

Supported Data Structures

PDS4 Data Standards >= v1.0 are supported.
PDS3 Data Standards are not supported.

The table below lists the main PDS4 data structures and the current status.

Read-in column indicates support by pds4_tools.read()
Display columns indicate support by pds4_tools.view().

Structure Read-in Display as Table Display as Image Display Columns as Plot
Header Yes No No No
Array Yes Yes Yes, N-dims Yes, 1-D only
Array_2D Yes Yes Yes No
Array_2D_* Yes Yes Yes No
Array_3D Yes Yes Yes No
Array_3D_* Yes Yes Yes No
Table_Character Yes Yes No Yes
Table_Binary Yes, except BitFields Yes No Yes
Table_Delimited Yes Yes No Yes
Composite_Structure No No No No

User Manual

Online usage documentation, both for scientists and for developers, is available.

Download

Download the ZIP file File:PDS4 tools-1.3.zip. Released on October 10, 2021.

Note: A distributable version of the viewer only, which does not require Python, is available.

Installation

Option 1

Use "pip install PDS4_tools-1.3.zip"

Option 2

Extract the downloaded file to a directory Python can find. To use it follow the instructions in Example Usage except with the following lines first,

import sys
sys.path.extend([r'/path/to/extraction_directory/'])

import pds4_tools

Example Usage

See also the User Manual.

pds4_read

Import via "import pds4_tools". You may then call pds4_tools.read() from your own code. The following is the docstring for pds4_tools.read():

        Reads PDS4 compliant data into a `StructureList`.

        Given a PDS4 label, reads the PDS4 data described in the label and
        associated label meta data into a `StructureList`, with each PDS4 data
        structure (e.g. Array_2D, Table_Binary, etc) as its own `Structure`. By
        default all data structures described in the label are immediately
        read into memory.

        Notes
        -----
        Python 2 v. Python 3: Non-data strings (label, meta data, etc)  in
        Python 2 will be decoded to ``unicode`` and in Python 3 they will
        be decoded to ``str``. The return type of all data strings is
        controlled by *decode_strings*.

        Remote URLs are downloaded into an on-disk cache which is cleared on
        Python interpreter exit.

        Parameters
        ----------
        filename : str or unicode
            The filename, including full or relative path, or a remote
            URL to the PDS4 label describing the data.
        quiet : bool, int or str, optional
            If True, suppresses all info/warnings from being output to stdout.
            Supports log-level style options for more fine grained control.
            Defaults to False.
        lazy_load : bool, optional
            If True, then the data of each PDS4 data structure will not be
            read-in to memory until the first attempt to access it. Additionally,
            for remote URLs, the data is not downloaded until first access.
            Defaults to False.
        no_scale : bool, optional
            If True, returned data will be exactly as written in the data file,
            ignoring offset or scaling values. Defaults to False.
        decode_strings : bool, optional
            If True, strings data types contained in the returned data will be
            decoded to the a unicode in Python 2, and to the str type in
            Python 3. If False, leaves string types as byte strings.
            Defaults to True.

        Returns
        -------
        StructureList
            Contains PDS4 data `Structure`'s, each of which contains the data,
            the meta data and the label portion describing that data structure.
            `StructureList` can be treated/accessed/used like a ``dict`` or
            ``list``.

        Examples
        --------

        Below we document how to read data described by an example label
        which has two data structures, an Array_2D_Image and a Table_Binary.
        An outline of the label, including the array and a table with 3
        fields, is given.

        >>> # Local file
        >>> struct_list = pds4_tools.read('/path/to/Example_Label.xml')

        >>> # Remote URL
        >>> struct_list = pds4_tools.read('https://url.com/Example_Label.xml')

        Example Label Outline::

           Array_2D_Image: unnamed
           Table_Binary: Observations
               Field: order
               Field: wavelength
               Group: unnamed
                   Field: pos_vector

        All below documentation assumes that the above outlined label,
        containing an array that does not have a name indicated in the label,
        and a table that has the name 'Observations' with 3 fields as shown,
        has been read-in.

        Accessing Example Structures:

            To access the data structures in `StructureList`, which is returned
            by `pds4_read()`, you may use any combination of ``dict``-like or
            ``list``-like access.

            >>> unnamed_array = struct_list[0]
            >>>              or struct_list['ARRAY_0']

            >>> obs_table = struct_list[1]
            >>>          or struct_list['Observations']

        Label or Structure Overview:

            To see a summary of the data structures, which for Arrays shows the
            type and dimensions of the array, and for Tables shows the type
            and number of fields, you may use the `StructureList.info()` method.
            Calling `Structure.info()` on a specific ``Structure`` instead will
            provide a more detailed summary, including all Fields for a table.

            >>> struct_list.info()
            >>> unnamed_array.info()
            >>> obs_table.info()

        Accessing Example Label data:

            To access the read-in data, as an array-like (subclass of ``ndarray``),
            you can use the data attribute for a PDS4 Array data structure, or
            list-like and the field() method to access a field for a table.

            >>> # PDS4 Arrays
            >>> unnamed_array.data

            >>> # PDS4 Table fields
            >>> obs_table['wavelength']
            >>> obs_table.field('wavelength')

            >>> # PDS4 Table records
            >>> obs_table[0:1000]

        Accessing Example Label meta data:

            You can access all meta data in the label for a given PDS4 data
            structure or field via the ``OrderedDict`` meta_data attribute. The
            below examples use the 'description' element.

            >>> unnamed_array.meta_data['description']

            >>> obs_table.field('wavelength').meta_data['description']
            >>> obs_table.field('pos_vector').meta_data['description']

        Accessing Example Label:

            The XML for a label is also accessible via the label attribute,
            either the entire label or for each PDS4 data structure.

            Entire label:
                >>> struct_list.label

            Part of label describing Observations table:
                >>> struct_list['Observations'].label
                >>> struct_list[1].label

            The returned object is similar to an ElementTree instance. It is
            searchable via `Label.find()` and `Label.findall()` methods and XPATH.
            Consult ``ElementTree`` manual for more details. For example,

            >>> struct_list.label.findall('.//disp:Display_Settings')

            Will find all elements in the entire label named 'Display_Settings'
            which are in the 'disp' prefix's namespace. You can additionally use the
            `Label.to_dict()` and `Label.to_string()` methods.

Usage is described above. A basic usage example is as follows:

""" Basic Reader example """

import pds4_tools

structures = pds4_tools.read('/path/to/label.xml')

structures.info()

0 - Array_3D_Spectrum 'table_name' (3 axes, 21 x 10 x 36)
1 - Table_Binary 'array_name' (5 fields x 1000 records)

# Table data access
table = structures['table_name'] # or
table = structures[0]

table.info()

field_data = table.field('field_name') # or
field_data = table.fields[0] 

record_data = table[0:50]

# Array data access
array = structures['array_name'] # or
array = structures[1]

array_data = array.data

# Meta-data access
field_meta = table.field('field_name').meta_data # or
field_meta = table.fields[0].meta_data
array_meta = array.meta_data

print field_meta['description']
print field_meta['unit']
print array_meta['local_identifier']

# Label access
label = structures.label # Full label
label = table.label      # Label section describing the table object

display_settings = label.findall('.//disp:Display_Settings')

display_dict = display_settings.to_dict()
label_dict = label.to_dict()
label_string = label.to_string()

pds4_viewer

Import via "import pds4_tools". To display the data structures (such as images, spectra, or tables) in a label you may then call pds4_tools.view() from the Python interpreter, with or without any arguments:

    Displays PDS4 compliant data in a GUI.

    Given a PDS4 label, displays PDS4 data described in the label and
    associated label meta data in a GUI. By default all data structures described
    in the label are read-in and displayed. Can be called without any
    parameters, opening a GUI that has a File->Open function to select
    desired label to be read-in and displayed.

    Parameters
    ----------
    filename : str or unicode, optional
        The filename, including full or relative path if necessary, of
        the PDS4 label describing the data to be viewed.
    from_existing_structures : StructureList, optional
        An existing StructureList, as returned by pds4_read(), to view. Takes
        precedence if given together with filename.
    lazy_load : bool, optional
        Do not read-in data of each data structure until attempt to view said
        data structure. Defaults to True.
    quiet : bool, int or str, optional
        Suppresses all info/warnings from being output and displayed. Supports
        log-level style options for more fine grained control. Defaults to False.

It is not necessary to include the filename parameter for pds4_tools.view, you may simplify call it without any options or arguments and a GUI will open from which you can open labels.

You may also call pds4_tools.view from another module or script. All the above arguments are available as optional named parameters. A basic example usage is as follows:

""" Basic Viewer example """

import pds4_tools

pds4_tools.view()

# or

pds4_tools.view('/path/to/label.xml')

# or 

struct_list = pds4_tools.view('label.xml')
pds4_tools.view(from_existing_structures=struct_list) # Won't re-read the data