Research Project — Colab Notebook

Last Updated: October 17, 2026 Download notebook (.ipynb)
  • Team Name: [Write in the name of your team.]
  • Authors: [Write in the names of the authors of this notebook.]

1 Dataset Overview

This notebook provides helper functions and examples for analyzing this semester's solar cell degradation data. All measurement data is stored in a single HDF5 file, data_<semester>.h5 (for example, data_fa26.h5 for Fall 2026), built by the Solar Cell Tracker.

Property Value
Cells One group per cell, named Cell followed by the cell's ID
Pixels per Cell 8 (numbered 1-8)
Measurements Power (one per cell), Current and IV (one per pixel), on each measurement date
Pixel Area 0.14 cm² (set by the aperture mask)

The file records which cells it holds, how they were stressed, their design factors and when they were measured. The Dataset Summary cell prints all of this for the file you load.

1.1 How to Use This Notebook

  1. Read the Understanding the HDF5 File section to see how the data is organized
  2. Load the dataset and execute the function definitions in the Defining Functions section
  3. Run the Dataset Summary to see what this semester's file holds
  4. Use the query functions to find cells with specific properties
  5. Retrieve data for analysis using the get_data functions
  6. Calculate metrics like EQE and PCE using the provided functions
  7. Visualize results with the plotting functions

2 Understanding the HDF5 File

Earlier in the course, you were introduced to HDF5 files when working with the LED spectra data. The research project dataset (data_<semester>.h5) uses the same format but is larger and more complex.

Recall that HDF5 files organize data hierarchically into groups (like folders) and datasets (like files), with attributes (metadata) at every level. The key difference from the LED spectra file is that the solar cell database has multiple levels of nesting: cells contain pixels, and each pixel contains multiple measurement types across multiple dates.

2.1 Structure of the Dataset File

data_<semester>.h5
attrs: Semester, Version, Built, Cells Left Out
+-- Cell<ID>/                        One group per solar cell
|   attrs: Stress Temperature, Stress Wavelength, design factors, ...
|   +-- Power/
|   |   +-- <YYYY_MM_DD>/            One group per measurement date
|   |       attrs: Measured By, Hours Under Stress, ...
|   |       +-- Data                 float64 array (n_wavelengths x 4)
|   |       +-- Headers              column names for the data array
|   +-- Pixel1/                      One group per pixel (1-8)
|   |   attrs: Stress Temperature, Stress Wavelength
|   |   +-- Current/
|   |   |   +-- <YYYY_MM_DD>/
|   |   |       +-- Data             float64 array (n_wavelengths x 4)
|   |   |       +-- Headers
|   |   +-- IV/
|   |       +-- <YYYY_MM_DD>/
|   |           +-- Data             float64 array (n_voltages x 7)
|   |           +-- Headers
|   +-- Pixel2/ ...
+-- Cell<ID>/ ...

To navigate this hierarchy, think of it like a file path. The IV data for one pixel of one cell, measured on one date, lives at:

Cell<ID>/Pixel<number>/IV/<YYYY_MM_DD>

The Dataset Summary cell picks an example measurement from the file and prints its path.

2.2 Data Columns

Each Data dataset is a numeric array. The Headers dataset tells you what each column means. The data include uncertainty information (mean, standard deviation, and number of measurements):

Measurement Columns
Power Wavelength (nm), Power_mean (uW), Power_std (uW), n
Current Wavelength (nm), Current_mean (nA), Current_std (nA), n
IV Voltage (V), Forward_mean (mA), Forward_std (mA), Forward_n, Reverse_mean (mA), Reverse_std (mA), Reverse_n

2.3 Attributes

Attributes record what the file knows at each level:

Level Attributes
File Semester, Version, Built, Cells Left Out
Cell Stress Temperature, Stress Wavelength, CU ID, Partner ID, Status, Teams, Stations, and the semester's design factors, such as Encapsulant
Pixel Stress Temperature, Stress Wavelength
Date group Measured By (a team such as 101-B, or TA or Staff), Session, Kept, File Name, Hours Under Stress, Station Setpoint, Measurement Temperature

The file is rebuilt as the semester goes on, so name its Version in your analysis. Hours Under Stress gives you the time axis directly. describe_dataset summarizes the file's attributes, read_metadata prints a cell's, and get_measurement_info returns a measurement's.

2.4 Accessing Data Directly

The helper functions defined in the next section handle data retrieval for you. But if you want to access the HDF5 file directly:

import h5py

with h5py.File(hdf5_path, 'r') as hdf:
    # List all cells
    print(list(hdf.keys()))

    # Read metadata for the file
    print(hdf.attrs['Version'])

    # Read metadata for a cell
    cell = hdf[f'Cell{example_cell}']
    print(cell.attrs['Stress Temperature'])
    print(cell.attrs['Stress Wavelength'])

    # List available dates for a pixel's IV data
    print(list(cell[f'Pixel{example_pixel}/IV'].keys()))

    # Load a specific dataset
    group = cell[f'Pixel{example_pixel}/IV/{example_date}']
    data = group['Data'][:]                    # numpy array
    headers = [h.decode('utf-8') for h in group['Headers'][:]]
    print(group.attrs['Hours Under Stress'])

