Skip to main content

Shift Scheduling Algorithm using OR-Tools with Modular Constraints

Project description

Modular NOC Scheduling System

Version Python 3.8+ License: MIT

An intelligent shift scheduling algorithm for Network Operations Center (NOC) and Security Operations Center (SOC) teams in 24/7 environments. Powered by Google OR-Tools constraint programming, it generates optimal work schedules with fair workload distribution, cultural awareness (including Ramadan), and expert supervision requirements.

Quick Start

Installation

Install the package from PyPI:

pip install modular-noc-scheduling

Basic Usage

Python Simple Usage for the Algorithm

from modular_scheduling import run_modular_scheduling_algorithm

# Basic example with minimal parameters
success, output_files, solver_status, error_msg, schedule_data, max_shifts_per_employee = run_modular_scheduling_algorithm(
    year=2025,
    month=9,
    employees_data=[
        {'type': 'EXPERT', 'vacation_days': 10},
        {'type': 'EXPERT', 'vacation_days': 15},
        {'type': 'BEGINNER', 'vacation_days': 5}
    ],
    holidays_file_path=None,  # Optional: path to holidays file
    solution_limit=1,         # Number of solutions to generate
    constraints=None          # Optional: custom constraint configuration
)

# Check results
if success:
    print(f"Schedule generated successfully!")
    print(f"Solver status: {solver_status}")
    print(f"Output files: {output_files}")
    print(f"Max shifts per employee: {max_shifts_per_employee}")
    
    # Access the schedule data
    for employee, days in schedule_data.items():
        print(f"\n{employee}:")
        for day, shift in days.items():
            print(f"  {day}: {shift}")
else:
    print(f"Failed to generate schedule: {error_msg}")
    print(f"Solver status: {solver_status}")

# Advanced example with custom constraints
constraints = {
    'constraint_weekday_shifts': True,
    'constraint_expert_supervision': True,
    'constraint_e_n_rest': True,
    'constraint_holiday_shifts': True,
    'constraint_weekend_shifts': True,
    'constraint_one_shift_per_person_per_day': True,
    'constraint_fair_weekend_distribution': True,
    'constraint_fair_holiday_distribution': True,
    'constraint_min_normal_evening_shifts': True,
    'constraint_min_abnormal_evening_shifts': True,
    'constraint_evenly_distribute_max_shifts': True,
    'constraint_off_days_based_on_vacation_balance': True,
    'constraint_limit_contiguous_shifts': True
}

success, output_files, solver_status, error_msg, schedule_data, max_shifts_per_employee = run_modular_scheduling_algorithm(
    year=2025,
    month=9,
    employees_data=[
        {'type': 'EXPERT', 'vacation_days': 12},
        {'type': 'EXPERT', 'vacation_days': 8},
        {'type': 'EXPERT', 'vacation_days': 10},
        {'type': 'BEGINNER', 'vacation_days': 6},
        {'type': 'BEGINNER', 'vacation_days': 4}
    ],
    holidays_file_path="holidays.txt",  # Path to your holidays file
    solution_limit=3,
    constraints=constraints
)

# Return Values Explained:
# - success (bool): True if scheduling succeeded, False otherwise
# - output_files (list): List of generated output file paths
# - solver_status (str): OR-Tools solver status ("OPTIMAL", "FEASIBLE", etc.)
# - error_msg (str): Error message if scheduling failed, empty string if successful
# - schedule_data (dict): Dictionary containing the complete schedule
#   Format: {employee_name: {day_name: shift_assignment}}
# - max_shifts_per_employee (int): Maximum number of shifts assigned to any employee

Command Line Interface

# Run the interactive scheduling tool
modular-scheduling

# Or with parameters
modular-scheduling --year 2025 --month 9 --employees "Alice,Bob,Charlie"

Key Features at a Glance

  • 24/7 Shift Coverage: Morning, Evening, Night shifts
  • Cultural Awareness: Special Ramadan scheduling
  • Expert Supervision: Automatic beginner-expert pairing
  • Fair Distribution: Balanced workload across team members
  • Holiday Management: Intelligent holiday and weekend coverage
  • Constraint-Based: Uses advanced optimization algorithms
  • Modular Design: Easy to extend and customize

📋 Table of Contents

  1. Quick Start
  2. What is This Algorithm?
  3. Who Should Use This Guide?
  4. Key Features
  5. Understanding the Basics
  6. How to Use the Algorithm
  7. Understanding the Schedule Output
  8. Common Scenarios and Solutions
  9. Troubleshooting
  10. Technical Information
  11. 🔧 API Reference
  12. 🤝 Contributing
  13. 📄 License
  14. 🆘 Support
  15. 🏷️ Version History

