25  KPI Module Development

In this assignment, you will enhance your understanding of Python project organization by adding a Key Performance Indicator (KPI) function to an existing module within a Python package. The focus is on developing a function to calculate a KPI relevant to industrial engineering, specifically within the Production and Logistics Management (PLM) specialization of the MSc Industrial Engineering and Management (IEM) program.

The module files for each orientation already exist in the project. Your task is to select a KPI and add it to the appropriate module.

25.1 Objectives

  • Understand Python project structure and file organization.
  • Add a KPI function to an existing Python module within a package.
  • Write unit tests using pytest.
  • Document and use your KPI in a Jupyter Notebook.
  • Use GitHub Desktop to manage and submit your code.

25.2 Prerequisites

  • Basic knowledge of Python programming.
  • GitHub Desktop installed on your computer.
  • Access to the shared GitHub repository.
  • Python environment set up with pytest and Jupyter Notebook (.ipynb files).

25.3 Part 1: Setting Up the Project

To work on this assignment, you need to clone the shared repository and set up your local development environment. We will use GitHub Desktop to manage the repository and Visual Studio Code (VS Code) as the code editor.

25.3.1 Step 1: Clone the Shared Repository

We are already collaborating on a shared repository, but if you haven’t cloned it yet, you can do so using GitHub Desktop. To get started, follow these steps to clone the shared repository to your local machine:

  1. Open GitHub Desktop:
    • Launch the GitHub Desktop application on your computer.
  2. Clone Repository:
    • Click on File > Clone Repository.
    • In the URL tab, paste the repository link provided to you (via email).
    • Choose a local path where you want to store the project.
    • Click Clone.

25.3.2 Step 2: Navigate the Project Structure

Once you have cloned the repository, you can explore the project structure and files. The project contains Python modules for different orientations within the PLM specialization (see Figure 25.1)

project/
β”œβ”€β”€ kpi/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ healthcare_operations.py
β”‚   β”œβ”€β”€ manufacturing_logistics.py
β”‚   β”œβ”€β”€ service_logistics.py
β”‚   └── supply_chain_management.py
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ test_healthcare_operations.py
β”‚   β”œβ”€β”€ test_manufacturing_logistics.py
β”‚   β”œβ”€β”€ test_service_logistics.py
β”‚   └── test_supply_chain_management.py
β”œβ”€β”€ README.md
β”œβ”€β”€ notebooks/
β”‚   └── 1.0-kpi_demo.ipynb
└── .gitignore
Figure 25.1: Project structure. The kpi directory contains module files for different orientations, the tests directory contains test files, and the notebooks directory contains Jupyter Notebooks.

25.4 Part 2: Selecting Your KPI

Before you start coding, you need to choose a Key Performance Indicator (KPI) relevant to the industrial engineering domain. The KPIs are categorized based on the different orientations within the Production and Logistics Management (PLM) specialization.

25.4.1 Step 1: Choose an Orientation

Select one orientation within the Production and Logistics Management (PLM) specialization:

  1. Operations Management in Healthcare (Table 25.1)
  2. Manufacturing Logistics (Table 25.2)
  3. Supply Chain and Transportation Management (Table 25.3)
  4. Service Logistics and Maintenance Management (Table 25.4)

25.4.2 Step 2: Select a KPI

Choose one KPI from the table relevant to your selected orientation. You will implement this KPI function in the existing module file corresponding to your chosen orientation.