3 Defining Functions

The functions in the cell below will assist you in retrieving the information you need from the HDF5 file. These functions are designed to help you access specific datasets, filter data based on metadata, and calculate metrics directly from the data stored in the HDF5 file.

You should not need to make any edits to the functions in this cell.

3.0.1 Simply execute the cell below to define the functions, HIDE THE CELL OUTPUT, and move on to using them in your analysis.

However, we have provided detailed comments within the functions to help you understand what each function is doing and how it works. Feel free to review the comments if you are interested in learning more about the implementation.

If you want to access or run only a portion of the code included here, below is a list of the functions included:

  1. read_metadata - Read metadata for a given cell
  2. find_cells_with_stress_temperature - Find cells by stress temperature
  3. find_cells_with_stress_wavelength - Find cells by stress wavelength
  4. find_cells_with_pixel_number - Find cells with a specific pixel number
  5. plot_iv_data - Plot IV data for a cell/pixel/date
  6. list_data_for_cell - List all measurements for a cell
  7. list_data_for_cell_date_match - List measurements where Current, IV, and Power have matching dates
  8. get_power_data - Retrieve Power data
  9. get_current_data - Retrieve Current data
  10. get_iv_data - Retrieve IV data
  11. retrieve_and_store_data - Batch retrieve and store data
  12. get_data_from_hdf5 - Retrieve data for a given group path
  13. calculate_eqe - Calculate EQE curve
  14. get_all_dates - Get all available dates for a cell/pixel
  15. plot_eqe_over_time - Plot EQE curves over time
  16. calculate_jsc - Calculate short circuit current density
  17. calculate_voc - Calculate open circuit voltage
  18. calculate_v_pmax - Calculate voltage at max power point
  19. calculate_j_pmax - Calculate current density at max power point
  20. calculate_fill_factor - Calculate fill factor
  21. calculate_pce - Calculate power conversion efficiency
  22. convert_iv_to_jv - Convert IV to JV data
  23. get_measurement_info - Read the attributes of one measurement (who measured it, hours under stress, ...)
  24. describe_dataset - Summarize the file: its version, cells, dates, stress conditions and design factors
  25. pick_example - Choose an example cell, pixel and date with a clean J-V curve

4 Load the Dataset

Upload the dataset file (data_<semester>.h5) to the same folder as this notebook (in Colab, the Files panel on the left). The cell below finds it. If the file is somewhere else, such as your Google Drive, set hdf5_path to its path instead.

# === DATASET ===
import glob

hdf5_path = None  # Set this to the file's path if it is not in this notebook's folder.
if hdf5_path is None:
    hdf5_files = sorted(glob.glob('data_*.h5'))
    if len(hdf5_files) != 1:
        raise FileNotFoundError(f'Expected one data_*.h5 file in this folder, found {hdf5_files}. Upload the dataset, or set hdf5_path.')
    hdf5_path = hdf5_files[0]
print(f'Dataset: {hdf5_path}')

pixel_area = 0.14  # cm^2, set by the aperture mask
# ============================================================================
# IMPORT LIBRARIES
# ============================================================================
import h5py              # For reading HDF5 files
import matplotlib.pyplot as plt  # For creating plots and visualizations
import pandas as pd      # For working with tabular data (DataFrames)
import numpy as np       # For numerical operations and calculations

# Physical constants used for EQE calculations
h = 6.62607015e-34   # Planck's constant in J·s (joule-seconds)
c = 2.998e8          # Speed of light in m/s (meters per second)
e = 1.602176634e-19  # Elementary charge in C (coulombs)


# ============================================================================
# HELPER: FORMAT CELL ID
# ============================================================================

def _cell_group(cell):
    """Convert a cell identifier to its HDF5 group name.

    Adds the 'Cell' prefix and upper-cases the ID.
    """
    return f"Cell{str(cell).upper()}"


# ============================================================================
# METADATA QUERY FUNCTIONS
# ============================================================================

def read_metadata(hdf5_path, cell_number):
    """
    Read and display metadata for a given cell from the HDF5 file.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file containing the solar cell data.
    cell_number : str
        Cell ID, without the 'Cell' prefix (e.g., example_cell).

    Example:
    --------
    read_metadata(hdf5_path, example_cell)
    """
    cell_group_name = _cell_group(cell_number)

    with h5py.File(hdf5_path, 'r') as hdf:
        cell_group = hdf.get(cell_group_name)

        if cell_group is None:
            print(f"{cell_group_name} not found in the HDF5 file.")
            return

        print(f"Metadata for {cell_group_name}:")
        if cell_group.attrs:
            for key, value in cell_group.attrs.items():
                print(f"  {key}: {value}")
        else:
            print("  No metadata found.")