What is This Algorithm?

The Modular NOC Scheduling System is an intelligent shift scheduling algorithm for Network Operations Center (NOC) and Security Operations Center (SOC) teams in 24/7 environments. Powered by Google OR-Tools constraint programming, it generates optimal work schedules with fair workload distribution, cultural awareness (including Ramadan), and expert supervision requirements.

What Makes It Special?

  • Intelligent: Uses advanced algorithms to solve complex scheduling puzzles
  • Fair: Ensures equal distribution of workload among team members
  • Cultural-Aware: Handles special requirements during Ramadan
  • Flexible: Adapts to different team sizes and requirements
  • Reliable: Guarantees all shifts are properly covered with qualified staff

Who Should Use This Guide?

This guide is designed for:

  • Team Managers: Who need to create monthly schedules
  • HR Personnel: Responsible for workforce planning
  • Supervisors: Who monitor shift coverage and fairness
  • Non-Technical Users: Who want to understand how the algorithm works

No programming knowledge required! This guide explains everything in simple terms.


Key Features

🕐 Multiple Shift Types

  • Morning Shifts (M): Regular daytime work
  • Evening Shifts (E): Afternoon/evening coverage
  • Night Shifts (N): Overnight operations
  • Ramadan Shifts: Special shifts during the holy month with adjusted timings

🏖️ Holiday & Weekend Management

  • Automatic holiday detection from your calendar
  • Special holiday shifts with premium staffing
  • Weekend coverage ensuring business continuity
  • Regional calendar support (Hijri and Gregorian)

👥 Smart Team Management

  • Expert vs. Beginner classification
  • Automatic supervision pairing (beginners always work with experts)
  • Fair workload distribution based on experience levels
  • Vacation balance consideration for off-day allocation

⚖️ Fairness Guarantees

  • Equal distribution of weekend and holiday work
  • Balanced shift assignments over time
  • Consideration of remaining vacation days
  • Prevention of excessive consecutive shifts

🔧 Customizable Rules

  • Enable/disable specific scheduling rules as needed
  • Adapt to your organization's unique requirements
  • Easy modification without technical expertise

Understanding the Basics

Employee Types

The algorithm recognizes two types of employees:

Experts (E)

  • Experienced team members who can work independently
  • Can supervise and guide beginners

Beginners (B)

  • Newer team members requiring supervision
  • Must always work alongside at least one expert

Shift Categories

Normal Days

  • M (Morning): Standard day shift
  • E (Evening): Standard evening shift
  • N (Night): Standard night shift

Ramadan Days (Special cultural/religious period)

  • MR (Morning Ramadan): Adjusted morning hours
  • E1R (Evening 1 Ramadan): First evening shift with special timing
  • E2R (Evening 2 Ramadan): Second evening shift with special timing
  • NR (Night Ramadan): Night shift with special considerations

Holiday Variants

  • All shift types get an "H" prefix on holidays (e.g., HM, HE, HN)
  • Holiday shifts may have different staffing requirements

Special States

  • OFF: Scheduled day off
  • No Shift Assigned - Rest: Mandatory rest day (cannot be changed)

Calendar Integration

The algorithm automatically identifies:

  • Weekdays: Sunday through Thursday (normal work days)
  • Weekends: Friday and Saturday (require special coverage)
  • Holidays: National and religious holidays from your calendar
  • Ramadan Period: Automatically calculated based on Islamic calendar

How to Use the Algorithm

Installation

The modular NOC scheduling system is available as a Python package that can be easily installed using pip.

Prerequisites:

  • Python 3.8 or higher
  • pip (Python package installer)

Install from PyPI (Recommended)

pip install modular-noc-scheduling

Install from Source

If you want to install from the source code:

# Clone or download the source code, then navigate to the package directory
cd path/to/scheduling_package

# Install the package
pip install .

# Or install in development mode (for developers)
pip install -e .

Verify Installation

# Test the command-line interface
modular-scheduling --help

# Or test Python import
python -c "from modular_scheduling import run_modular_scheduling_algorithm; print('Installation successful!')"

Windows Notes:

  • If you encounter issues with OR-Tools installation, you might need Microsoft Visual C++ 14.0 or greater
  • Use PowerShell or Command Prompt as Administrator if you get permission errors
  • On some Windows systems, you may need to use python -m pip instead of just pip

Quick Start

Once installed, you can use the algorithm in several ways:

