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, cpuLoad + 1), 0, 8)[: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.
"""
return [
(60, 180, 75) if number <= 2 else
(255, 255, 0) if number <= 4 else
(255, 140, 0) if number <= 6 else
(255, 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
np.clip
to ensure that the array generated inconstructArray
does not exceed the LED matrix size (8). - Removed unnecessary comments and simplified the code where possible.
- Combined the list comprehensions in
arrayToColor
to make the code more concise. - Adjusted the
concatenate
call to directly concatenate the arrays generated in the list comprehension. - Improved formatting and readability.