def find_cells_with_stress_temperature(hdf5_path, target_temperature):
    """
    Find all cells with a specific stress temperature.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    target_temperature : float or str
        Target stress temperature in degrees Celsius (e.g., 55).

    Returns:
    --------
    list
        List of cell group names that match (e.g., ['Cell<ID>', ...]).

    Example:
    --------
    cells_at_55C = find_cells_with_stress_temperature(hdf5_path, 55)
    """
    cells_with_target_temp = []

    with h5py.File(hdf5_path, 'r') as hdf:
        for cell in hdf.keys():
            cell_group = hdf[cell]
            if 'Stress Temperature' in cell_group.attrs:
                try:
                    stress_temp = float(cell_group.attrs['Stress Temperature'])
                    if stress_temp == float(target_temperature):
                        cells_with_target_temp.append(cell)
                except ValueError:
                    print(f"Warning: Could not convert Stress Temperature for {cell}")

    return cells_with_target_temp


def find_cells_with_stress_wavelength(hdf5_path, target_wavelength):
    """
    Find all cells with a specific stress wavelength.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    target_wavelength : str
        Target stress wavelength (e.g., 'White').

    Returns:
    --------
    list
        List of cell group names that match.

    Example:
    --------
    white_light_cells = find_cells_with_stress_wavelength(hdf5_path, 'White')
    """
    cells_with_target_wavelength = []

    with h5py.File(hdf5_path, 'r') as hdf:
        for cell in hdf.keys():
            cell_group = hdf[cell]
            if 'Stress Wavelength' in cell_group.attrs:
                if str(cell_group.attrs['Stress Wavelength']).lower() == str(target_wavelength).lower():
                    cells_with_target_wavelength.append(cell)

    return cells_with_target_wavelength


def find_cells_with_pixel_number(hdf5_path, target_pixel_number):
    """
    Find all cells that have data for a specific pixel number.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    target_pixel_number : int
        Target pixel number (1-8).

    Returns:
    --------
    list
        List of cell group names that have the target pixel.

    Example:
    --------
    cells_with_pixel_5 = find_cells_with_pixel_number(hdf5_path, 5)
    """
    cells_with_target_pixel = []

    with h5py.File(hdf5_path, 'r') as hdf:
        for cell in hdf.keys():
            cell_group = hdf[cell]
            for pixel in cell_group.keys():
                if pixel == f'Pixel{target_pixel_number}':
                    cells_with_target_pixel.append(cell)
                    break

    return cells_with_target_pixel


def get_measurement_info(hdf5_path, cell, pixel, kind, date):
    """What the file says of one measurement. kind is 'IV', 'Current' or 'Power' (pixel None for Power)."""
    path = f'{_cell_group(cell)}/Power/{date}' if kind == 'Power' else f'{_cell_group(cell)}/Pixel{pixel}/{kind}/{date}'
    with h5py.File(hdf5_path, 'r') as hdf:
        return dict(hdf[path].attrs) if path in hdf else None


def describe_dataset(hdf5_path, max_groups=6):
    """
    Print a summary of the dataset: the file's own attributes, its cells and
    measurement dates, and each cell attribute that sorts the cells into a few
    groups (stress conditions and design factors), with the number of cells in each.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    max_groups : int
        Cell attributes with more distinct values than this (IDs, teams) are not listed.

    Example:
    --------
    describe_dataset(hdf5_path)
    """
    with h5py.File(hdf5_path, 'r') as hdf:
        print(f'Dataset: {hdf5_path}')
        for key, value in hdf.attrs.items():
            print(f'  {key}: {value}')

        cells = sorted(name for name in hdf.keys() if name.startswith('Cell'))
        if not cells:
            print('No cells found.')
            return
        print(f'\nCells: {len(cells)}, {cells[0][4:]} to {cells[-1][4:]}')

        dates = set()
        values = {}
        for name in cells:
            cell_group = hdf[name]
            for key, value in cell_group.attrs.items():
                values.setdefault(key, []).append(str(value))
            for pixel in cell_group.keys():
                if pixel == 'Power':
                    dates.update(cell_group[pixel].keys())
                else:
                    for kind in cell_group[pixel].keys():
                        dates.update(cell_group[pixel][kind].keys())
        if dates:
            print(f'Measured: {min(dates)} to {max(dates)} ({len(dates)} dates)')

        print('\nCells by attribute:')
        for key, vals in values.items():
            counts = pd.Series(vals).value_counts()
            if len(counts) <= max_groups:
                print(f'  {key}: ' + ', '.join(f'{v} ({n})' for v, n in counts.items()))