Command Line Interface:

# Run the scheduling algorithm with interactive prompts
modular-scheduling

# Or with specific parameters
modular-scheduling --year 2025 --month 9

Python API:

# Direct function call (see detailed example below)
from modular_scheduling import run_modular_scheduling_algorithm

result = run_modular_scheduling_algorithm(
    year=2025,
    month=9,
    employees_data=[
        {'type': 'EXPERT', 'vacation_days': 10},
        {'type': 'EXPERT', 'vacation_days': 15},
        {'type': 'BEGINNER', 'vacation_days': 5}
    ]
)

Using the Algorithm

Web Interface (If Available)

If your organization provides a web interface for the NOC scheduling system:

Step 1: Access the Interface

  1. Open your web browser
  2. Navigate to the provided URL
  3. You'll see a user-friendly interface with clear sections

Step 2: Enter Basic Information

  • Year and Month: Select the period you want to schedule
  • Team Size: Specify how many employees to schedule

Step 3: Add Employee Information For each team member, provide:

  • Employee Type: Expert or Beginner
  • Remaining Vacation Days: How many vacation days they have left

Step 4: Upload Holiday Calendar (Optional)

  • If you have a special holiday file, upload it in the required format

Step 5: Configure Rules (Advanced) Most users can skip this section, but you can:

  • Enable/disable specific scheduling rules
  • Adjust minimum shift requirements
  • Modify fairness settings

Step 6: Generate Schedule

  • Click "Generate Schedule"
  • Wait for the algorithm to process (may take a few seconds)
  • Review the generated schedule

Python Integration

For integrating the scheduling system into your own applications, use the Python API as shown in the examples above. The function returns detailed results that can be processed programmatically.

File-Based Input

For organizations that prefer file-based processes:

  1. Prepare employee data in the correct format (see examples above)
  2. Create holiday calendar file in the specified format
  3. Call the algorithm function with file paths as parameters

Understanding the Schedule Output

Reading the Schedule

The algorithm generates a calendar-style schedule showing:

  • Rows: Each day of the month
  • Columns: Each team member
  • Cells: Assigned shift or status for each person each day

Color Coding (Web Interface)

  • Blue: Normal shifts (M, E, N)
  • Green: Ramadan shifts (MR, E1R, E2R, NR)
  • Red: Holiday shifts (HM, HE, HN, etc.)
  • Gray: Off days
  • White: Rest days (mandatory)

Schedule Statistics

The algorithm provides helpful statistics:

  • Total shifts per employee: Ensuring fairness
  • Weekend/Holiday distribution: Showing equal sharing
  • Shift type distribution: Balanced assignment patterns
  • Overtime indicators: If someone exceeds normal limits

Generated Files

The algorithm creates several detailed reports:

1. Input Summary

  • All the parameters you entered
  • Which rules were enabled/disabled
  • Team composition details

2. Schedule Solution

  • Complete day-by-day assignments
  • Easy-to-read format for printing or sharing

3. Off-Days Distribution

  • Calculation details for vacation day allocation
  • Fairness metrics and explanations

4. Calendar Information

  • Holiday and weekend identification
  • Ramadan period calculations

Common Scenarios and Solutions

Scenario 1: "The Algorithm Says No Solution Found"

What this means: Your requirements cannot be met with the current team size or constraints.

Solutions:

  • Add more team members
  • Reduce minimum shift requirements
  • Check if vacation day allocations are realistic

Scenario 2: "Someone Has Too Many Shifts"

What this means: The workload distribution isn't perfectly even.

Solutions:

  • Enable the "Fair Distribution" constraints
  • Increase the solution search time
  • Consider if the person has fewer vacation days (affecting their off-day allocation)

Scenario 3: "Weekend Coverage Looks Uneven"

What this means: Some people work more weekends than others.

Solutions:

  • Ensure "Fair Weekend Distribution" is enabled
  • Check that you have enough team members for weekend coverage
  • Consider the impact of vacation day differences

Scenario 4: "Ramadan Shifts Aren't Working"

What this means: The algorithm can't properly assign special Ramadan shifts.

Solutions:

  • Verify the Ramadan period is correctly calculated
  • Ensure you have enough experts for supervision during Ramadan
  • Check that Ramadan-specific constraints are enabled

Scenario 5: "Holiday Coverage Is Missing"

What this means: Some holidays don't have proper shift coverage.

Solutions:

  • Upload a complete holiday calendar file
  • Enable holiday shift constraints
  • Ensure minimum holiday staffing requirements are met

Troubleshooting