Table 25.1: List of Key Performance Indicators (KPIs) in Operations Management in Healthcare.
KPI Name Description Calculation Formula
Bed Occupancy Rate Measures the utilization of hospital bed capacity over a period. \(\text{Bed Occupancy Rate} = \left( \frac{\text{Total Patient Bed Days}}{\text{Total Available Bed Days}} \right) \times 100\%\)
Average Patient Wait Time Average time patients wait before receiving care, indicating service efficiency. \(\text{Average Wait Time} = \frac{\text{Total Wait Time}}{\text{Number of Patients}}\)
Appointment No-Show Rate Percentage of patients who miss their scheduled appointments, affecting scheduling efficiency. \(\text{No-Show Rate} = \left( \frac{\text{Number of No-Shows}}{\text{Total Appointments Scheduled}} \right) \times 100\%\)
Staff Utilization Rate Measures how effectively medical staff time is utilized in patient care. \(\text{Staff Utilization Rate} = \left( \frac{\text{Actual Time Spent on Patient Care}}{\text{Total Available Staff Time}} \right) \times 100\%\)
Readmission Rate Percentage of patients readmitted within a certain period, indicating quality of care. \(\text{Readmission Rate} = \left( \frac{\text{Number of Readmissions}}{\text{Total Discharges}} \right) \times 100\%\)
Average Length of Stay (ALOS) Average duration of a patient’s hospitalization, reflecting efficiency of care. \(\text{ALOS} = \frac{\text{Total Inpatient Days}}{\text{Number of Discharges}}\)
Operating Room Utilization Rate Percentage of time operating rooms are in use, indicating resource optimization. \(\text{OR Utilization Rate} = \left( \frac{\text{Total OR Time Used}}{\text{Total OR Time Available}} \right) \times 100\%\)
Patient Throughput Number of patients treated over a period, reflecting capacity and efficiency. \(\text{Patient Throughput} = \frac{\text{Number of Patients Treated}}{\text{Total Time Period}}\)
Clinic Cycle Time Total time from patient check-in to check-out, indicating process efficiency. \(\text{Clinic Cycle Time} = \text{Check-Out Time} - \text{Check-In Time}\)
Medication Error Rate Frequency of medication errors, indicating patient safety and process reliability. \(\text{Medication Error Rate} = \left( \frac{\text{Number of Medication Errors}}{\text{Total Medications Administered}} \right) \times 100\%\)
Table 25.2: List of Key Performance Indicators (KPIs) in Manufacturing Logistics.
KPI Name Description Calculation Formula
Warehouse Utilization Rate Measures the percentage of warehouse space that is actively used for storage. \(\text{Utilization Rate} = \left( \frac{\text{Used Space}}{\text{Total Available Space}} \right) \times 100\%\)
Order Picking Accuracy Percentage of orders picked correctly without errors, indicating warehousing efficiency. \(\text{Picking Accuracy} = \left( \frac{\text{Accurate Orders Picked}}{\text{Total Orders Picked}} \right) \times 100\%\)
Inventory Turnover Ratio Number of times inventory is sold and replaced over a period, reflecting inventory management efficiency. \(\text{Inventory Turnover} = \frac{\text{Cost of Goods Sold}}{\text{Average Inventory}}\)
Cycle Time Total time from the beginning to the end of a process, measuring operational efficiency. \(\text{Cycle Time} = \text{Process End Time} - \text{Process Start Time}\)
Schedule Adherence Measures how closely production follows the planned schedule, indicating planning effectiveness. \(\text{Schedule Adherence} = \left( \frac{\text{Actual Output}}{\text{Scheduled Output}} \right) \times 100\%\)
Throughput Number of units produced or processed in a given time period, indicating production efficiency. \(\text{Throughput} = \frac{\text{Total Units Produced}}{\text{Total Production Time}}\)
Capacity Utilization Rate Percentage of total production capacity being utilized, reflecting efficiency and resource utilization. \(\text{Capacity Utilization} = \left( \frac{\text{Actual Output}}{\text{Maximum Possible Output}} \right) \times 100\%\)
Order Cycle Time Average time from customer order to delivery, reflecting warehousing and logistics efficiency. \(\text{Order Cycle Time} = \text{Delivery Date} - \text{Order Date}\)
Dock-to-Stock Time Time taken to move received goods from the dock to storage, indicating warehousing efficiency. \(\text{Dock-to-Stock Time} = \text{Storage Time} - \text{Receiving Time}\)
Carrying Cost of Inventory Total cost of holding inventory over a period, impacting profitability. \(\text{Carrying Cost} = \text{Average Inventory Value} \times \text{Carrying Cost Rate}\)
Table 25.3: Key Performance Indicators (KPIs) for Supply Chain Management and Transportation Management.
KPI Name Description Calculation Formula
On-Time Delivery Rate (OTD) Percentage of orders delivered on or before the promised date, reflecting delivery reliability. \(\text{OTD} = \left( \frac{\text{On-Time Deliveries}}{\text{Total Deliveries}} \right) \times 100\%\)
Freight Cost per Unit Average transportation cost per unit shipped, indicating transportation efficiency. \(\text{Freight Cost per Unit} = \frac{\text{Total Freight Cost}}{\text{Total Units Shipped}}\)
Order Fulfillment Cycle Time Average time from customer order to delivery, measuring the efficiency of the supply chain process. \(\text{Cycle Time} = \text{Delivery Date} - \text{Order Date}\)
Inventory Turnover Ratio Number of times inventory is sold and replaced over a period, indicating inventory management effectiveness. \(\text{Inventory Turnover} = \frac{\text{Cost of Goods Sold}}{\text{Average Inventory}}\)
Perfect Order Rate Percentage of orders delivered without any errors, reflecting overall supply chain performance. \(\text{Perfect Order Rate} = \left( \frac{\text{Perfect Orders}}{\text{Total Orders}} \right) \times 100\%\)
Fill Rate Proportion of customer demand met from available inventory, indicating inventory availability. \(\text{Fill\ Rate} = \left( \frac{\text{Total Units Shipped}}{\text{Total Units Ordered}} \right) \times 100\%\)
Backorder Rate Percentage of orders delayed due to stockouts, highlighting inventory management issues. \(\text{Backorder Rate} = \left( \frac{\text{Backordered Units}}{\text{Total Units Ordered}} \right) \times 100\%\)
Table 25.4: Key Performance Indicators (KPIs) for Service Logistics and Maintenance Management.
KPI Name Description Calculation Formula
Mean Time Between Failures (MTBF) Average operational time between system failures, indicating reliability. \(\text{MTBF} = \frac{\text{Total Operational Time}}{\text{Number of Failures}}\)
Mean Time to Repair (MTTR) Average time required to repair a system after a failure, reflecting maintainability. \(\text{MTTR} = \frac{\text{Total Repair Time}}{\text{Number of Repairs}}\)
Service Level Percentage of customer demand met without stockouts, indicating service effectiveness. \(\text{Service Level} = \left( \frac{\text{Total Orders Fulfilled Immediately}}{\text{Total Orders}} \right) \times 100\%\)
Fill Rate Proportion of customer demand satisfied from available inventory, reflecting inventory efficiency. \(\text{Fill\ Rate} = \left( \frac{\text{Total Units Shipped}}{\text{Total Units Ordered}} \right) \times 100\%\)
Stockout Rate Percentage of customer demand not met due to insufficient inventory, indicating supply chain issues. \(\text{Stockout Rate} = \left( 1 - \frac{\text{Total Units Shipped}}{\text{Total Units Ordered}} \right) \times 100\%\)
First Pass Yield (FPY) Percentage of products or services that meet quality standards without rework. \(\text{FPY} = \left( \frac{\text{Good Units Produced}}{\text{Total Units Produced}} \right) \times 100\%\)
Equipment Availability Proportion of time equipment is operational and available for use. \(\text{Availability} = \left( \frac{\text{Total Operational Time}}{\text{Total Time}} \right) \times 100\%\)