def pick_example(hdf5_path):
    """
    Choose an example measurement from the file: the pixel with clean J-V curves
    on the most dates that also have Power and Current data at matching
    wavelengths (so EQE can be calculated), and the first of those dates.

    Returns:
    --------
    tuple or None
        (cell, pixel, date): a cell ID, a pixel number and a 'YYYY_MM_DD' date.

    Example:
    --------
    example_cell, example_pixel, example_date = pick_example(hdf5_path)
    """
    def clean(group):
        headers = [h.decode('utf-8') for h in group['Headers'][:]]
        jv_data = convert_iv_to_jv(pd.DataFrame(group['Data'][:], columns=headers))
        scan = 'Reverse Scan (mA/cm^2)'
        try:
            jsc = calculate_jsc(jv_data, scan)
            voc = calculate_voc(jv_data, scan)
            ff = (calculate_v_pmax(jv_data, scan) * calculate_j_pmax(jv_data, scan)) / (jsc * voc)
        except (IndexError, ZeroDivisionError):
            return False
        return jsc > 0 and voc > 0 and 0 < ff < 1

    best = None
    with h5py.File(hdf5_path, 'r') as hdf:
        for name in sorted(hdf.keys()):
            cell_group = hdf[name]
            if 'Power' not in cell_group:
                continue
            for pixel in range(1, 9):
                pixel_group = cell_group.get(f'Pixel{pixel}')
                if pixel_group is None or 'Current' not in pixel_group or 'IV' not in pixel_group:
                    continue
                dates = sorted(set(cell_group['Power']) & set(pixel_group['Current']) & set(pixel_group['IV']))
                dates = [d for d in dates
                         if np.array_equal(cell_group['Power'][d]['Data'][:, 0], pixel_group['Current'][d]['Data'][:, 0])
                         and clean(pixel_group['IV'][d])]
                if dates and (best is None or len(dates) > len(best[2])):
                    best = (name[4:], pixel, dates)

    if best is None:
        print('No pixel has Power and Current at matching wavelengths and a clean IV curve on the same date.')
        return None
    return best[0], best[1], best[2][0]


# ============================================================================
# DATA LISTING FUNCTIONS
# ============================================================================

def list_data_for_cell(hdf5_path, cell_number):
    """
    List all measurement data available for a given cell.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    cell_number : str
        Cell ID (e.g., example_cell).

    Example:
    --------
    list_data_for_cell(hdf5_path, example_cell)
    """
    cell_group_name = _cell_group(cell_number)
    dataset_list = []

    with h5py.File(hdf5_path, 'r') as hdf:
        cell_group = hdf.get(cell_group_name)
        if cell_group is None:
            print(f"{cell_group_name} not found in the HDF5 file.")
            return dataset_list

        print(f"Listing all measurement data for {cell_group_name}:")

        for pixel in cell_group.keys():
            if pixel == 'Power':
                print(f"Power:")
                power_group = cell_group[pixel]
                for dataset in power_group.keys():
                    print(f"  Dataset: {dataset}")
            else:
                print(f"Pixel: {pixel}")
                pixel_group = cell_group[pixel]
                for group in pixel_group.keys():
                    print(f"  Group: {group}")
                    data_group = pixel_group[group]
                    for dataset in data_group.keys():
                        print(f"    Dataset: {dataset}")

    return dataset_list


def list_data_for_cell_date_match(hdf5_path, cell_number):
    """
    List measurement data where Current, IV, and Power all have the same date.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    cell_number : str
        Cell ID (e.g., example_cell).

    Example:
    --------
    list_data_for_cell_date_match(hdf5_path, example_cell)
    """
    cell_group_name = _cell_group(cell_number)
    dataset_list = []

    with h5py.File(hdf5_path, 'r') as hdf:
        cell_group = hdf.get(cell_group_name)
        if cell_group is None:
            print(f"{cell_group_name} not found in the HDF5 file.")
            return dataset_list

        print(f"Listing measurement data with common dates for {cell_group_name}:")

        current_dates = set()
        iv_dates = set()
        power_dates = set()

        for pixel in cell_group.keys():
            if pixel == 'Power':
                power_dates = set(cell_group[pixel].keys())
            else:
                pixel_group = cell_group[pixel]
                if 'Current' in pixel_group:
                    current_dates.update(pixel_group['Current'].keys())
                if 'IV' in pixel_group:
                    iv_dates.update(pixel_group['IV'].keys())

        common_dates = current_dates & iv_dates & power_dates

        for date in sorted(common_dates):
            print(f"Common Date: {date}")
            for pixel in cell_group.keys():
                if pixel != 'Power':
                    pixel_group = cell_group[pixel]
                    if ('Current' in pixel_group and date in pixel_group['Current'] and
                        'IV' in pixel_group and date in pixel_group['IV']):
                        print(f"  {pixel}")

    return dataset_list


# ============================================================================
# DATA RETRIEVAL FUNCTIONS
# ============================================================================

def get_power_data(hdf5_path, cell_number, date):
    """
    Retrieve Power data for a given cell and date.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    cell_number : str
        Cell ID (e.g., example_cell).
    date : str
        Date in 'YYYY_MM_DD' format (e.g., example_date).

    Returns:
    --------
    pd.DataFrame or None
        DataFrame with columns ['Wavelength (nm)', 'Power_mean (uW)', 'Power_std (uW)', 'n'].

    Example:
    --------
    power_df = get_power_data(hdf5_path, example_cell, example_date)
    """
    cell_group_name = _cell_group(cell_number)

    with h5py.File(hdf5_path, 'r') as hdf:
        group_path = f'{cell_group_name}/Power/{date}'
        if group_path in hdf:
            group = hdf[group_path]
            data = group['Data'][:]
            headers = [h.decode('utf-8') for h in group['Headers'][:]]
            return pd.DataFrame(data, columns=headers)
        else:
            print(f"Power data for {cell_group_name} on {date} not found.")
            return None