Common Issues and Quick Fixes

Issue: Algorithm is very slow

  • Solution: Reduce the number of solutions requested, try with fewer constraints enabled

Issue: Schedule looks unfair

  • Solution: Enable all fairness constraints

Issue: Beginners are working alone

  • Solution: Ensure "Expert Supervision" constraint is enabled, check expert-to-beginner ratio

Issue: Too many consecutive work days

  • Solution: Enable "Limit Contiguous Shifts" constraint, adjust maximum consecutive days

Issue: Off days don't match vacation entitlements

  • Solution: Verify vacation day numbers are correct, enable vacation-based off-day constraints

When to Contact Support

Contact your IT team if:

  • The algorithm doesn't load or crashes
  • You get error messages you don't understand
  • The schedule results seem completely wrong
  • You need to modify algorithm rules or constraints

Technical Information

Algorithm Architecture

Core Components

  • Scheduler Engine: Uses Google OR-Tools constraint programming
  • Web Interface: Built with Streamlit for easy use
  • Constraint Algorithm: Modular rules that can be enabled/disabled
  • Calendar Integration: Supports both Gregorian and Hijri calendars

How It Works

  1. Input Processing: Algorithm converts your requirements into mathematical constraints
  2. Optimization: Advanced algorithms find the best schedule that satisfies all rules
  3. Solution Generation: Multiple valid schedules may be found
  4. Output Formatting: Results are presented in user-friendly formats

Constraint Categories

Coverage Constraints

  • Ensure all shifts have adequate staffing
  • Guarantee weekend and holiday coverage
  • Maintain 24/7 operations continuity

Fairness Constraints

  • Equal distribution of workload
  • Balanced weekend/holiday assignments
  • Fair vacation day consideration

Safety Constraints

  • Expert supervision for beginners
  • Mandatory rest after certain shift sequences
  • Limits on consecutive working days

Cultural Constraints

  • Special Ramadan shift patterns
  • Regional holiday observances
  • Cultural work week conventions

File Formats

Employee Data Input Employee information is entered through the web interface with the following parameters:

  • Employee Type: EXPERT or BEGINNER
  • Vacation Days: Integer value (0-21 for experts, 0-14 for beginners)

No separate employee data file is required - all input is handled through the interactive web interface.

Holiday File Format Upload a text file (.txt) with holidays using this exact format:

day; month; description
1; 1; New Year's Day
15; 8; Independence Day
25; 12; Christmas Day

Format requirements:

  • Each line contains: day; month; description
  • Semicolon (;) separated values
  • Day and month as integers (e.g., 1-31 for day, 1-12 for month)
  • Description is optional but recommended for clarity
  • Lines starting with "day" are treated as headers and ignored
  • Empty lines are ignored
  • File encoding: UTF-8

Generated Output Files The algorithm automatically creates several output files with structured formats:

  1. Input Summary (input_summary_YYYY_MM_timestamp.txt)

    • Contains all input parameters and constraint settings
    • Employee details and configuration used
  2. Solution File (solution_YYYY_MM_timestamp_sol1.txt)

    • Complete day-by-day schedule assignments
    • Employee-day-shift mappings in readable format

🔧 API Reference

Main Function

run_modular_scheduling_algorithm()

The primary function for generating NOC schedules.

Function Signature:

from modular_scheduling import run_modular_scheduling_algorithm

success, output_files, solver_status, error_msg, schedule_data, max_shifts_per_employee = run_modular_scheduling_algorithm(
    year,                    # int: Gregorian year (e.g., 2025)
    month,                   # int: Month (1-12)
    employees_data,          # list: Employee information
    holidays_file_path=None, # str or None: Path to holidays file
    solution_limit=1,        # int: Maximum solutions to generate
    constraints=None         # dict or None: Constraint configuration
)

Parameters:

  • year (int): The Gregorian year for scheduling
  • month (int): Month (1-12) for scheduling
  • employees_data (list): List of employee dictionaries with format:
    [
        {'type': 'EXPERT', 'vacation_days': 10},
        {'type': 'BEGINNER', 'vacation_days': 5}
    ]
    
  • holidays_file_path (str, optional): Path to holidays file in specified format
  • solution_limit (int): Maximum number of solutions to generate (default: 1)
  • constraints (dict, optional): Constraint configuration dictionary

Returns:

  • success (bool): True if scheduling succeeded, False otherwise
  • output_files (list): List of generated output file paths
  • solver_status (str): OR-Tools solver status ("OPTIMAL", "FEASIBLE", "INFEASIBLE", etc.)
  • error_msg (str): Error message if failed, empty string if successful
  • schedule_data (dict): Complete schedule in format: {employee_name: {day_name: shift_assignment}}
  • max_shifts_per_employee (int): Maximum number of shifts assigned to any employee

