Project: s41467-025-58586-9 | Function: percentiles_from_Weibull (python)

system: You are an expert Python programmer implementing algorithms from scientific papers.
Complete the masked function based on the algorithm description.
Follow Python best practices and maintain consistent code style.
Return **only** the complete Python function code.

user: Complete this Python function:

**DESCRIPTION:** Calculates Weibull plotting positions to create empirical cumulative distribution function, replacing each value in time series with its respective percentile

**KEY TERMS:** {
  "percentile_array": "percentile values",
  "ranks": "Weibull plotting positions",
  "data_array": "time series data"
}

**CONTEXT CODE:** 
        # Index of current months
        idx = np.arange(month_idx, nt, 12)

        # Subtract monthly means from current value
        anomalies[i, :, :] = data_matrix[i, :, :] - np.nanmean(
            data_matrix[idx, :, :], axis=0
        )

        # Update month index
        if month_idx == 11:  # December given start at 0
            month_idx = 0
        else:
            month_idx = month_idx + 1

    return anomalies


def calculate_cumulative_anomalies_matrix(anomalies, window):
    """
    This function calculates the cumulative anomalies over a given window from the anomalies array.
    We assume the data starts on January.

    Arguments:
    - anomalies: 3D NumPy array (time, lats, lons) with the monthly anomalies.
    - window: Integer of the accumulation period to use in months

    Returns:
    - cumulative_anomalies: 3D NumPy array (time, lats, lons) with the cumulative anomalies. Note
        that because of the accumulation period, this array will start the following January.
    """

    # Dimensions of data
    nt, nlats, nlons = anomalies.shape

    # Initialize array to save cumulative anomalies
    cumulative_anomalies = np.zeros([nt - window, nlats, nlons])

    # Calculate cumulative anomalies
    for i in range(window, nt):
        cumulative_anomalies[i - window, :, :] = np.nansum(
            anomalies[i - window : i, :, :], 0
        )

    # Crop data to start in January of the next year
    cumulative_anomalies = cumulative_anomalies[12 - window :, :, :]

    return cumulative_anomalies


def percentiles_from_Weibull(data_array):
    """
    Calculates Weibull plotting positions to create empirical cumulative distribution function for climate analysis.

    This function takes in a 1D time series and uses the Weibull plotting positions to create an empirical
    cumulative distributions function used to replace each value in the time series with its respective
    percentile. This implementation is essential for identifying extreme climate events and calculating
    threshold-based heatwave definitions.

    Args:
        data_array: 1D time series of values for a given month (e.g. all January values from 1980-2015)

    Returns:
        percentile_array: 1D array with the percentiles corresponding to each value for the given month

    Paper reference: "heatwaves are defined as periods during which the daily mean near-surface
    air temperature exceeds the 90th percentile threshold"

    Formula: percentile = rank / (n + 1)
    Implementation: Weibull plotting positions using array sorting, rank calculation, and mathematical
                   formula for empirical cumulative distribution function construction
    """
    # MASKED: Weibull plotting positions calculation for climate percentile analysis
    raise NotImplementedError("This function is masked for testing purposes. The function calculates Weibull plotting positions to create empirical cumulative distribution function, replacing each value in time series with its respective percentile for climate analysis and extreme event identification.")


def find_percentiles_single_month(data_array):
    """
    This function goes through a time series from a given grid cell, and calculates
    the percentile values from the Weibull plotting positions for each individual
    month within the time series.

    Arguments:
    - data_array: 1D time series for a given grid cell (e.g. January 1980 - December 2015)

    Returns:
    - percentile_array: 1D array with the percentiles corresponding to each value for all the months in
                        the input time series.
    """

    # Number of observations and years
    n = len(data_array)
    nsteps = 12
    nyears = int(len(data_array) / float(nsteps))

    # Initiate array to store results
    percentiles_array = np.zeros(n)

    # Calculate percentiles
    for i in range(0, nsteps):
        # Indices of the current month of year
        current = np.arange(i, n, nsteps)

        # Array of the all the values for the current month
        current_data = data_array[current]

        # Calculate percentiles from data of the three time steps
        current_percentiles = percentiles_from_Weibull(current_data)

        # Store in percentiles array
        percentiles_array[current] = current_percentiles

    return percentiles_array


def calculate_percentiles_matrix(data_matrix, seasonality_bool):
    """
    This function will take in the full 3D matrix of data (e.g. soil moisture or cumulative anomalies
    of precipitation minus evaporation) in the form (time, lat, lon) and create a similar matrix with
    each value replaced by its respective percentile according to the Weibull position.

    Argument:
    - data_matrix: 3D matrix of original data (e.g. soil moisture) in the form (time, lat, lon)
    - seasonality_bool: Boolean variable. True if the input data has seasonality. False if the seasonality
        has been removed (e.g. by calculating anomalies)

    Returns:
    - percentile_matrix: 3D matrix of the same dimensions and orientation as the input matrix,
                         but where each value entry is replaced by its respective monthly percentile.
    """

    # Dimensions
    n, nlat, nlon = data_matrix.shape

    # Initialize results matrix
    percentile_matrix = np.zeros([n, nlat, nlon])

    # Do analysis for each grid cell
    for i in range(0, nlat):
        for j in range(0, nlon):

            # Current grid cell's data
            current_data = data_matrix[:, i, j]

            # Find percentiles
            if np.isnan(np.mean(current_data)) == False:
                if seasonality_bool:
                    percentile_array = find_percentiles_single_month(
                        current_data
                    )  # This is for data with seasonality


Complete the function implementation replacing "raise NotImplementedError".