25.5 Part 3: Adding Your KPI Function to the Existing Module

Once you have selected your KPI, you will add a new function to the existing module file corresponding to your chosen orientation. The function should calculate the KPI based on the provided formula.

25.5.1 Step 1: Locate the Module File

Inside the kpi package directory, locate the existing module file that corresponds to your chosen orientation. The mapping is as follows:

  • Operations Management in Healthcare: healthcare_operations.py
  • Manufacturing Logistics: manufacturing_logistics.py
  • Service Logistics and Maintenance Management: service_logistics.py
  • Supply Chain and Transportation Management: supply_chain_management.py

25.5.2 Step 2: Implement the KPI Function

Add a new function to the module file that calculates your chosen KPI. Ensure that the function has the following characteristics:

  • Parameters: Include appropriate parameters for the function. For example, if your KPI requires the number of failures and total operational time, these should be passed as parameters.
  • Calculation: Use the calculation formula provided in the relevant KPI table to implement the function.
  • Return Value: Ensure that the function returns the correct output based on the formula.

Make sure your function adheres to best practices for Python coding:

  • Include a docstring explaining the function’s purpose, parameters, and return value.
  • Use meaningful variable names.
  • Follow PEP 8 style guidelines for Python code.
  • Handle potential errors or edge cases (e.g., you could use assert statements to validate inputs and avoid division by zero).
  • Add comments where necessary to explain complex logic.