def get_current_data(hdf5_path, cell_number, pixel_number, date):
    """
    Retrieve Current data for a specific cell, pixel, and date.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    cell_number : str
        Cell ID (e.g., example_cell).
    pixel_number : int
        Pixel number (1-8).
    date : str
        Date in 'YYYY_MM_DD' format.

    Returns:
    --------
    pd.DataFrame or None
        DataFrame with columns ['Wavelength (nm)', 'Current_mean (nA)', 'Current_std (nA)', 'n'].

    Example:
    --------
    current_df = get_current_data(hdf5_path, example_cell, example_pixel, example_date)
    """
    cell_group_name = _cell_group(cell_number)
    pixel_number = str(pixel_number)

    with h5py.File(hdf5_path, 'r') as hdf:
        group_path = f'{cell_group_name}/Pixel{pixel_number}/Current/{date}'
        if group_path in hdf:
            group = hdf[group_path]
            data = group['Data'][:]
            headers = [h.decode('utf-8') for h in group['Headers'][:]]
            return pd.DataFrame(data, columns=headers)
        else:
            print(f"Current data for {cell_group_name}, Pixel{pixel_number} on {date} not found.")
            return None


def get_iv_data(hdf5_path, cell_number, pixel_number, date):
    """
    Retrieve IV data for a specific cell, pixel, and date.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    cell_number : str
        Cell ID (e.g., example_cell).
    pixel_number : int
        Pixel number (1-8).
    date : str
        Date in 'YYYY_MM_DD' format.

    Returns:
    --------
    pd.DataFrame or None
        DataFrame with columns:
        ['Voltage (V)', 'Forward_mean (mA)', 'Forward_std (mA)', 'Forward_n',
         'Reverse_mean (mA)', 'Reverse_std (mA)', 'Reverse_n']

    Example:
    --------
    iv_df = get_iv_data(hdf5_path, example_cell, example_pixel, example_date)
    """
    cell_group_name = _cell_group(cell_number)
    pixel_number = str(pixel_number)

    with h5py.File(hdf5_path, 'r') as hdf:
        group_path = f'{cell_group_name}/Pixel{pixel_number}/IV/{date}'
        if group_path in hdf:
            group = hdf[group_path]
            data = group['Data'][:]
            headers = [h.decode('utf-8') for h in group['Headers'][:]]
            return pd.DataFrame(data, columns=headers)
        else:
            print(f"IV data for {cell_group_name}, Pixel{pixel_number} on {date} not found.")
            return None


def retrieve_and_store_data(hdf5_path, cell_pixel_date_info):
    """
    Batch retrieve and store data from the HDF5 file as global variables.

    Creates global variables like:
    - cell<ID>_power_<YYYY_MM_DD>
    - cell<ID>_pixel<number>_current_<YYYY_MM_DD>
    - cell<ID>_pixel<number>_iv_<YYYY_MM_DD>

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    cell_pixel_date_info : dict
        Dictionary with structure:
        {
            example_cell: {
                'pixels': [1, example_pixel],
                'dates': [example_date]
            }
        }

    Example:
    --------
    info = {example_cell: {'pixels': [1, example_pixel], 'dates': [example_date]}}
    retrieve_and_store_data(hdf5_path, info)
    """
    stored = []
    for cell, info in cell_pixel_date_info.items():
        pixels = info['pixels']
        dates = info['dates']

        for pixel in pixels:
            for date in dates:
                power_data = get_power_data(hdf5_path, cell, date)
                if power_data is not None:
                    var_name = f'cell{cell}_power_{date}'
                    globals()[var_name] = power_data
                    stored.append(var_name)

                current_data = get_current_data(hdf5_path, cell, pixel, date)
                if current_data is not None:
                    var_name = f'cell{cell}_pixel{pixel}_current_{date}'
                    globals()[var_name] = current_data
                    stored.append(var_name)

                iv_data = get_iv_data(hdf5_path, cell, pixel, date)
                if iv_data is not None:
                    var_name = f'cell{cell}_pixel{pixel}_iv_{date}'
                    globals()[var_name] = iv_data
                    stored.append(var_name)

    print(f'Stored {len(stored)} variables:')
    for name in stored:
        print(f'  {name}')


def get_data_from_hdf5(hdf5_path, group_path):
    """
    Generic function to retrieve data from any HDF5 group path.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    group_path : str
        Full path within the HDF5 file (e.g., 'Cell<ID>/Pixel<number>/Current/<YYYY_MM_DD>').

    Returns:
    --------
    pd.DataFrame or None
    """
    with h5py.File(hdf5_path, 'r') as hdf:
        if group_path in hdf:
            group = hdf[group_path]
            data = group['Data'][:]
            headers = [h.decode('utf-8') for h in group['Headers'][:]]
            return pd.DataFrame(data, columns=headers)
        else:
            print(f"Data for {group_path} not found.")
            return None


# ============================================================================
# EQE CALCULATION FUNCTIONS
# ============================================================================

