Skip to content

Commit

Permalink
feat(bandit): improve performance of priority updates and arm addition
Browse files Browse the repository at this point in the history
- Replaced lambda-based priority updates with `numpy.vectorize` for better performance in `update_priority`.
- Added a check to prevent unnecessary `pd.concat` calls in `add_arms` if the arm list is empty.
- Introduced validation for empty actions in `EvaluationMetricBandit.pull`.
  • Loading branch information
jacksonpradolima committed Dec 22, 2024
1 parent ffc5670 commit 343f0b8
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions coleman4hcs/bandit.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
from abc import ABC, abstractmethod
from typing import Dict, List

import numpy as np
import pandas as pd

from coleman4hcs.evaluation import EvaluationMetric


Expand Down Expand Up @@ -80,25 +82,27 @@ def add_arms(self, arms: List[Dict]):
:param arms: List of arms.
"""
self.arms = pd.concat([self.arms, pd.DataFrame(arms, columns=self.tc_fieldnames)], ignore_index=True)
if arms:
self.arms = pd.concat([self.arms, pd.DataFrame(arms, columns=self.tc_fieldnames)], ignore_index=True)

@abstractmethod
def pull(self, action):
"""
Simulate pulling an arm. To be implemented by subclasses.
"""

return NotImplementedError('You must to implemented this function')

def update_priority(self, action):
"""
Update the Priority column with the priorities
:param action: List of test cases in order of prioritization
"""
self.arms['CalcPrio'] = self.arms['Name'].apply(lambda x: action.index(x) + 1)
action_map = {name: priority for priority, name in enumerate(action, start=1)}
priorities = np.vectorize(action_map.get)(self.arms['Name'].to_numpy())
self.arms['CalcPrio'] = priorities


class DynamicBandit(Bandit):
class DynamicBandit(Bandit, ABC):
"""
A Bandit that allows dynamic management of its arms.
"""
Expand All @@ -107,7 +111,6 @@ def update_arms(self, arms: List[Dict]):
"""
Update the arms of the bandit.
"""

# I can replace all arms because the bandit don't need to maintain a "history"
# The agent needs to maintain the "history"
self.reset()
Expand Down Expand Up @@ -142,6 +145,9 @@ def pull(self, action):
:param action: The Prioritized Test Suite List
:return: The result ("state") of an evaluation by Evaluation Metric
"""
if not action:
raise ValueError("Action list cannot be empty")

super().update_priority(action)

# After, we need to order the test cases based on the priorities
Expand Down

0 comments on commit 343f0b8

Please sign in to comment.