In Figure 25.2, you can see an example of how the function should be structured.

# kpi/orientation_module.py

def your_kpi_function(param1: type, param2: type, ...) -> type:
    """
    Calculates the [KPI Name].

    Explanation on how the KPI is calculated.

    Parameters:
    ----------
    param1 : type
        Description of the parameter.
    param2 : type
        Description of the parameter.

    Returns:
    -------
    type
        Description of the return value.
    
    Example:
    -------
    >>> your_kpi_function(arguments)
    result
    >>> your_kpi_function(arguments)

    """
    # Implement the calculation
    result = ...  # Calculation based on parameters
    return result
Figure 25.2: Example structure of a KPI function in a module file. Replace the placeholders with your KPI name, parameters, and calculation logic. Notice the docstring format and type annotations.

25.6 Part 4: Testing Your Function

After implementing your KPI function, you need to write unit tests to ensure that it works correctly. You will create a new test file in the tests directory and write test cases using pytest.

Unit Testing

Unit testing is a software testing method where individual units or components of a program are tested in isolation to ensure they work as expected. In this assignment, you will write unit tests for your KPI function to verify its correctness.

Pytest Framework

We will use the pytest framework for writing and running tests. If you are not familiar with pytest, you can refer to the official documentation.

25.6.1 Step 1: Set Up the Testing Environment

Ensure that pytest is installed in your Python environment. You can install it using pip if it’s not already available:

pip install pytest

25.6.2 Step 2: Create a Test File

Inside the tests folder, find the test file corresponding to your chosen orientation. You will add test cases for your KPI function in this file. Notice that the test file has the same name as the module file but with a test_ prefix. For example, if you added your KPI function to service_logistics.py, you should modify test_service_logistics.py.

25.6.3 Step 3: Write Test Cases

Now that you have your test file open, you can start writing test cases for your KPI function. The test cases should cover typical scenarios and edge cases to ensure the function behaves as expected. In Listing 25.1, you can see an example of how a test case should be structured.

Listing 25.1: Example of a test case for a KPI function. Replace the placeholders with your function name, arguments, and expected results.
# tests/test_your_module.py

import kpi.orientation_module as om

def test_your_kpi_function():
    # Test case 1
    assert om.your_kpi_function(arguments) == expected_result
    # Additional test cases

25.6.4 Step 4: Run Tests with Pytest

  • In the terminal, navigate to the project root directory.

  • Run the tests using pytest:

    pytest tests/
  • Ensure all tests pass. If not, debug and fix your code accordingly.

25.6.5 Step 5: Error Handling and Edge Cases

Review your KPI function and test cases to ensure you handle potential errors and edge cases. For example, you could test the function with invalid inputs such as negative values, division by zero, strings instead of numbers, etc. Make your function return None in these cases and add corresponding test cases to check the behavior.

25.7 Part 5: Using Your KPI in a Jupyter Notebook

To demonstrate the functionality of your KPI function and its relevance in the industrial engineering domain, you will create a Jupyter Notebook. The notebook should explain the KPI, provide a calculation example, and interpret the results. You will use Markdown cells for explanations and code cells to demonstrate the KPI calculation.

Speed Up with AI

Use Copilot to generate the explanation and code snippets for your Jupyter Notebook. Copilot can help you write Markdown and Python code faster, saving you time and effort. Also, you could explore visualizations for your KPI results using libraries like matplotlib or seaborn. Ask AI for suggestions on how to present your data effectively in the GitHub Copilot Chat.

25.7.1 Step 1: Create a Jupyter Notebook

Create a new Jupyter Notebook in the notebooks directory named <author>-kpi-<orientation>-<kpi>.ipynb. Replace the fields with your information (use snake_case for consistency):

  • <author>: Your name or initials.
  • <orientation>: The PLM specialization orientation.
  • <kpi>: The name of the KPI you implemented.

25.7.2 Step 2: Explain the KPI Using Markdown

In the first cells, use Markdown to:

  • Introduce your chosen KPI.
  • Explain its importance in the context of the PLM specialization.
  • Provide the calculation formula using LaTeX formatting. Ask AI to help you write the explanation and formula in Markdown. You don’t need to write the LaTeX code from scratch; Copilot can generate it for you.

In Listing 25.2, you can see an example of how to structure the explanation and formula in a Markdown cell. The formula is written using LaTeX syntax for mathematical expressions. To ask AI for help with LaTeX formatting, you can:

  • Select
Listing 25.2: Example Markdown cell explaining the KPI definition and formula using LaTeX formatting. The formula is written in a math block ($$ ... $$) using the LaTeX syntax.
# Warehouse Utilization Rate

**Orientation**: Manufacturing Logistics

**Definition**: The Warehouse Utilization Rate is a measure of how efficiently a warehouse space is being used. It is calculated as the ratio of the actual inventory stored in the warehouse to the total capacity of the warehouse.

**Formula**:
$$
\text{Warehouse Utilization Rate} = \frac{\text{Actual Inventory Stored}}{\text{Total Warehouse Capacity}}
$$

Ask AI to help you write the explanation and formula in Markdown:

  1. Prompt Copilot to generate the explanation and formula of your KPI. For example, for kpi β€œMean Time Between Failures (MTBF)” in the context of Service Logistics, you can ask:

    β€œExplain the concept of Mean Time Between Failures (MTBF) in the context of Service Logistics using the Markdown Syntax. Write the formula for MTBF using LaTeX syntax. Use the following template to structure your explanation:”

  2. Copy the template in Listing 25.2 and paste the generated explanation and formula into your Jupyter Notebook.

  3. Copy the answer from Copilot and paste it into the Markdown cell in your Jupyter Notebook and adjust it as needed.

25.7.3 Step 3: Import the Module and Use the KPI Function

In code cells, demonstrate how to use your KPI function:

  • Provide sample data and show the calculation of the KPI (e.g., for β€œwarehouse utilization rate”, the parameters are actual inventory stored and total warehouse capacity).
Listing 25.3: Example code cell demonstrating the use of the KPI function in a Jupyter Notebook. Replace the placeholders with your function name and sample data. The sys.path.append line adds the kpi directory to the Python path since the notebook is in a different directory and cannot β€œsee” the module directly.
# Add kpi module to the Python path
import sys
sys.path.append("../")

# Import your KPI function
from kpi.your_module import your_kpi_function

# Sample data
param1 = ...
param2 = ...

# Calculate KPI
result = your_kpi_function(param1, param2, ...)

# Display result
print(f"Your KPI Result: {result}")

25.7.4 Step 4: Explore Ways to Visualize the KPI Results

Ask AI to visualize the KPI given synthetic data. For example, for the β€œWarehouse Utilization Rate” KPI, you can ask:

β€œVisualize the Warehouse Utilization Rate using a bar chart. Generate synthetic data for the actual inventory stored and total warehouse capacity. Plot the Warehouse Utilization Rate for different warehouses.”

25.8 Part 6: Committing and Pushing Your Changes

Once you have implemented your KPI function, written tests, and created the Jupyter Notebook, you need to commit your changes to the shared repository using GitHub Desktop.

25.8.1 Step 1: Stage Changes

  • Open GitHub Desktop.
  • You should see your modified files listed under Changes:
    • kpi/your_module.py (modified)
    • tests/test_your_module.py (new or modified)
    • notebooks/<author>-kpi-<orientation>-<kpi>.ipynb (new)

25.8.2 Step 2: Write a Commit Message

  • In the Summary box, write a meaningful commit message.
    • Example: β€œAdd MTBF function and demonstration for Service Logistics”

25.8.3 Step 3: Commit Changes

  • Click Commit to main (or the appropriate branch if instructed).

25.8.4 Step 4: Push to Repository

  • Click Push origin to upload your changes to the shared repository.

25.9 Additional Resources