def calculate_eqe(hdf5_path, cell, pixel, date):
    """
    Calculate the External Quantum Efficiency (EQE) for a given cell/pixel/date.

    EQE = (I * h * c) / (P * \u03bb * e) * 100%%

    Handles unit conversion: power is stored in \u03bcW, current in nA.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    cell : str
        Cell ID (e.g., example_cell).
    pixel : int
        Pixel number (1-8).
    date : str
        Date in 'YYYY_MM_DD' format.

    Returns:
    --------
    pd.DataFrame or None
        DataFrame with columns ['Wavelength (nm)', 'EQE (%)'].

    Example:
    --------
    eqe_df = calculate_eqe(hdf5_path, example_cell, example_pixel, example_date)
    """
    cell_group_name = _cell_group(cell)
    pixel_number = str(pixel)

    power_group_path = f'{cell_group_name}/Power/{date}'
    current_group_path = f'{cell_group_name}/Pixel{pixel_number}/Current/{date}'

    power_data = get_data_from_hdf5(hdf5_path, power_group_path)
    current_data = get_data_from_hdf5(hdf5_path, current_group_path)

    if power_data is None or current_data is None:
        return None

    if not power_data['Wavelength (nm)'].equals(current_data['Wavelength (nm)']):
        print("Wavelengths do not match between Power and Current datasets.")
        return None

    wavelength = power_data['Wavelength (nm)']        # nm
    power_uW = power_data['Power_mean (uW)']           # microwatts
    current_nA = current_data['Current_mean (nA)']      # nanoamps

    # Convert to SI units for EQE calculation
    power_W = power_uW * 1e-6      # uW -> W
    current_A = current_nA * 1e-9   # nA -> A
    wavelength_m = wavelength * 1e-9  # nm -> m

    # EQE = (I * h * c) / (P * lambda * e) * 100%
    eqe = (current_A * h * c) / (power_W * wavelength_m * e) * 100

    return pd.DataFrame({'Wavelength (nm)': wavelength, 'EQE (%)': eqe})


def get_all_dates(hdf5_path, cell, pixel):
    """
    Retrieve all available measurement dates for a given cell and pixel.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    cell : str
        Cell ID (e.g., example_cell).
    pixel : int
        Pixel number (1-8).

    Returns:
    --------
    list
        Sorted list of dates in 'YYYY_MM_DD' format.

    Example:
    --------
    dates = get_all_dates(hdf5_path, example_cell, example_pixel)
    """
    cell_group_name = _cell_group(cell)
    pixel_number = str(pixel)
    dates = set()

    with h5py.File(hdf5_path, 'r') as hdf:
        power_path = f'{cell_group_name}/Power'
        current_path = f'{cell_group_name}/Pixel{pixel_number}/Current'

        if power_path in hdf:
            dates.update(hdf[power_path].keys())
        if current_path in hdf:
            dates.update(hdf[current_path].keys())

    return sorted(dates)


# ============================================================================
# PLOTTING FUNCTIONS
# ============================================================================

def plot_iv_data(hdf5_path, cell, pixel, date):
    """
    Plot IV curves (forward and reverse mean scans) for a cell/pixel/date.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    cell : str
        Cell ID (e.g., example_cell).
    pixel : int
        Pixel number (1-8).
    date : str
        Date in 'YYYY_MM_DD' format.

    Example:
    --------
    plot_iv_data(hdf5_path, example_cell, example_pixel, example_date)
    """
    cell_group_name = _cell_group(cell)

    with h5py.File(hdf5_path, 'r') as hdf:
        group_path = f'{cell_group_name}/Pixel{pixel}/IV/{date}'

        if group_path in hdf:
            group = hdf[group_path]
            data = group['Data'][:]
            headers = [h.decode('utf-8') for h in group['Headers'][:]]

            df = pd.DataFrame(data, columns=headers)

            plt.figure(figsize=(10, 6))
            plt.plot(df['Voltage (V)'], df['Forward_mean (mA)'], label='Forward Scan (mA)')
            plt.plot(df['Voltage (V)'], df['Reverse_mean (mA)'], label='Reverse Scan (mA)')
            plt.xlabel('Voltage (V)')
            plt.ylabel('Current (mA)')
            plt.title(f'IV Data for {cell_group_name}, Pixel {pixel} on {date}')
            plt.legend()
            plt.grid(True)
            plt.show()
        else:
            print(f"No IV data found for {cell_group_name}, Pixel {pixel} on {date}")


def plot_eqe_over_time(hdf5_path, cell, pixel):
    """
    Plot EQE curves over time for a given cell and pixel.

    Parameters:
    -----------
    hdf5_path : str
        Path to the HDF5 file.
    cell : str
        Cell ID (e.g., example_cell).
    pixel : int
        Pixel number (1-8).

    Example:
    --------
    plot_eqe_over_time(hdf5_path, example_cell, example_pixel)
    """
    dates = get_all_dates(hdf5_path, cell, pixel)

    if not dates:
        print(f"No dates found for {_cell_group(cell)}, Pixel {pixel}.")
        return

    plt.figure(figsize=(10, 6))

    for date in dates:
        eqe_data = calculate_eqe(hdf5_path, cell, pixel, date)
        if eqe_data is not None:
            plt.plot(eqe_data['Wavelength (nm)'], eqe_data['EQE (%)'], label=f'Date: {date}')

    plt.xlabel('Wavelength (nm)')
    plt.ylabel('EQE (%)')
    plt.title(f'EQE Curves for {_cell_group(cell)}, Pixel {pixel} Over Time')
    plt.legend()
    plt.grid(True)
    plt.show()


