Skip to content
Snippets Groups Projects
Commit d5ed5375 authored by Xia, Ning's avatar Xia, Ning :penguin:
Browse files

updated utility template

parent c8eaf110
No related branches found
No related tags found
No related merge requests found
import numpy as np
import matplotlib.pyplot as plt
import h5py as h5
import os
from typing import List, Tuple
import h5py as h5
import matplotlib.pyplot as plt
import numpy as np
def plot_temp_over_time(
data: List[np.ndarray],
......@@ -11,8 +11,6 @@ def plot_temp_over_time(
legend: List[str],
x_label: str,
y_label: str,
is_save: bool = False,
file_name: str = "image.svg",
) -> None:
"""Plots temperature data over time with error bars for multiple datasets.
......@@ -30,42 +28,116 @@ def plot_temp_over_time(
legend (List[str]): A list of strings that label each dataset in the legend.
x_label (str): The label for the x-axis (time).
y_label (str): The label for the y-axis (temperature).
is_save (bool, optional): If set to True, the plot will be saved to the path specified by
`file_name`. Defaults to False.
file_name (str, optional): The path and filename where the plot image will be saved if
`is_save` is True. Defaults to "image.svg".
"""
# TODO: Complete the function.
# This line of code throws an exception. This is just to make sure you can see
# all the code you need to refine. If you already know how to implement the program
# or have done so, then you can safely delete the three lines of code below, as well
# as this comment.
# init the matplotlib.axes.Axes and matplotlib.figure.Figure Object for later plot
fig, ax = plt.subplots(1, 1)
markers = ["o", "^", "2", "p", "D"]
for i in range(len(data)):
# TODO: draw a plot using the ax.errorbar(...) function
# Document: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.errorbar.html
raise NotImplementedError(
"Delete these 3 lines if you have finished the code or want to test it.".upper()
)
# DONE #
# Errorbars removed from Legend
legend_handles, labels = ax.get_legend_handles_labels()
legend_handles = [h[0] for h in legend_handles]
# TODO: set legend, x- and y- axis label.
raise NotImplementedError(
"Delete these 3 lines if you have finished the code or want to test it.".upper()
)
# DONE #
ax.ticklabel_format(scilimits=(0, 3))
def get_plot_data_from_dataset(
data_path: str, group_path: str
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
) -> dict[str, np.ndarray]:
"""Get the necessary data from the dataset to plot.
This function returns the data in a HDF5 file in all subgroups of a group in 'group_path'
and automatically categorizes and names the data based on the name of the dataset as well as the metadata.
Args:
data_path (str): path to dataset.
group_path (str): path in HDF5 to group containing the measurement data.
data_path (str): path to HDF5 file.
group_path (str): path in HDF5 to group.
Returns:
tuple[np.ndarray, np.ndarray, np.ndarray]: Data for plot in a tuple (temperature, time step, label of data).
dict[str, np.ndarray]: Data for plot in a dict.
Example:
Output (example data):
{
"temperature": np.array([
[24.89, 24.92, 24.00, 25.39],
[24.89, 24.92, 24.00, 25.39],
[24.89, 24.92, 24.00, 25.39]
]) -> temperature from each sensor, The first dimension represents the sensor.
"timestamp": np.array([
[0.43, 1.60, 3.05, 4.25],
[0.81, 2.13, 3.49, 4.62],
[1.34, 2.60, 3.85, 5.08],
]) -> timestamp for each sensor, The first dimension represents the sensor.
"name": np.ndarray(["sensor_1", "sensor_2", "sensor_3"]) -> name of each sensor should be hier
}
"""
# TODO: Complete the function.
# This line of code throws an exception. This is just to make sure you can see
# all the code you need to refine. If you already know how to implement the program
# or have done so, then you can safely delete the three lines of code below, as well
# as this comment.
temperature = []
time = []
name = []
with h5.File(data_path) as data:
group = data[group_path]
subgroups = []
min_len = None
start_time = None
for subgroup in group:
try:
dataset_start_time = group[subgroup]["timestamp"][0]
dataset_len = len(group[subgroup]["timestamp"])
# Find the minimum length of the data set.
if min_len is None:
min_len = dataset_len
elif dataset_len < min_len:
min_len = dataset_len
subgroups.append(subgroup)
# Only group with dataset called timestamp will be read.
except KeyError:
continue
# TODO: Find the start time point of the measurement.
raise NotImplementedError(
"Delete these 3 lines if you have finished the code or want to test it.".upper()
)
# DONE #
for subgroup in subgroups:
# TODO: Save data in to the lists temperature, time and mame.
# Data for each sensor must have the same length because of np.ndarray will be use in the output.
raise NotImplementedError(
"Delete these 3 lines if you have finished the code or want to test it.".upper()
)
# DONE #
# TODO: return the output dict.
raise NotImplementedError(
"Delete these 3 lines if you have finished the code or want to test it.".upper()
)
......@@ -74,21 +146,19 @@ def get_plot_data_from_dataset(
def cal_mean_and_standard_deviation(data: np.ndarray) -> np.ndarray:
"""Calculating mean and standard_deviation for raw data.
"""Calculating mean and standard deviation for raw data of multiple sensors.
Args:
data (np.ndarray): raw data in a 2 dimensional array (m, n), the first dimension should not be 1 if
there are multiple (m) measurements of the same time (and place).
there are multiple measurements at the same time (and place).
Returns:
np.ndarray: raw data with uncertainty in a 2D ndarray with shape (2, n).
np.ndarray: mean of raw data with standard deviation in a 2D ndarray with shape (2, n).
"""
# TODO: Complete the function.
# This line of code throws an exception. This is just to make sure you can see
# all the code you need to refine. If you already know how to implement the program
# or have done so, then you can safely delete the three lines of code below, as well
# as this comment.
# TODO: Calculate the mean and standard deviation of the first dimension and return the result as a
# two-dimensional (2, n)-shaped ndarray.
raise NotImplementedError(
"Delete these 3 lines if you have finished the code or want to test it.".upper()
)
......@@ -97,31 +167,28 @@ def cal_mean_and_standard_deviation(data: np.ndarray) -> np.ndarray:
def get_start_end_temperature(
temperature_data: np.ndarray, threshold: float
temperature_data: np.ndarray, threshold: float = 0.05
) -> Tuple[float, float]:
"""Calculates the average high and low temperatures from a dataset.
"""Calculates the high and low temperatures from a dataset.
This function computes the average of the highest temperatures and the average of the lowest temperatures
This function computes the (average of) the highest temperatures and the (average of) the lowest temperatures
within a given threshold from the maximum and minimum temperatures recorded in the dataset. These are
considered as the ending and starting temperatures respectively.
Args:
temperature_data (np.ndarray): The temperature dataset as a 2D numpy array.
threshold (float): The threshold percentage used to identify temperatures close to the maximum
and minimum values as high and low temperatures respectively.
and minimum values as high and low temperatures respectively. Default to 0.05
Returns:
Tuple[float, float]: A tuple containing the average high temperature first and the average low
temperature second.
"""
# TODO: Complete the function.
# Hint: the temperature_data should contain the raw data of the sensors.
# numpy.ndarray.flatten() function may be useful for multidimensionale arrays.
# This line of code throws an exception. This is just to make sure you can see
# all the code you need to refine. If you already know how to implement the program
# or have done so, then you can safely delete the three lines of code below, as well
# as this comment.
# TODO: You don't have to implement this function exactly as docstring expresses it, it just gives
# an idea that you can refer to. The goal of this function is to obtain from the data the high and
# low temperatures necessary to calculate the heat capacity.
raise NotImplementedError(
"Delete these 3 lines if you have finished the code or want to test it.".upper()
)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment