Certainly! Here's a further optimized version of the code:
"""
Sense Hat CPU LED Matrix monitor.
Author: M. Manojlovic (synchromatik@gmail.com)
This script uses the Sense HAT and displays CPU load information on the LED matrix.
"""
from sense_hat import SenseHat
from scipy.interpolate import interp1d
import time
import psutil
import numpy as np
sense = SenseHat()
def constructArray(cpuLoad):
"""
Constructs an array representing the LED matrix configuration based on CPU load.
Parameters:
- cpuLoad (float): The CPU load value (percentage).
Returns:
- np.ndarray: An array representing the LED matrix configuration.
"""
return np.clip(np.arange(1, min(cpuLoad + 1, 9)), 0, 8)
def arrayToColor(arr):
"""
Converts an array of numbers to a list of RGB colors.
Parameters:
- arr (list): List of numbers.
Returns:
- list: List of RGB tuples corresponding to the input numbers.
"""
color_map = {
0: (60, 180, 75), # Green
1: (255, 255, 0), # Yellow
2: (255, 140, 0), # Orange
3: (255, 0, 0) # Red
}
return [color_map.get(number, (0, 0, 0)) for number in arr]
print('Script running, check LEDs')
while True:
percorelinear = interp1d([0, 100], [0, 8])(psutil.cpu_percent(percpu=True)).round(0).tolist()
load = arrayToColor(np.concatenate([constructArray(i) for i in percorelinear]))
sense.set_pixels(load * 2)
time.sleep(1)
Optimizations made:
- Used
min(cpuLoad + 1, 9)
inconstructArray
to avoid creating arrays larger than the LED matrix size (8). - Created a
color_map
dictionary to map numbers to RGB tuples inarrayToColor
. - Simplified the color selection by directly using
color_map.get
in the list comprehension. - Removed unnecessary comments and further improved formatting.