# ============================================================================
# SOLAR CELL PERFORMANCE CALCULATION FUNCTIONS
# ============================================================================

def calculate_jsc(jv_data, scan_type):
    """
    Calculate Short Circuit Current Density (Jsc) from JV data.

    Jsc is the current density when voltage = 0V.

    Parameters:
    -----------
    jv_data : pd.DataFrame
        DataFrame with 'Voltage (V)' and current density columns.
    scan_type : str
        Column name for the scan (e.g., 'Forward Scan (mA/cm^2)' or 'Reverse Scan (mA/cm^2)').

    Returns:
    --------
    float
        Jsc in mA/cm^2.
    """
    jsc_index = jv_data.index[jv_data['Voltage (V)'] == 0]
    jsc = abs(jv_data.loc[jsc_index, scan_type].values[0])
    return jsc


def calculate_voc(jv_data, scan_type):
    """
    Calculate Open Circuit Voltage (Voc) from JV data.

    Voc is the voltage when current = 0A. Uses interpolation.

    Parameters:
    -----------
    jv_data : pd.DataFrame
        DataFrame containing JV data.
    scan_type : str
        Column name for the scan type.

    Returns:
    --------
    float
        Voc in V.
    """
    voc = np.interp(0, jv_data[scan_type], jv_data['Voltage (V)'])
    return voc


def calculate_v_pmax(jv_data, scan_type):
    """
    Calculate voltage at the maximum power point (V_pmax).

    Parameters:
    -----------
    jv_data : pd.DataFrame
        DataFrame containing JV data.
    scan_type : str
        Column name for the scan type.

    Returns:
    --------
    float
        V_pmax in V.
    """
    jv_data['Power (mW/cm^2)'] = jv_data['Voltage (V)'] * jv_data[scan_type]
    pmax_index = np.argmin(jv_data['Power (mW/cm^2)'])
    v_pmax = jv_data.loc[pmax_index, 'Voltage (V)']
    return v_pmax


def calculate_j_pmax(jv_data, scan_type):
    """
    Calculate current density at the maximum power point (J_pmax).

    Parameters:
    -----------
    jv_data : pd.DataFrame
        DataFrame containing JV data.
    scan_type : str
        Column name for the scan type.

    Returns:
    --------
    float
        J_pmax in mA/cm^2.
    """
    jv_data['Power (mW/cm^2)'] = jv_data['Voltage (V)'] * jv_data[scan_type]
    pmax_index = np.argmin(jv_data['Power (mW/cm^2)'])
    j_pmax = abs(jv_data.loc[pmax_index, scan_type])
    return j_pmax


def calculate_fill_factor(jsc, voc, v_pmax, j_pmax):
    """
    Calculate Fill Factor: FF = (V_pmax * J_pmax) / (Voc * Jsc)

    Parameters:
    -----------
    jsc, voc, v_pmax, j_pmax : float
        Solar cell parameters.

    Returns:
    --------
    float
        Fill Factor (dimensionless, typically 0-1).
    """
    ff = (v_pmax * j_pmax) / (jsc * voc)
    if not 0 < ff < 1:
        print(f'Warning: a fill factor of {ff:.2f} is outside 0 to 1. The curve may have a glitch: plot it with plot_iv_data.')
    return ff


def calculate_pce(jsc, voc, ff):
    """
    Calculate Power Conversion Efficiency (PCE).

    PCE = (Jsc * Voc * FF) / P_incident * 100%%

    Parameters:
    -----------
    jsc : float
        Short Circuit Current Density in mA/cm^2.
    voc : float
        Open Circuit Voltage in V.
    ff : float
        Fill Factor.

    Returns:
    --------
    float
        PCE as a percentage.
    """
    incident_power = 99.8  # mW/cm^2
    max_power_output = jsc * voc * ff
    pce = (max_power_output / incident_power) * 100
    return pce


def convert_iv_to_jv(iv_data, area=0.14):
    """
    Convert IV data (current in mA) to JV data (current density in mA/cm^2).

    Parameters:
    -----------
    iv_data : pd.DataFrame
        DataFrame with columns including 'Forward_mean (mA)' and 'Reverse_mean (mA)'.
    area : float
        Active pixel area in cm^2 (default: 0.14 cm^2).

    Returns:
    --------
    pd.DataFrame
        DataFrame with 'Forward Scan (mA/cm^2)' and 'Reverse Scan (mA/cm^2)' columns.

    Example:
    --------
    jv_data = convert_iv_to_jv(iv_data, area=0.14)
    """
    iv_data['Forward Scan (mA/cm^2)'] = iv_data['Forward_mean (mA)'] / area
    iv_data['Reverse Scan (mA/cm^2)'] = iv_data['Reverse_mean (mA)'] / area
    jv_data = iv_data[['Voltage (V)', 'Forward Scan (mA/cm^2)', 'Reverse Scan (mA/cm^2)']].copy()
    return jv_data

5 Dataset Summary

The cell below prints what this semester's file holds, then picks an example measurement for the examples that follow: a cell, pixel and date with Power and Current at matching wavelengths, so EQE can be calculated, and a clean IV curve. To run the examples on a different measurement, set example_cell, example_pixel and example_date yourself.

describe_dataset(hdf5_path)

example_cell, example_pixel, example_date = pick_example(hdf5_path)
print(f'\nExample measurement: Cell{example_cell}/Pixel{example_pixel}/IV/{example_date}')

6 Query Cell Metadata

read_metadata(hdf5_path, example_cell)

7 Query Temperature Metadata

# Example usage — Find the cells stressed at one temperature
target_temperature = 55  # one of the Stress Temperature values in the Dataset Summary
cells = find_cells_with_stress_temperature(hdf5_path, target_temperature)
print(f'Cells with stress temperature {target_temperature}°C: {cells}')

8 Query Wavelength Metadata

# Example usage — Find the cells stressed with one wavelength
target_wavelength = 'White'  # one of the Stress Wavelength values in the Dataset Summary; white light is stored as 'White'
cells = find_cells_with_stress_wavelength(hdf5_path, target_wavelength)
print(f'Cells with stress wavelength {target_wavelength}: {cells}')

9 Query Pixel Number

# Example usage — Find all cells with pixel 6 data
target_pixel_number = 6
cells = find_cells_with_pixel_number(hdf5_path, target_pixel_number)
print(f'Cells with Pixel {target_pixel_number}: {cells}')

10 Query All Measurement Data for a Cell

This will return a list all measurements for a given cell number that exist in the HDF5 file.

dataset_list = list_data_for_cell(hdf5_path, example_cell)
for item in dataset_list:
    print(item)

11 Query Measurement Data with a Common Date for a Cell

This will return a list of measurements for a given cell number that have matching dates, grouped by date. If a pixel is listed under that date, then there exists a complete set of measurements (current, power, and IV) for that pixel on that date.

dataset_list = list_data_for_cell_date_match(hdf5_path, example_cell)
for item in dataset_list:
    print(item)

12 Getting Data from a single Cell/Pixel/Date

# Get Power data (one per cell)
power_data = get_power_data(hdf5_path, example_cell, example_date)
print('Power data:')
print(power_data)

# Get Current data (per pixel)
current_data = get_current_data(hdf5_path, example_cell, example_pixel, example_date)
print()
print('Current data:')
print(current_data)

# Get IV data (per pixel)
iv_data = get_iv_data(hdf5_path, example_cell, example_pixel, example_date)
print()
print('IV data:')
print(iv_data)

13 Getting Data from Multiple Cells/Pixels/Dates

cell_pixel_date_info = {
    example_cell: {
        'pixels': [1, example_pixel],
        'dates': [example_date]
    }
}

retrieve_and_store_data(hdf5_path, cell_pixel_date_info)

14 Calculate EQE for a given cell/pixel/date

eqe_data = calculate_eqe(hdf5_path, example_cell, example_pixel, example_date)
print(eqe_data)

15 Plot EQE over time

plot_eqe_over_time(hdf5_path, example_cell, example_pixel)

16 Plot IV Data

plot_iv_data(hdf5_path, example_cell, example_pixel, example_date)
# Retrieve data for all pixels on the example cell/date
cell_pixel_date_info = {
    example_cell: {
        'pixels': [1, 2, 3, 4, 5, 6, 7, 8],
        'dates': [example_date]
    }
}

retrieve_and_store_data(hdf5_path, cell_pixel_date_info)

# Calculate PCE for one pixel
iv_data = get_iv_data(hdf5_path, example_cell, example_pixel, example_date)
if iv_data is not None:
    jv_data = convert_iv_to_jv(iv_data, area=pixel_area)

    scan = 'Reverse Scan (mA/cm^2)'
    jsc = calculate_jsc(jv_data, scan)
    voc = calculate_voc(jv_data, scan)
    v_pmax = calculate_v_pmax(jv_data, scan)
    j_pmax = calculate_j_pmax(jv_data, scan)
    ff = calculate_fill_factor(jsc, voc, v_pmax, j_pmax)
    pce = calculate_pce(jsc, voc, ff)

    print(f'Cell {example_cell}, Pixel {example_pixel}, Date {example_date}')
    print(f'  Jsc = {jsc:.4f} mA/cm^2')
    print(f'  Voc = {voc:.4f} V')
    print(f'  V_pmax = {v_pmax:.4f} V')
    print(f'  J_pmax = {j_pmax:.4f} mA/cm^2')
    print(f'  FF = {ff:.4f}')
    print(f'  PCE = {pce:.4f} %')

18 Start your work here

# Start your code here

19 Author Contributions (required)

List the name of each team member and please describe briefly how each member contributed to the work on the research project.

20 Use of AI (required)

  1. How your team used AI tools: Describe the specific tasks where AI-assisted tools were involved. For example, did AI help with writing, debugging, optimizing, or refining your code? Which components of the analysis did your team use AI on?
  2. When your team used AI tools: Specify at what stage(s) of your programming process you used AI. Was it during initial code development, troubleshooting, etc.?
  3. Which AI tools your team used: Identify the AI tools or platforms your team consulted (e.g., ChatGPT, GitHub Copilot, etc.).