Example:

employees_data = [
    {'type': 'EXPERT', 'vacation_days': 12},
    {'type': 'EXPERT', 'vacation_days': 8},
    {'type': 'BEGINNER', 'vacation_days': 6}
]

success, files, status, error, schedule, max_shifts = run_modular_scheduling_algorithm(
    year=2025,
    month=9,
    employees_data=employees_data,
    holidays_file_path="holidays.txt",
    solution_limit=1
)

if success:
    print(f"Success! Status: {status}")
    print(f"Generated files: {files}")
    print(f"Max shifts per employee: {max_shifts}")
else:
    print(f"Failed: {error}")

Available Constraints

All constraints are modular and can be enabled/disabled through the constraints parameter:

constraints = {
    'constraint_weekday_shifts': True,                    # Ensure proper weekday shift coverage
    'constraint_expert_supervision': True,               # Require expert supervision for beginners
    'constraint_one_shift_per_person_per_day': True,     # One shift per employee per day
    'constraint_e_n_rest': True,                         # Rest after evening and night shifts
    'constraint_holiday_shifts': True,                   # Special holiday shift coverage
    'constraint_weekend_shifts': True,                   # Weekend shift coverage
    'constraint_fair_weekend_distribution': True,        # Fair weekend shift distribution
    'constraint_fair_holiday_distribution': True,        # Fair holiday shift distribution
    'constraint_min_normal_evening_shifts': True,        # Minimum evening shifts on normal days
    'constraint_min_abnormal_evening_shifts': True,      # Minimum evening shifts on Ramadan days
    'constraint_evenly_distribute_max_shifts': True,     # Equal maximum shifts for all employees
    'constraint_off_days_based_on_vacation_balance': True, # Off-days based on vacation balance
    'constraint_limit_contiguous_shifts': True           # Limit consecutive working days
}

Constraint Descriptions:

  • constraint_weekday_shifts: Ensures adequate coverage during weekdays
  • constraint_expert_supervision: Beginners must work with at least one expert
  • constraint_one_shift_per_person_per_day: Prevents double-booking employees
  • constraint_e_n_rest: Mandatory rest after evening/night shift sequences
  • constraint_holiday_shifts: Special requirements for holiday coverage
  • constraint_weekend_shifts: Ensures weekend shift coverage
  • constraint_fair_weekend_distribution: Balances weekend work among employees
  • constraint_fair_holiday_distribution: Balances holiday work among employees
  • constraint_min_normal_evening_shifts: Minimum evening shifts for each employee
  • constraint_min_abnormal_evening_shifts: Minimum evening shifts during Ramadan
  • constraint_evenly_distribute_max_shifts: Forces equal workload distribution
  • constraint_off_days_based_on_vacation_balance: Allocates off-days based on vacation entitlement
  • constraint_limit_contiguous_shifts: Prevents excessive consecutive working days

🤝 Contributing

We welcome contributions! Here's how to get started:

Development Setup

# Clone the repository
git clone https://github.com/abdalkarimnael/scheduling_package.git
cd scheduling_package

# Install in development mode
pip install -e .[dev]

# Install pre-commit hooks
pre-commit install

Running Tests

pytest tests/

Code Style

We use Black for code formatting:

black modular_scheduling/

Submitting Changes

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


🆘 Support


🏷️ Version History

  • v1.0.4 - Updated documentation with package-focused installation and improved usage examples
  • v1.0.3 - Enhanced documentation and installation instructions
  • v1.0.2 - Enhanced documentation and installation instructions
  • v1.0.1 - Enhanced documentation and installation instructions
  • v1.0.0 - Initial release with core scheduling functionality

Made with ❤️ by the Innovation Team - Digital Transformation

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

modular_noc_scheduling-1.0.4-py3-none-any.whl (495.7 kB view details)

Uploaded Python 3

File details

Details for the file modular_noc_scheduling-1.0.4-py3-none-any.whl.

File metadata

File hashes

Hashes for modular_noc_scheduling-1.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 0c67d08e8b5e0a136f69b0410a0885d93a4725924c55da4ac77c39b6003a4054
MD5 ea9b54b78335f05caaf8d4d5a598c2e5
BLAKE2b-256 0f4b3755f59f5760d89820730cf1a43bae86fe5c875f9ea077ede1843f251eb5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page