### Install pyMannKendall from source Source: https://github.com/mmhs013/pymannkendall/blob/master/README.md Steps to clone the repository and perform a local installation. ```bash git clone https://github.com/mmhs013/pymannkendall cd pymannkendall python setup.py install ``` -------------------------------- ### Install pyMannKendall via pip Source: https://github.com/mmhs013/pymannkendall/blob/master/README.md Commands to install the package on Linux or Windows systems. ```python sudo pip install pymannkendall ``` ```python pip install pymannkendall ``` -------------------------------- ### Installation Source: https://github.com/mmhs013/pymannkendall/blob/master/README.md Instructions for installing the pyMannKendall library using pip, conda, or by cloning the repository. ```APIDOC ## Installation Install `pyMannKendall` using your preferred package manager. ### Using pip **Linux:** ```bash sudo pip install pymannkendall ``` **Windows:** ```bash pip install pymannkendall ``` ### Using conda ```bash conda install -c conda-forge pymannkendall ``` ### From Source 1. Clone the repository: ```bash git clone https://github.com/mmhs013/pymannkendall ``` 2. Navigate to the directory: ```bash cd pymannkendall ``` 3. Install the package: ```bash python setup.py install ``` ``` -------------------------------- ### Usage Example Source: https://github.com/mmhs013/pymannkendall/blob/master/README.md A basic example demonstrating how to use the `original_test` function from the pyMannKendall library. ```APIDOC ## Usage Example Here's a quick example of how to use the `pyMannKendall` library for a Mann-Kendall trend test. ### Basic Test ```python import numpy as np import pymannkendall as mk # Generate random data for demonstration data = np.random.rand(360, 1) # Perform the original Mann-Kendall test result = mk.original_test(data) # Print the full result (named tuple) print(result) # Access specific results by name print(result.slope) # Alternatively, unpack the results directly trend, h, p, z, Tau, s, var_s, slope, intercept = mk.original_test(data) print(f"Trend: {trend}, H-statistic: {h}, P-value: {p}") ``` ### Example Output ``` Mann_Kendall_Test(trend='no trend', h=False, p=0.9507221701045581, z=0.06179991635055463, Tau=0.0021974620860414733, s=142.0, var_s=5205500.0, slope=1.0353584906597959e-05, intercept=0.5232692553379981) 1.0353584906597959e-05 Trend: no trend, H-statistic: False, P-value: 0.9507221701045581 ``` ``` -------------------------------- ### Install pyMannKendall via conda Source: https://github.com/mmhs013/pymannkendall/blob/master/README.md Command to install the package using the conda-forge channel. ```bash conda install -c conda-forge pymannkendall ``` -------------------------------- ### Perform Mann-Kendall test Source: https://github.com/mmhs013/pymannkendall/blob/master/README.md Basic example of generating data and running the original Mann-Kendall test. ```python import numpy as np import pymannkendall as mk # Data generation for analysis data = np.random.rand(360,1) result = mk.original_test(data) print(result) ``` -------------------------------- ### Correlated Seasonal Mann-Kendall Test Setup Source: https://context7.com/mmhs013/pymannkendall/llms.txt Initializes monthly data for a correlated seasonal Mann-Kendall test. This setup is for demonstrating the test's application to seasonal data with potential inter-seasonal correlations. ```python import numpy as np import pymannkendall as mk np.random.seed(42) n_years = 5 months = 12 n = n_years * months ``` -------------------------------- ### Access test results Source: https://github.com/mmhs013/pymannkendall/blob/master/README.md Examples of accessing specific attributes from the returned named tuple or unpacking the results. ```python print(result.slope) ``` ```python trend, h, p, z, Tau, s, var_s, slope, intercept = mk.original_test(data) ``` -------------------------------- ### Display First Few Rows of Shampoo Sales Data Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Use `.head()` to display the first few rows of the Shampoo_data DataFrame. This provides a quick look at the sales data. ```python Shampoo_data.head() ``` -------------------------------- ### Import Libraries and Load Datasets Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Imports necessary libraries and loads three datasets (Births, Shampoo, Passengers) into pandas DataFrames. Ensure the dataset files are in the correct directory. ```python import numpy as np import pandas as pd import pymannkendall as mk import matplotlib.pyplot as plt import statsmodels.api as sm %matplotlib inline # read all datasets Birth_data = pd.read_csv("daily-total-female-births.csv",parse_dates=['Date'],index_col='Date') Shampoo_data = pd.read_csv("shampoo.csv",parse_dates=['Month'],index_col='Month') Passenger_data = pd.read_csv("AirPassengers.csv",parse_dates=['Month'],index_col='Month') ``` -------------------------------- ### Display First Few Rows of Birth Data Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Use `.head()` to display the first few rows of the Birth_data DataFrame. This is useful for a quick inspection of the data. ```python Birth_data.head() ``` -------------------------------- ### Compare Pre-Whitening Methods Source: https://context7.com/mmhs013/pymannkendall/llms.txt Compares the results of standard pre-whitening and trend-free pre-whitening modification tests. Ensure data is preprocessed before applying these methods. ```python import pymannkendall as mk pw_result = mk.pre_whitening_modification_test(data, alpha=0.05) tfpw_result = mk.trend_free_pre_whitening_modification_test(data, alpha=0.05) print("Pre-Whitening:") print(f" Trend: {pw_result.trend}, Tau: {pw_result.Tau:.4f}, p: {pw_result.p:.6f}") print("\nTrend-Free Pre-Whitening:") print(f" Trend: {tfpw_result.trend}, Tau: {tfpw_result.Tau:.4f}, p: {tfpw_result.p:.6f}") print(f" Slope: {tfpw_result.slope:.4f}") ``` -------------------------------- ### Display First Few Rows of Passenger Data Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Use `.head()` to display the first few rows of the Passenger_data DataFrame. This is useful for inspecting the monthly passenger numbers. ```python Passenger_data.head() ``` -------------------------------- ### Plot Shampoo Sales Time Series Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Visualize the Shampoo_data time series using a plot. This helps in observing trends and seasonality in the sales data. Set `figsize` for better readability. ```python Shampoo_data.plot(figsize=(12,8)); ``` -------------------------------- ### Plot Birth Data Time Series Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Visualize the Birth_data time series using a plot. This helps in observing patterns and trends over time. Set `figsize` for better readability. ```python Birth_data.plot(figsize=(12,8)); ``` -------------------------------- ### Mann-Kendall Test Functions Source: https://github.com/mmhs013/pymannkendall/blob/master/README.md Details on the common input parameters and return values for all Mann-Kendall test functions in the pyMannKendall library. ```APIDOC ## Mann-Kendall Test Functions All Mann-Kendall test functions share common input parameters and return a named tuple with detailed test results. ### Input Parameters - **x** (vector): A vector (list, numpy array, or pandas Series) containing the data for the test. - **alpha** (float): The significance level for the test. Defaults to 0.05. - **lag** (int): The number of first significant lags. Only available in `hamed_rao_modification_test` and `yue_wang_modification_test`. - **period** (int): The seasonal cycle period. For monthly data, it's 12; for weekly data, it's 52. Only available in seasonal tests. ### Return Value All Mann-Kendall tests return a named tuple containing the following fields: - **trend** (string): Indicates the type of trend ('increasing', 'decreasing', or 'no trend'). - **h** (boolean): True if a trend is present, False otherwise. - **p** (float): The p-value of the significance test. - **z** (float): The normalized test statistic. - **Tau** (float): Kendall's Tau correlation coefficient. - **s** (float): Mann-Kendall's score. - **var_s** (float): The variance of S. - **slope** (float): The Theil-Sen estimator/slope. - **intercept** (float): The intercept of the Kendall-Theil Robust Line. For seasonal tests, the full period cycle is considered a unit time step. ### Sen's Slope Function - **sen_slope(x, period=12)**: Requires a data vector `x`. The optional `period` parameter defaults to 12. Returns only the slope value. - **seasonal_sen_slope(x, period=12)**: Similar to `sen_slope` but for seasonal data. Returns only the slope value. ``` -------------------------------- ### Plot Shampoo Sales Data with Trend Line Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Visualize the Shampoo_data and overlay a trend line calculated using the Hamed and Rao Modified MK Test. This helps in visually assessing the trend. ```python data = Shampoo_data fig, ax = plt.subplots(figsize=(12, 8)) res = mk.hamed_rao_modification_test(data) trend_line = np.arange(len(data)) * res.slope + res.intercept ax.plot(data) ax.plot(data.index, trend_line) ax.legend(['data', 'trend line']) ``` -------------------------------- ### Run tests manually Source: https://github.com/mmhs013/pymannkendall/blob/master/README.md Command to execute the test suite using pytest. ```bash pytest -v ``` -------------------------------- ### Plot Air Passenger Data Time Series Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Visualize the Passenger_data time series using a plot. This helps in observing trends and seasonality, particularly the yearly seasonality in monthly data. Set `figsize` for better readability. ```python Passenger_data.plot(figsize=(12,8)); ``` -------------------------------- ### Perform Pre-Whitening Modified MK Test on Shampoo Sales Data Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Apply the Pre-Whitening Modified Mann Kendall test to the Shampoo_data. This method addresses autocorrelation by pre-whitening the series. ```python mk.pre_whitening_modification_test(Shampoo_data) ``` -------------------------------- ### Cite pyMannKendall Source: https://github.com/mmhs013/pymannkendall/blob/master/README.md BibTeX citation format for the pyMannKendall package. ```bibtex @article{Hussain2019pyMannKendall, journal = {Journal of Open Source Software}, doi = {10.21105/joss.01556}, issn = {2475-9066}, number = {39}, publisher = {The Open Journal}, title = {pyMannKendall: a python package for non parametric Mann Kendall family of trend tests.}, url = {http://dx.doi.org/10.21105/joss.01556}, volume = {4}, author = {Hussain, Md. and Mahmud, Ishtiak}, pages = {1556}, date = {2019-07-25}, year = {2019}, month = {7}, day = {25}, } ``` -------------------------------- ### Perform Seasonal Mann-Kendall Test and Visualize Trend Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Uses the seasonal_test function to calculate trend statistics and plots the data against the calculated trend line. ```python data = Passenger_data period = 12 fig, ax = plt.subplots(figsize=(12, 8)) res = mk.seasonal_test(data, period=period) trend_line = np.arange(len(data)) / period * res.slope + res.intercept ax.plot(data) ax.plot(data.index, trend_line) ax.legend(['data', 'trend line']) ``` -------------------------------- ### Comprehensive Trend Analysis Workflow - Python Source: https://context7.com/mmhs013/pymannkendall/llms.txt Use this function to automatically select the most appropriate Mann-Kendall trend test based on data properties. It handles seasonality and autocorrelation, returning the recommended test results. ```python import numpy as np import pymannkendall as mk def analyze_trend(data, alpha=0.05, check_autocorrelation=True, seasonal_period=None): """ Comprehensive trend analysis workflow. Parameters: ----------- data : array-like Time series data alpha : float Significance level check_autocorrelation : bool Whether to check and handle autocorrelation seasonal_period : int or None Period for seasonal data (e.g., 12 for monthly) Returns: -------- dict : Results from the most appropriate test """ results = {} # Step 1: Original test as baseline orig = mk.original_test(data, alpha=alpha) results['original'] = orig # Step 2: If seasonal data, apply seasonal test if seasonal_period: seasonal = mk.seasonal_test(data, period=seasonal_period, alpha=alpha) results['seasonal'] = seasonal results['recommended'] = seasonal results['test_used'] = 'seasonal_test' return results # Step 3: Check for autocorrelation using lag-1 data_array = np.asarray(data).flatten() n = len(data_array) if check_autocorrelation and n > 10: # Calculate lag-1 autocorrelation y = data_array - data_array.mean() acf1 = np.correlate(y[:-1], y[1:])[0] / np.correlate(y, y)[0] # If significant autocorrelation (|acf1| > 1.96/sqrt(n)) if abs(acf1) > 1.96 / np.sqrt(n): # Apply modified tests hr = mk.hamed_rao_modification_test(data, alpha=alpha) tfpw = mk.trend_free_pre_whitening_modification_test(data, alpha=alpha) results['hamed_rao'] = hr results['trend_free_pw'] = tfpw results['recommended'] = tfpw # Generally preferred results['test_used'] = 'trend_free_pre_whitening' results['autocorrelation_detected'] = True return results # Step 4: No autocorrelation - use original test results['recommended'] = orig results['test_used'] = 'original_test' results['autocorrelation_detected'] = False return results # Example usage with different data types np.random.seed(42) # Non-seasonal data without autocorrelation simple_data = np.arange(100) * 0.3 + np.random.normal(0, 5, 100) result1 = analyze_trend(simple_data) print("=== Simple Data ===") print(f"Test used: {result1['test_used']}") print(f"Trend: {result1['recommended'].trend}, p={result1['recommended'].p:.6f}") # Data with autocorrelation autocorr_data = np.zeros(100) autocorr_data[0] = 0 for i in range(1, 100): autocorr_data[i] = 0.7 * autocorr_data[i-1] + np.random.normal(0, 1) + 0.05 * i result2 = analyze_trend(autocorr_data) print("\n=== Autocorrelated Data ===") print(f"Test used: {result2['test_used']}") print(f"Trend: {result2['recommended'].trend}, p={result2['recommended'].p:.6f}") # Seasonal monthly data seasonal_data = np.sin(np.linspace(0, 24*np.pi, 144)) * 10 + np.arange(144) * 0.1 + np.random.normal(0, 2, 144) result3 = analyze_trend(seasonal_data, seasonal_period=12) print("\n=== Seasonal Data ===") print(f"Test used: {result3['test_used']}") print(f"Trend: {result3['recommended'].trend}, p={result3['recommended'].p:.6f}") print(f"Slope (per year): {result3['recommended'].slope:.4f}") ``` -------------------------------- ### Perform Seasonal Mann Kendall Test on Passenger Data Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Apply the Seasonal Mann Kendall test to the Passenger_data. Set `period=12` as the data is monthly, which is crucial for detecting seasonal trends accurately. ```python mk.seasonal_test(Passenger_data,period=12) ``` -------------------------------- ### Perform Yue and Wang Modified MK Test on Shampoo Sales Data Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Apply the Yue and Wang Modified Mann Kendall test to the Shampoo_data. This is another option for handling autocorrelation in time series data. ```python mk.yue_wang_modification_test(Shampoo_data) ``` -------------------------------- ### Seasonal Mann-Kendall Test for Monthly Data Source: https://context7.com/mmhs013/pymannkendall/llms.txt Applies the seasonal Mann-Kendall test to monthly time series data. Requires specifying the period (e.g., 12 for monthly data). ```python import numpy as np import pymannkendall as mk np.random.seed(42) years = 10 months = 12 n = years * months seasonal_pattern = np.array([10, 12, 18, 25, 32, 38, 40, 38, 30, 22, 15, 11]) time_index = np.arange(n) trend = 0.5 * time_index / months seasonal = np.tile(seasonal_pattern, years) noise = np.random.normal(0, 3, n) monthly_data = seasonal + trend + noise result = mk.seasonal_test(monthly_data, period=12, alpha=0.05) print(f"Trend: {result.trend}") print(f"p-value: {result.p:.6f}") print(f"Slope (per year): {result.slope:.4f}") print(f"Intercept: {result.intercept:.4f}") ``` -------------------------------- ### Estimate Trend with Theil-Sen Slope Source: https://context7.com/mmhs013/pymannkendall/llms.txt Calculates a robust monotonic trend slope that is resistant to outliers. Useful for trend line visualization. ```python import numpy as np import pymannkendall as mk # Data with trend and outliers np.random.seed(42) n = 50 data = np.arange(n) * 2.5 + np.random.normal(0, 5, n) # Add outliers data[10] = 200 data[30] = -100 # Estimate slope and intercept slope, intercept = mk.sens_slope(data) print(f"Theil-Sen Slope: {slope:.4f}") print(f"Intercept: {intercept:.4f}") # Use for trend line visualization import matplotlib.pyplot as plt x = np.arange(n) trend_line = x * slope + intercept plt.figure(figsize=(10, 6)) plt.scatter(x, data, label='Data (with outliers)', alpha=0.7) plt.plot(x, trend_line, 'r-', linewidth=2, label=f'Trend line (slope={slope:.2f})') plt.legend() plt.xlabel('Time') plt.ylabel('Value') plt.title('Theil-Sen Slope Estimation (Robust to Outliers)') plt.show() ``` -------------------------------- ### Apply Correlated Seasonal Mann-Kendall Test Source: https://context7.com/mmhs013/pymannkendall/llms.txt Performs a Mann-Kendall test on data with inter-seasonal correlation. Requires the period parameter to define the seasonal cycle. ```python seasonal_data = np.zeros(n) seasonal_data[0] = 50 for i in range(1, n): seasonal_effect = 10 * np.sin(2 * np.pi * i / 12) trend = 0.2 * i correlation = 0.5 * seasonal_data[i-1] if i > 0 else 0 seasonal_data[i] = 0.3 * correlation + seasonal_effect + trend + np.random.normal(0, 3) # Apply correlated seasonal test result = mk.correlated_seasonal_test(seasonal_data, period=12, alpha=0.05) print(f"Trend: {result.trend}") print(f"p-value: {result.p:.6f}") print(f"Tau: {result.Tau:.4f}") print(f"Slope (per year): {result.slope:.4f}") ``` -------------------------------- ### Perform Hamed and Rao Modified MK Test on Shampoo Sales Data Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Apply the Hamed and Rao Modified Mann Kendall test to the Shampoo_data. This test is suitable for data with autocorrelation. ```python mk.hamed_rao_modification_test(Shampoo_data) ``` -------------------------------- ### Seasonal Mann-Kendall Test for Weekly Data Source: https://context7.com/mmhs013/pymannkendall/llms.txt Applies the seasonal Mann-Kendall test to weekly time series data. Requires specifying the period (e.g., 52 for weekly data). ```python import numpy as np import pymannkendall as mk weekly_data = np.random.rand(520) + np.arange(520) * 0.001 weekly_result = mk.seasonal_test(weekly_data, period=52, alpha=0.05) print(f"\nWeekly data - Trend: {weekly_result.trend}") ``` -------------------------------- ### Perform Trend Free Pre-Whitening Modified MK Test on Shampoo Sales Data Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Apply the Trend Free Pre-Whitening Modified Mann Kendall test to the Shampoo_data. This method is used to remove trend and autocorrelation before applying the test. ```python mk.trend_free_pre_whitening_modification_test(Shampoo_data) ``` -------------------------------- ### Estimate Seasonal Theil-Sen Slope Source: https://context7.com/mmhs013/pymannkendall/llms.txt Estimates trend magnitude for seasonal data by calculating slopes within each season. Supports custom periods for different data frequencies. ```python import numpy as np import pymannkendall as mk # Monthly data spanning 8 years np.random.seed(42) years = 8 period = 12 n = years * period # Seasonal data with trend seasonal_pattern = np.sin(np.linspace(0, 2*np.pi, period)) * 20 data = np.tile(seasonal_pattern, years) + np.arange(n) * 0.5 + np.random.normal(0, 3, n) # Estimate seasonal slope (slope is per full seasonal cycle/year) slope, intercept = mk.seasonal_sens_slope(data, period=12) print(f"Seasonal Slope (per year): {slope:.4f}") print(f"Intercept: {intercept:.4f}") # For weekly data weekly_data = np.random.rand(260) + np.arange(260) * 0.01 # 5 years weekly weekly_slope, weekly_intercept = mk.seasonal_sens_slope(weekly_data, period=52) print(f"\nWeekly data slope (per year): {weekly_slope:.4f}") ``` -------------------------------- ### Trend-Free Pre-Whitening Modification Test Source: https://context7.com/mmhs013/pymannkendall/llms.txt Removes trend, then pre-whitens, and re-applies the trend to avoid removing signal. Suitable for data with both trend and autocorrelation. ```python import numpy as np import pymannkendall as mk # Data with both trend and autocorrelation np.random.seed(42) n = 180 data = np.zeros(n) data[0] = 50 for i in range(1, n): data[i] = 0.75 * data[i-1] + np.random.normal(12, 3) + 0.15 * i # The code for applying the Trend-Free Pre-Whitening test is missing in the provided text. ``` -------------------------------- ### Plot Autocorrelation Function (ACF) for Shampoo Sales Data Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Generate an ACF plot for the Shampoo_data to identify autocorrelation. Set `lags` to control the number of lags displayed and `figsize` for plot dimensions. This is important for choosing the correct modified MK test. ```python fig, ax = plt.subplots(figsize=(12, 8)) sm.graphics.tsa.plot_acf(Shampoo_data, lags=20, ax=ax); ``` -------------------------------- ### Yue and Wang Modified MK Test for Autocorrelation Source: https://context7.com/mmhs013/pymannkendall/llms.txt Handles serial autocorrelation with a different variance correction method. Yue and Wang suggest lag=1 for hydrological data. ```python import numpy as np import pymannkendall as mk # Hydrological data with serial correlation np.random.seed(42) n = 200 streamflow = np.zeros(n) streamflow[0] = 100 for i in range(1, n): streamflow[i] = 0.6 * streamflow[i-1] + np.random.normal(50, 10) + 0.05 * i # Apply Yue-Wang modification result = mk.yue_wang_modification_test(streamflow, alpha=0.05) print(f"Trend: {result.trend}") print(f"p-value: {result.p:.6f}") print(f"Kendall Tau: {result.Tau:.4f}") # With specified lag (Yue and Wang suggest lag=1) result_1lag = mk.yue_wang_modification_test(streamflow, alpha=0.05, lag=1) print(f"With lag=1 - Trend: {result_1lag.trend}, Slope: {result_1lag.slope:.4f}") ``` -------------------------------- ### Perform Original Mann Kendall Test on Birth Data Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Apply the original Mann Kendall test to the Birth_data to check for a significant trend. Set `alpha` for the significance level. The test assumes no autocorrelation. ```python mk.original_test(Birth_data, alpha=0.05) ``` -------------------------------- ### Original Mann-Kendall Test Source: https://context7.com/mmhs013/pymannkendall/llms.txt Use for independent observations without serial correlation or seasonal effects. Requires numpy and pymannkendall. ```python import numpy as np import pymannkendall as mk # Generate sample time series data with an increasing trend np.random.seed(42) data = np.arange(100) * 0.5 + np.random.normal(0, 5, 100) # Perform the original Mann-Kendall test result = mk.original_test(data, alpha=0.05) # Access results as named tuple print(f"Trend: {result.trend}") # 'increasing', 'decreasing', or 'no trend' print(f"Significant: {result.h}") # True if trend is significant print(f"p-value: {result.p:.6f}") # p-value of the test print(f"z-statistic: {result.z:.4f}") # Normalized test statistic print(f"Tau: {result.Tau:.4f}") # Kendall Tau correlation print(f"Slope: {result.slope:.4f}") # Theil-Sen slope estimate print(f"Intercept: {result.intercept:.4f}") # Alternative: unpack all results directly trend, h, p, z, Tau, s, var_s, slope, intercept = mk.original_test(data) ``` -------------------------------- ### Multivariate Mann-Kendall Test Source: https://context7.com/mmhs013/pymannkendall/llms.txt Analyzes trends across multiple time series simultaneously. Suitable for data from multiple monitoring stations or parameters. ```python import numpy as np import pymannkendall as mk np.random.seed(42) n_obs = 100 n_params = 5 data = np.zeros((n_obs, n_params)) for j in range(n_params): noise = np.random.normal(0, 2, n_obs) trend = np.arange(n_obs) * (0.1 + 0.02 * j) data[:, j] = trend + noise result = mk.multivariate_test(data, alpha=0.05) print(f"Overall Trend: {result.trend}") print(f"p-value: {result.p:.10f}") print(f"Combined Tau: {result.Tau:.4f}") print(f"Slope: {result.slope:.4f}") ``` -------------------------------- ### Plot Autocorrelation Function (ACF) for Birth Data Source: https://github.com/mmhs013/pymannkendall/blob/master/Examples/Example_pyMannKendall.ipynb Generate an ACF plot for the Birth_data to identify autocorrelation. Set `lags` to control the number of lags displayed and `figsize` for plot dimensions. ```python fig, ax = plt.subplots(figsize=(12, 8)) sm.graphics.tsa.plot_acf(Birth_data, lags=20, ax=ax); ``` -------------------------------- ### Pre-Whitening Modification Test Source: https://context7.com/mmhs013/pymannkendall/llms.txt Removes lag-1 autocorrelation before applying the Mann-Kendall test, as proposed by Yue and Wang (2002). Useful for autocorrelated climate data. ```python import numpy as np import pymannkendall as mk # Autocorrelated climate data np.random.seed(42) n = 150 temperature = np.zeros(n) temperature[0] = 15 for i in range(1, n): temperature[i] = 0.8 * temperature[i-1] + np.random.normal(3, 2) + 0.02 * i # Apply pre-whitening modification result = mk.pre_whitening_modification_test(temperature, alpha=0.05) print(f"Trend: {result.trend}") print(f"Significant: {result.h}") print(f"p-value: {result.p:.6f}") print(f"Slope: {result.slope:.4f}") ``` -------------------------------- ### Regional Mann-Kendall Test Source: https://context7.com/mmhs013/pymannkendall/llms.txt Calculates overall trends at a regional scale by combining data from multiple locations. Assumes annual data for each station. ```python import numpy as np import pymannkendall as mk np.random.seed(42) n_years = 50 n_stations = 5 regional_data = np.zeros((n_years, n_stations)) for station in range(n_stations): base_level = 100 + np.random.normal(0, 20) trend = 0.8 * np.arange(n_years) noise = np.random.normal(0, 5, n_years) regional_data[:, station] = base_level + trend + noise result = mk.regional_test(regional_data, alpha=0.05) print(f"Regional Trend: {result.trend}") print(f"Significant: {result.h}") print(f"p-value: {result.p:.10f}") print(f"Regional Slope: {result.slope:.4f}") ``` -------------------------------- ### Correlated Multivariate Mann-Kendall Test Source: https://context7.com/mmhs013/pymannkendall/llms.txt Handles multivariate data where parameters are correlated. Accounts for cross-correlation in variance calculations. ```python import numpy as np import pymannkendall as mk np.random.seed(42) n = 100 shared_trend = np.arange(n) * 0.1 shared_noise = np.random.normal(0, 1, n) param1 = shared_trend + shared_noise + np.random.normal(0, 0.5, n) param2 = shared_trend * 0.8 + shared_noise * 0.9 + np.random.normal(0, 0.5, n) correlated_data = np.column_stack([param1, param2]) result = mk.correlated_multivariate_test(correlated_data, alpha=0.05) print(f"Trend: {result.trend}") print(f"p-value: {result.p:.6f}") print(f"Tau: {result.Tau:.4f}") print(f"Slope: {result.slope:.4f}") ``` -------------------------------- ### Hamed and Rao Modified MK Test for Autocorrelation Source: https://context7.com/mmhs013/pymannkendall/llms.txt Addresses serial autocorrelation using variance correction. Specify the number of significant lags if known, otherwise defaults to all significant lags. ```python import numpy as np import pymannkendall as mk # Time series with autocorrelation (e.g., monthly temperature data) np.random.seed(42) n = 120 data = np.zeros(n) data[0] = np.random.normal(0, 1) for i in range(1, n): data[i] = 0.7 * data[i-1] + np.random.normal(0, 1) + 0.1 * i # Apply Hamed-Rao modification with default (all significant lags) result = mk.hamed_rao_modification_test(data, alpha=0.05) print(f"Trend: {result.trend}, p-value: {result.p:.6f}") # Specify first 3 significant lags (as recommended by Hamed and Rao) result_3lag = mk.hamed_rao_modification_test(data, alpha=0.05, lag=3) print(f"With lag=3 - Trend: {result_3lag.trend}, p-value: {result_3lag.p:.6f}") print(f"Slope: {result_3lag.slope:.4f}") ``` -------------------------------- ### Perform Partial Mann-Kendall Test Source: https://context7.com/mmhs013/pymannkendall/llms.txt Removes the influence of a confounding covariate from the trend analysis. Input data must be a 2-column matrix containing the response variable and the covariate. ```python import numpy as np import pymannkendall as mk # Response variable affected by a confounding factor np.random.seed(42) n = 100 # Covariate (e.g., population growth) covariate = np.arange(n) * 0.5 + np.random.normal(0, 2, n) # Response variable influenced by both time trend and covariate time_trend = np.arange(n) * 0.3 covariate_effect = covariate * 0.4 response = time_trend + covariate_effect + np.random.normal(0, 3, n) # Combine into 2-column matrix: [response, covariate] data = np.column_stack([response, covariate]) # Apply partial test to find trend after removing covariate influence result = mk.partial_test(data, alpha=0.05) print(f"Trend (after controlling for covariate): {result.trend}") print(f"p-value: {result.p:.6f}") print(f"Tau: {result.Tau:.4f}") print(f"Slope: {result.slope:.4f}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.