### Install paretoset with Numba Source: https://context7.com/tommyod/paretoset/llms.txt Installs the paretoset library along with Numba for optional JIT acceleration, recommended for large datasets. ```bash pip install paretoset numba ``` -------------------------------- ### Install paretoset using pip Source: https://github.com/tommyod/paretoset/blob/master/docs/index.md Install the paretoset library using pip. This command should be run in your terminal or command prompt. ```bash pip install paretoset ``` -------------------------------- ### Find Top Performing Salespeople (Min Salary, Max Sales) Source: https://github.com/tommyod/paretoset/blob/master/docs/index.md Identify top-performing salespeople by minimizing salary and maximizing sales within each department. This example uses pandas DataFrames and specifies mixed minimization and maximization senses. ```python from paretoset import paretoset import pandas as pd salespeople = pd.DataFrame( { "salary": [94, 107, 67, 87, 153, 62, 43, 115, 78, 77, 119, 127], "sales": [123, 72, 80, 40, 64, 104, 106, 135, 61, 81, 162, 60], "department": ["c", "c", "c", "b", "b", "a", "a", "c", "b", "a", "b", "a"], } ) mask = paretoset(salespeople, sense=["min", "max", "diff"]) top_performers = salespeople[mask] ``` -------------------------------- ### Using ranks for tiered selection in optimization Source: https://context7.com/tommyod/paretoset/llms.txt Demonstrates how to use paretorank to identify solutions within the top two Pareto fronts for selection in optimization tasks. ```python rng = np.random.default_rng(0) population = rng.random((100, 3)) # 100 solutions, 3 objectives ranks = paretorank(population, sense=["min", "min", "max"]) top_two_fronts = population[ranks <= 2] print(f"Solutions in top 2 fronts: {len(top_two_fronts)}") ``` -------------------------------- ### Apply Pareto Set Optimization to Computers Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Applies the paretoset function to find the Pareto optimal set for computer sales data. It optimizes for maximum RAM and HDD, and minimum weight and price. The number of non-dominated solutions is then printed. ```python mask = paretoset(df_computers[["RAM", "HDD", "weight", "price"]], sense=[max, max, min, min]) print(sum(mask)) ``` -------------------------------- ### Visualizing Domination in a Minimization Problem Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Illustrates the concept of domination in a 2D minimization problem by plotting regions representing dominated and dominating points relative to a reference point (0,0). Requires matplotlib.pyplot and a predefined COLORS list. ```python fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Domination in a minimization problem") left, bottom, width, height = (-1, -1, 1, 1) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[0], alpha=0.25, zorder=7) ax.add_patch(rect) ax.text(x=-0.775, y=-0.55, s=r"Dominates $\mathbf{x}$", fontsize=14, zorder=10) left, bottom, width, height = (0, 0, 1, 1) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[1], alpha=0.25, zorder=7) ax.add_patch(rect) ax.text(x=0.15, y=0.45, s=r"Dominated by $\mathbf{x}$", fontsize=14, zorder=10) left, bottom, width, height = (0, -1, 1, 1) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[2], alpha=0.25, zorder=7) ax.add_patch(rect) left, bottom, width, height = (-1, 0, 1, 1) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[2], alpha=0.25, zorder=7) ax.add_patch(rect) ax.scatter([0], [0], color="k", zorder=10) ax.set_xlabel(r"$x_1$") ax.set_ylabel(r"$x_2$") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("domination.pdf") plt.savefig("domination.png", dpi=200) ``` -------------------------------- ### Load apartment data into a DataFrame Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Creates a pandas DataFrame from a list of tuples, where each tuple represents an apartment with its price and square meters. This data is used for demonstrating Pareto set analysis. ```python # Data on apartment prices and square meters # from central Oslo, Norway (april 2020) apartments = [(13000, 38), (16000, 55), (29000, 74), (16600, 54), (16200, 68), (12300, 42), (15000, 42), (21000, 90), (13250, 43), (24000, 88), (20000, 85), (12800, 48), (12300, 32), (16700, 66), (13000, 40), (23000, 90), (16000, 70), (24000, 77), (24000, 84), (15500, 84), (19000, 89), (12800, 33), (12900, 35), (14800, 64), (27000, 86), (19800, 79), (18800, 79), (19800, 63), (12900, 42), (15500, 65)] # Load into a dataframe df_apartments = pd.DataFrame(apartments, columns=["price", "square_meters"]) ``` -------------------------------- ### Create Basic Apartment Scatter Plot Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Generates a scatter plot of apartment prices against square meters using matplotlib. This serves as a baseline visualization before applying optimization or annotations. ```python fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments1.pdf") ``` -------------------------------- ### Apply Pareto Set with Max/Max/Min Sense Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Applies the paretoset function to filter computers based on maximizing RAM and HDD, and minimizing price. It then displays the results in LaTeX format. ```python mask = paretoset(df_computers[["RAM", "HDD", "price"]], sense=[max, max, min]) print(df_computers[mask].to_latex(index=False,)) ``` -------------------------------- ### run_tests() Source: https://context7.com/tommyod/paretoset/llms.txt Executes the test suite for the paretoset library, including unit tests and doctests. ```APIDOC ## run_tests() ### Description Executes the test suite for the paretoset library, including unit tests and doctests. ### Request Example ```python import paretoset paretoset.run_tests() ``` ``` -------------------------------- ### Visualize Pareto Frontier with Linear Combinations Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Plots a scatter plot of apartments and overlays lines representing linear combinations of price and square meters. This helps visualize the Pareto frontier for a specific objective function. ```python fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.scatter([84], [15500], zorder=12, color=COLORS[1], s=75) x = np.linspace(0, 100) for i, diff in enumerate(np.linspace(7150, 15000, num=6)): ax.plot(x, diff + 99 * x, zorder=15, color=COLORS[1], alpha=1 - 0.15 * i) ax.annotate(r'$f(\mathrm{price}, \mathrm{sqm}) = 0.99 \, \mathrm{price} + 0.01 \, (-\mathrm{sqm})$', xy=(32, 22000), xycoords='data', zorder=50, fontsize=12 ) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments3.pdf") ``` -------------------------------- ### Basic Apartment Price vs. Square Meters Scatter Plot Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Creates a scatter plot to visualize apartment prices against their square meters, setting axis labels and a grid. Saves the plot to a PDF file. ```python fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.scatter([84], [15500], zorder=12, color="k", s=75) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments6.pdf") ``` -------------------------------- ### Load and Prepare Computer Data Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Loads computer data into a pandas DataFrame and displays its length. This is a prerequisite for applying the paretoset function. ```python computers = [("Apple MacBook Air 13,3 128GB", 13.3, 8, 128, None, 9990), ("Asus ZenBook Pure UX430UN-PURE2", 14, 8, 256, 1.3, 7999), ("HP Pavilion Gaming 15-cx0015no", 15.6, 8, 256, 2.22, 5999), ("Huawei D15 (53010TTV)", 14, 8, 256, 1.53, 5495), ("Apple MacBook Air 13.3 256GB", 13.3, 8, 256, 1.29, 12495), ("Asus Chromebook C523", 15.6, 4, 32, 1.43, 3495), ("Huawei MateBook 13 (18140)", 13, 8, 256, None, 8995), ("Asus ZenBook UX433FN-A6094T", 14, 8, 256, 1.3, 7999), ("Microsoft Surface Laptop 2", 13.5, 8, 128, 1.283, 7999), ("Lenovo Ideapad S145 (81W80028MX)", 15.6, 8, 256, 1.85, 4690), ("Huawei MateBook 13 (51204)", 13, 8, 512, 1.3, 9995), ("Apple MacBook Air (Mid 2017)", 13.3, 8, 128, 1.35, 9199), ("Acer Nitro 5 (NH.Q5XED.018)", 15.6, 16, 512, 2.2, 8499)] columns=["name", "screen", "RAM", "HDD", "weight", "price"] df_computers = pd.DataFrame(computers, columns=columns) len(df_computers) ``` -------------------------------- ### Apply Pareto Set with Distinct=True Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Applies the paretoset function with 'distinct=True' to filter computers, considering RAM, HDD, weight, and price. Missing values (NaN) are filled with 0. Results are displayed in LaTeX. ```python mask = paretoset(df_computers[["RAM", "HDD", "weight", "price"]].fillna(0), sense=[max, max, min, min], distinct=True) print(df_computers[mask].to_latex(index=False,)) ``` -------------------------------- ### Find Hotels in Pareto Set (Min Price, Min Distance) Source: https://github.com/tommyod/paretoset/blob/master/docs/index.md Use this snippet to identify hotels that are not worse than any other hotel in both price and distance to the beach. Requires pandas DataFrame and the paretoset function. ```python from paretoset import paretoset import pandas as pd hotels = pd.DataFrame({"price": [50, 53, 62, 87, 83, 39, 60, 44], "distance_to_beach": [13, 21, 19, 13, 5, 22, 22, 25]}) mask = paretoset(hotels, sense=["min", "min"]) paretoset_hotels = hotels[mask] ``` -------------------------------- ### Apply Pareto Set with Distinct=False Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Applies the paretoset function with 'distinct=False' to filter computers, considering RAM, HDD, weight, and price. Missing values (NaN) are filled with 0. Results are displayed in LaTeX. ```python mask = paretoset(df_computers[["RAM", "HDD", "weight", "price"]].fillna(0), sense=[max, max, min, min], distinct=False) print(df_computers[mask].to_latex(index=False,)) ``` -------------------------------- ### Run paretoset tests Source: https://context7.com/tommyod/paretoset/llms.txt Executes the full pytest suite for the paretoset library, including doctests. ```python import paretoset paretoset.run_tests() # Runs the full pytest suite including doctests ``` -------------------------------- ### Plotting Apartments Data with a Specific Point Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Generates a scatter plot of apartment prices versus square meters, marking a specific data point with a black marker. Saves the plot to a PDF file. ```python ax.scatter([64], [14800], zorder=12, color="k", s=75) edges = pd.DataFrame({"x":[84, 42, 90, 89], "y":[15500, 12300, 21000, 19000]}) edges = edges.sort_values("x") ax.plot(edges.x, edges.y, color=COLORS[1]) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments5.pdf") ``` -------------------------------- ### Compute Pareto Efficient Solutions in Multiobjective Optimization Source: https://github.com/tommyod/paretoset/blob/master/docs/index.md This snippet demonstrates how to find Pareto efficient solutions from a list of solutions with objective values. It uses numpy arrays and specifies minimization and maximization senses for the objectives. ```python from paretoset import paretoset import numpy as np from collections import namedtuple # Create Solution objects holding the problem solution and objective values Solution = namedtuple("Solution", ["solution", "obj_value"]) solutions = [Solution(solution=object, obj_value=np.random.randn(2)) for _ in range(999)] # Create an array of shape (solutions, objectives) and compute the non-dominated set objective_values_array = np.vstack([s.obj_value for s in solutions]) mask = paretoset(objective_values_array, sense=["min", "max"]) # Filter the list of solutions, keeping only the non-dominated solutions efficient_solutions = [solution for (solution, m) in zip(solutions, mask) if m] ``` -------------------------------- ### Applying Pareto Set to Apartment Data Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Filters apartment data to identify Pareto optimal solutions using the paretoset function with both minimization and maximization senses. Requires pandas DataFrame and matplotlib.pyplot. ```python fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") mask = paretoset(df_apartments, sense=[min, max]) ax.scatter(df_apartments[~mask].square_meters, df_apartments[~mask].price, alpha=0.5, color=COLORS[0], s=25) ax.scatter(df_apartments[mask].square_meters, df_apartments[mask].price, zorder=9, color="k", s=75) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments10.pdf") ``` -------------------------------- ### Highlighting a Region of Interest in Apartment Data Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Visualizes apartment data with a scatter plot, highlighting a specific point and adding a shaded rectangle to represent a region of interest. Saves the plot to a PDF file. ```python fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.scatter([84], [15500], zorder=12, color="k", s=75) # 15500 84 left, bottom, width, height = (0, 15500, 84, 20000) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[0], alpha=0.25, zorder=7) ax.add_patch(rect) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments7.pdf") ``` -------------------------------- ### Import necessary libraries Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Imports the pandas, paretoset, matplotlib, and numpy libraries for data manipulation, Pareto set calculations, and plotting. ```python import pandas as pd from paretoset import paretoset import matplotlib.pyplot as plt import numpy as np ``` -------------------------------- ### NSGA-II selection workflow: rank + crowding distance Source: https://context7.com/tommyod/paretoset/llms.txt Combines Pareto ranking and crowding distance calculation for NSGA-II-like selection. Identifies the Pareto front, computes diversity, and ranks solutions by crowding distance. ```python from paretoset import paretoset, crowding_distance import pandas as pd rng = np.random.default_rng(7) population = rng.random((50, 2)) # Step 1: Identify the Pareto front mask = paretoset(population, sense=["min", "min"]) front = population[mask] # Step 2: Compute crowding distances to maintain diversity distances = crowding_distance(front) # Step 3: Sort front by descending crowding distance (prefer spread-out solutions) order = np.argsort(-distances) ranked_front = pd.DataFrame(front[order], columns=["obj1", "obj2"]) ranked_front["crowding_distance"] = distances[order] print(ranked_front.head()) ``` -------------------------------- ### Counting Pareto Optimal Solutions Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Calculates the number of Pareto optimal solutions (True values in the mask) and the total number of data points. ```python sum(mask), len(df_apartments) ``` -------------------------------- ### Visualize Alternative Pareto Frontier Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Similar to the previous plot, this visualizes a different Pareto frontier by overlaying lines representing another linear combination of price and square meters. It highlights a different set of trade-offs. ```python fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.scatter([42], [12300], zorder=12, color=COLORS[1], s=75) x = np.linspace(0, 100) for i, diff in enumerate(np.linspace(11800, 20500, num=6)): ax.plot(x, diff + 9 * x, zorder=15, color=COLORS[1], alpha=1 - 0.15 * i) ax.annotate(r'$f(\mathrm{price}, \mathrm{sqm}) = 0.9 \, \mathrm{price} + 0.1 \, (-\mathrm{sqm})$', xy=(32, 22000), xycoords='data', zorder=50, fontsize=12 ) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments4.pdf") ``` -------------------------------- ### Identifying and Visualizing Dominated Apartments Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Plots apartment data, distinguishing between dominated and non-dominated apartments using different visual styles. A specific point and a region are also highlighted. Saves the plot to PDF and PNG. ```python fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") at_least_as_good = ((df_apartments.square_meters <= 84) & (df_apartments.price >= 15500)) dominated = at_least_as_good & ((df_apartments.square_meters < 84) | (df_apartments.price > 15500)) ax.scatter(df_apartments[~dominated].square_meters, df_apartments[~dominated].price, zorder=9) ax.scatter(df_apartments[dominated].square_meters, df_apartments[dominated].price, zorder=9, alpha=0.5, color=COLORS[0], s=25) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.scatter([84], [15500], zorder=12, color="k", s=75) # 15500 84 left, bottom, width, height = (0, 15500, 84, 20000) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[0], alpha=0.25, zorder=7) ax.add_patch(rect) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments8.pdf") plt.savefig("apartments8.png", dpi=200) ``` -------------------------------- ### paretorank(costs, sense=None, distinct=True, use_numba=True) Source: https://context7.com/tommyod/paretoset/llms.txt Returns an integer array assigning a Pareto rank to each observation. Rank 1 is the Pareto set; rank 2 is the Pareto set of the remaining data after removing rank 1; and so on. ```APIDOC ## paretorank(costs, sense=None, distinct=True, use_numba=True) ### Description Returns an integer array assigning a Pareto rank to each observation. Rank 1 is the Pareto set; rank 2 is the Pareto set of the remaining data after removing rank 1; and so on. This produces a full layered ordering of the data useful for NSGA-II–style selection and tiered filtering. ### Parameters #### Path Parameters - **costs** (pandas DataFrame or NumPy array) - Required - The input data for which to compute the Pareto ranks. - **sense** (list of strings, optional) - Optional - Specifies the optimization direction for each column ('min', 'max', or 'diff'). If None, defaults to 'min' for all columns. - **distinct** (boolean, optional) - Optional - If True (default), duplicate rows are deduplicated before computation. If False, duplicates are considered distinct. - **use_numba** (boolean, optional) - Optional - If True (default), attempts to use Numba for accelerated computation if available. ### Request Example ```python from paretoset import paretorank import pandas as pd import numpy as np # Example 1: Basic Pareto ranking costs = np.array([[2, 0], [1, 1], [0, 2], [3, 3]]) print(paretorank(costs)) # Example 2: Ranking candidates by multiple criteria candidates = pd.DataFrame({ "error_rate": [0.05, 0.10, 0.03, 0.08, 0.12], "latency_ms": [120, 80, 200, 90, 60], }) ranks = paretorank(candidates, sense=["min", "min"]) candidates["pareto_rank"] = ranks print(candidates.sort_values("pareto_rank")) # Example 3: Distinct parameter with duplicate rows print(paretorank([0, 0], distinct=True)) print(paretorank([0, 0], distinct=False)) ``` ### Response #### Success Response (integer array) - Returns an integer NumPy array where each element represents the Pareto rank of the corresponding observation. ### Response Example ``` # For Example 1: # array([1, 1, 1, 2]) # For Example 2: # error_rate latency_ms pareto_rank # 1 0.10 80 1 # 3 0.08 90 1 # 4 0.12 60 1 # 0 0.05 120 2 # 2 0.03 200 3 # For Example 3 (distinct=True): # array([1, 2]) ``` ``` -------------------------------- ### paretoset(costs, sense) Source: https://context7.com/tommyod/paretoset/llms.txt Filters a population of solutions to identify the Pareto optimal set. The `sense` parameter determines whether each objective should be minimized or maximized. ```APIDOC ## paretoset(costs, sense) ### Description Filters a population of solutions to identify the Pareto optimal set. The `sense` parameter determines whether each objective should be minimized or maximized. ### Parameters * **costs** (numpy.ndarray) - Input array of shape (solutions, objectives). * **sense** (list of str) - A list of strings, where each string is either 'min' or 'max', indicating the optimization sense for each objective. * **use_numba** (bool, optional) - Whether to use Numba for acceleration. Defaults to True. ### Request Example ```python from paretoset import paretoset import numpy as np costs = np.random.rand(10000, 4) mask = paretoset(costs, sense=["min", "min", "max", "min"], use_numba=False) ``` ### Response * **mask** (numpy.ndarray) - A boolean mask indicating which solutions are part of the Pareto optimal set. ``` -------------------------------- ### Counting Non-Dominated Apartments and Plotting Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Calculates and prints the number of non-dominated apartments. It then generates a scatter plot showing only the non-dominated apartments, along with a highlighted reference point. ```python fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") at_least_as_good = ((df_apartments.square_meters <= 84) & (df_apartments.price >= 15500)) dominated = at_least_as_good & ((df_apartments.square_meters < 84) | (df_apartments.price > 15500)) print(len(df_apartments[~dominated])) ax.scatter(df_apartments[~dominated].square_meters, df_apartments[~dominated].price, zorder=9) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.scatter([84], [15500], zorder=12, color="k", s=75) ``` -------------------------------- ### Annotate Apartment Scatter Plot Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Adds annotations with arrows to a scatter plot of apartment prices versus square meters. This highlights specific data points or trends in the dataset. ```python fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) ax.annotate('', xy=(35, 27000), xycoords='data', xytext=(50, 21500), arrowprops=dict(facecolor='black', shrink=0.05), zorder=50, fontsize=16 ) ax.annotate('', xy=(45, 27000), xycoords='data', xytext=(50, 23000), arrowprops=dict(facecolor='black', shrink=0.05), zorder=50, fontsize=16 ) ax.annotate('', xy=(32, 21000), xycoords='data', xytext=(50, 20000), arrowprops=dict(facecolor='black', shrink=0.05), zorder=50, fontsize=16 ) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments2.pdf") ``` -------------------------------- ### paretoset(costs, sense=None, distinct=True, use_numba=True) Source: https://context7.com/tommyod/paretoset/llms.txt Returns a boolean mask identifying observations in the Pareto (non-dominated) set. Each column's objective direction is controlled via `sense`: "min" (minimize), "max" (maximize), or "diff" (group-by). Duplicate rows are deduplicated by default (`distinct=True`). ```APIDOC ## paretoset(costs, sense=None, distinct=True, use_numba=True) ### Description Returns a boolean mask identifying observations in the Pareto (non-dominated) set. Each column's objective direction is controlled via `sense`: "min" (minimize), "max" (maximize), or "diff" (group-by — observations are only compared within groups sharing the same value). Duplicate rows are deduplicated by default (`distinct=True`). ### Parameters #### Path Parameters - **costs** (pandas DataFrame or NumPy array) - Required - The input data for which to compute the Pareto set. - **sense** (list of strings, optional) - Optional - Specifies the optimization direction for each column ('min', 'max', or 'diff'). If None, defaults to 'min' for all columns. - **distinct** (boolean, optional) - Optional - If True (default), duplicate rows are deduplicated before computation. If False, duplicates are considered distinct. - **use_numba** (boolean, optional) - Optional - If True (default), attempts to use Numba for accelerated computation if available. ### Request Example ```python from paretoset import paretoset import pandas as pd import numpy as np # Example 1: Hotel skyline query (minimize price AND distance to beach) hotels = pd.DataFrame({ "price": [50, 53, 62, 87, 83, 39, 60, 44], "distance_to_beach": [13, 21, 19, 13, 5, 22, 22, 25], }) mask = paretoset(hotels, sense=["min", "min"]) print(hotels[mask]) # Example 3: NumPy array — 2D minimization costs = np.array([[2, 0], [1, 1], [0, 2], [3, 3]]) print(paretoset(costs)) # Example 4: Distinct parameter — handling duplicate rows print(paretoset([0, 0], distinct=True)) print(paretoset([0, 0], distinct=False)) ``` ### Response #### Success Response (boolean mask) - Returns a boolean NumPy array where True indicates the observation is part of the Pareto set. ### Response Example ``` # For Example 1: # price distance_to_beach # 0 50 13 # 4 83 5 # 5 39 22 # For Example 3 (default sense): # array([ True, True, True, False]) # For Example 4 (distinct=True): # array([ True, False]) ``` ``` -------------------------------- ### Compute Convex Hull of Apartment Data Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Calculates the vertices of the convex hull for the apartment data using scipy.spatial.ConvexHull. This identifies the extreme points of the dataset. ```python from scipy.spatial import ConvexHull cvxhull = df_apartments.iloc[ConvexHull(df_apartments.values).vertices,:] list(cvxhull.square_meters) ``` -------------------------------- ### 2D Pareto front diversity measure Source: https://context7.com/tommyod/paretoset/llms.txt Computes crowding distances for a 2D Pareto front to measure diversity. Boundary points are assigned infinite distance. ```python from paretoset import crowding_distance import numpy as np front = np.array([ [0.0, 1.0], [0.3, 0.7], [0.5, 0.5], [0.7, 0.3], [1.0, 0.0], ]) distances = crowding_distance(front) print(distances) ``` -------------------------------- ### Crowding distance edge case: two points Source: https://context7.com/tommyod/paretoset/llms.txt Demonstrates the crowding distance calculation for an edge case with only two points, where both receive infinite distance. ```python from paretoset import crowding_distance import numpy as np # Only 2 points — both get infinite distance two_pts = np.array([[0.0, 1.0], [1.0, 0.0]]) print(crowding_distance(two_pts)) ``` -------------------------------- ### Fill Missing Computer Weight Data Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Fills missing values in the 'weight' column of the df_computers DataFrame with 0.1. This is a common data cleaning step before applying optimization algorithms. ```python df_computers["weight"] = df_computers["weight"].fillna(0.1) ``` -------------------------------- ### Plotting a Rectangle for Pareto Set Visualization Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Adds a rectangular patch to an axes object, often used to highlight a region of interest in plots. Requires matplotlib.pyplot and a predefined COLORS list. ```python left, bottom, width, height = (0, 15500, 84, 20000) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[0], alpha=0.25, zorder=7) ax.add_patch(rect) ``` -------------------------------- ### Disable Numba for paretoset Source: https://context7.com/tommyod/paretoset/llms.txt Shows how to disable Numba acceleration for a specific paretoset call, useful for testing or profiling. ```python # Disable numba for a specific call (e.g., during testing or profiling) from paretoset import paretoset import numpy as np costs = np.random.rand(10000, 4) mask = paretoset(costs, sense=["min", "min", "max", "min"], use_numba=False) ``` -------------------------------- ### Display Non-Pareto Optimal Computers Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Filters the df_computers DataFrame to show the rows that are NOT part of the Pareto optimal set, based on the previously computed mask. ```python df_computers[~mask] ``` -------------------------------- ### paretorank(population, sense) Source: https://context7.com/tommyod/paretoset/llms.txt Assigns a rank to each solution in a population based on its Pareto dominance. Solutions on the first Pareto front receive rank 0, the second front rank 1, and so on. ```APIDOC ## paretorank(population, sense) ### Description Assigns a rank to each solution in a population based on its Pareto dominance. Solutions on the first Pareto front receive rank 0, the second front rank 1, and so on. ### Parameters * **population** (numpy.ndarray) - Input array of shape (solutions, objectives). * **sense** (list of str) - A list of strings, where each string is either 'min' or 'max', indicating the optimization sense for each objective. ### Request Example ```python import numpy as np from paretoset import paretorank rng = np.random.default_rng(0) population = rng.random((100, 3)) # 100 solutions, 3 objectives ranks = paretorank(population, sense=["min", "min", "max"]) print(ranks) # Example output: array([0, 0, 1, 0, 2, ...]) ``` ### Response * **ranks** (numpy.ndarray) - An array of integers representing the Pareto rank of each solution. ``` -------------------------------- ### 1D crowding distance calculation Source: https://context7.com/tommyod/paretoset/llms.txt Calculates the crowding distance for a 1D array of costs. Boundary points receive infinite distance, while interior points receive normalized spans. ```python from paretoset import crowding_distance import numpy as np costs = np.array([1, 3, 5, 9, 11]).reshape(-1, 1) print(crowding_distance(costs)) ``` -------------------------------- ### crowding_distance(costs) Source: https://context7.com/tommyod/paretoset/llms.txt Computes the crowding distance for each observation in a Pareto front, as used in NSGA-II. Boundary points receive distance inf; interior points receive a normalized average span across objectives. Requires a plain NumPy ndarray of shape (observations, objectives) — NaN values, duplicate rows, and constant columns must be handled before calling. ```APIDOC ## crowding_distance(costs) ### Description Computes the crowding distance for each observation in a Pareto front, as used in NSGA-II. Boundary points receive distance `inf`; interior points receive a normalized average span across objectives. Requires a plain NumPy ndarray of shape `(observations, objectives)` — NaN values, duplicate rows, and constant columns must be handled before calling. ### Parameters * **costs** (numpy.ndarray) - Input array of shape (observations, objectives). ### Request Example ```python from paretoset import crowding_distance import numpy as np # --- Example 1: 1D crowding distance --- costs = np.array([1, 3, 5, 9, 11]).reshape(-1, 1) print(crowding_distance(costs)) # array([inf, 0.4, 0.6, 0.6, inf]) # --- Example 2: 2D Pareto front diversity measure --- front = np.array([ [0.0, 1.0], [0.3, 0.7], [0.5, 0.5], [0.7, 0.3], [1.0, 0.0], ]) distances = crowding_distance(front) print(distances) # array([ inf, 0.6 , 0.6 , 0.6 , inf]) # --- Example 4: Edge cases --- # Only 2 points — both get infinite distance two_pts = np.array([[0.0, 1.0], [1.0, 0.0]]) print(crowding_distance(two_pts)) # array([inf, inf]) ``` ### Response * **distances** (numpy.ndarray) - Array of crowding distances for each observation. ``` -------------------------------- ### Plot Convex Hull Vertices on Scatter Plot Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Adds the vertices of the convex hull to an existing scatter plot of apartment prices versus square meters. This visually highlights the extreme data points identified by the convex hull computation. ```python fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) ax.scatter([84, 42, 90, 89], [15500, 12300, 21000, 19000], zorder=9) xlim = ax.get_xlim() ylim = ax.get_ylim() ``` -------------------------------- ### Define default plot colors Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Retrieves the default color cycle from matplotlib's plot configuration to be used for visualizations. ```python COLORS = list(plt.rcParams['axes.prop_cycle'].by_key()['color']) ``` -------------------------------- ### Identify Non-Dominated Observations with paretoset Source: https://context7.com/tommyod/paretoset/llms.txt Use `paretoset` to find rows that are not dominated by any other row based on specified optimization objectives. Supports pandas DataFrames and NumPy arrays, with options for objective direction ('min', 'max', 'diff') and duplicate handling. ```python from paretoset import paretoset import pandas as pd import numpy as np # --- Example 1: Hotel skyline query (minimize price AND distance to beach) --- hotels = pd.DataFrame({ "price": [50, 53, 62, 87, 83, 39, 60, 44], "distance_to_beach": [13, 21, 19, 13, 5, 22, 22, 25], }) mask = paretoset(hotels, sense=["min", "min"]) print(hotels[mask]) # Output: rows where no other hotel is cheaper AND closer to the beach # price distance_to_beach # 0 50 13 # 4 83 5 # 5 39 22 ``` ```python # --- Example 2: Mixed min/max with group-by (top salespeople per department) --- salespeople = pd.DataFrame({ "salary": [94, 107, 67, 87, 153, 62, 43, 115, 78, 77, 119, 127], "sales": [123, 72, 80, 40, 64, 104, 106, 135, 61, 81, 162, 60], "department": ["c", "c", "c", "b", "b", "a", "a", "c", "b", "a", "b", "a"], }) # Find top performers: low salary ("min"), high sales ("max"), per department ("diff") mask = paretoset(salespeople, sense=["min", "max", "diff"]) print(salespeople[mask]) ``` ```python # --- Example 3: NumPy array — 2D minimization --- costs = np.array([[2, 0], [1, 1], [0, 2], [3, 3]]) print(paretoset(costs)) # array([ True, True, True, False]) print(paretoset(costs, sense=["min", "max"])) # array([False, False, True, True]) ``` ```python # --- Example 4: Distinct parameter — handling duplicate rows --- print(paretoset([0, 0], distinct=True)) # array([ True, False]) print(paretoset([0, 0], distinct=False)) # array([ True, True]) ``` ```python # --- Example 5: Multi-objective optimization solutions --- from collections import namedtuple Solution = namedtuple("Solution", ["solution", "obj_value"]) rng = np.random.default_rng(42) solutions = [Solution(solution=i, obj_value=rng.standard_normal(2)) for i in range(500)] obj_array = np.vstack([s.obj_value for s in solutions]) mask = paretoset(obj_array, sense=["min", "max"]) efficient = [s for s, m in zip(solutions, mask) if m] print(f"Non-dominated solutions: {len(efficient)} out of {len(solutions)}") ``` -------------------------------- ### Convert DataFrame to LaTeX Source: https://github.com/tommyod/paretoset/blob/master/scripts/video/paretoset_video.ipynb Converts a pandas DataFrame to a LaTeX table format. This is used to display the results of filtering and Pareto set analysis. ```python print(df_computers.to_latex(index=False,)) ``` -------------------------------- ### Assign Pareto Ranks with paretorank Source: https://context7.com/tommyod/paretoset/llms.txt Use `paretorank` to assign a layered rank to each observation, where rank 1 is the Pareto set. This function is useful for NSGA-II-style selection and tiered filtering. It supports pandas DataFrames and NumPy arrays. ```python from paretoset import paretorank import pandas as pd import numpy as np # --- Example 1: Basic Pareto ranking --- costs = np.array([[2, 0], [1, 1], [0, 2], [3, 3]]) print(paretorank(costs)) # array([1, 1, 1, 2]) — first three are on the front, last is rank 2 print(paretorank(costs, sense=["min", "max"])) # array([3, 2, 1, 1]) ``` ```python # --- Example 2: Ranking candidates by multiple criteria --- candidates = pd.DataFrame({ "error_rate": [0.05, 0.10, 0.03, 0.08, 0.12], "latency_ms": [120, 80, 200, 90, 60], }) ranks = paretorank(candidates, sense=["min", "min"]) candidates["pareto_rank"] = ranks print(candidates.sort_values("pareto_rank")) # error_rate latency_ms pareto_rank # 1 0.10 80 1 # 3 0.08 90 1 # 4 0.12 60 1 # 0 0.05 120 2 # 2 0.03 200 3 ``` ```python # --- Example 3: Distinct parameter with duplicate rows --- print(paretorank([0, 0], distinct=True)) # array([1, 2]) print(paretorank([0, 0], distinct=False)) # array([1, 1]) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.