content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
import datetime\nimport numpy as np\n\nimport pytest\n\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\n\nclass TestDatetimePlotting:\n @mpl.style.context("default")\n def test_annotate(self):\n mpl.rcParams["date.converter"] = 'concise'\n fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, layout="constrained")\n\n start_date = datetime.datetime(2023, 10, 1)\n dates = [start_date + datetime.timedelta(days=i) for i in range(31)]\n data = list(range(1, 32))\n test_text = "Test Text"\n\n ax1.plot(dates, data)\n ax1.annotate(text=test_text, xy=(dates[15], data[15]))\n ax2.plot(data, dates)\n ax2.annotate(text=test_text, xy=(data[5], dates[26]))\n ax3.plot(dates, dates)\n ax3.annotate(text=test_text, xy=(dates[15], dates[3]))\n ax4.plot(dates, dates)\n ax4.annotate(text=test_text, xy=(dates[5], dates[30]),\n xytext=(dates[1], dates[7]), arrowprops=dict(facecolor='red'))\n\n @pytest.mark.xfail(reason="Test for arrow not written yet")\n @mpl.style.context("default")\n def test_arrow(self):\n fig, ax = plt.subplots()\n ax.arrow(...)\n\n @mpl.style.context("default")\n def test_axhline(self):\n mpl.rcParams["date.converter"] = 'concise'\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, layout='constrained')\n ax1.set_ylim(bottom=datetime.datetime(2020, 4, 1),\n top=datetime.datetime(2020, 8, 1))\n ax2.set_ylim(bottom=np.datetime64('2005-01-01'),\n top=np.datetime64('2005-04-01'))\n ax3.set_ylim(bottom=datetime.datetime(2023, 9, 1),\n top=datetime.datetime(2023, 11, 1))\n ax1.axhline(y=datetime.datetime(2020, 6, 3), xmin=0.5, xmax=0.7)\n ax2.axhline(np.datetime64('2005-02-25T03:30'), xmin=0.1, xmax=0.9)\n ax3.axhline(y=datetime.datetime(2023, 10, 24), xmin=0.4, xmax=0.7)\n\n @mpl.style.context("default")\n def test_axhspan(self):\n mpl.rcParams["date.converter"] = 'concise'\n\n start_date = datetime.datetime(2023, 1, 1)\n dates = [start_date + datetime.timedelta(days=i) for i in range(31)]\n numbers = list(range(1, 32))\n\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1,\n constrained_layout=True,\n figsize=(10, 12))\n\n ax1.plot(dates, numbers, marker='o', color='blue')\n for i in range(0, 31, 2):\n ax1.axhspan(ymin=i+1, ymax=i+2, facecolor='green', alpha=0.5)\n ax1.set_title('Datetime vs. Number')\n ax1.set_xlabel('Date')\n ax1.set_ylabel('Number')\n\n ax2.plot(numbers, dates, marker='o', color='blue')\n for i in range(0, 31, 2):\n ymin = start_date + datetime.timedelta(days=i)\n ymax = ymin + datetime.timedelta(days=1)\n ax2.axhspan(ymin=ymin, ymax=ymax, facecolor='green', alpha=0.5)\n ax2.set_title('Number vs. Datetime')\n ax2.set_xlabel('Number')\n ax2.set_ylabel('Date')\n\n ax3.plot(dates, dates, marker='o', color='blue')\n for i in range(0, 31, 2):\n ymin = start_date + datetime.timedelta(days=i)\n ymax = ymin + datetime.timedelta(days=1)\n ax3.axhspan(ymin=ymin, ymax=ymax, facecolor='green', alpha=0.5)\n ax3.set_title('Datetime vs. Datetime')\n ax3.set_xlabel('Date')\n ax3.set_ylabel('Date')\n\n @pytest.mark.xfail(reason="Test for axline not written yet")\n @mpl.style.context("default")\n def test_axline(self):\n fig, ax = plt.subplots()\n ax.axline(...)\n\n @mpl.style.context("default")\n def test_axvline(self):\n mpl.rcParams["date.converter"] = 'concise'\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, layout='constrained')\n ax1.set_xlim(left=datetime.datetime(2020, 4, 1),\n right=datetime.datetime(2020, 8, 1))\n ax2.set_xlim(left=np.datetime64('2005-01-01'),\n right=np.datetime64('2005-04-01'))\n ax3.set_xlim(left=datetime.datetime(2023, 9, 1),\n right=datetime.datetime(2023, 11, 1))\n ax1.axvline(x=datetime.datetime(2020, 6, 3), ymin=0.5, ymax=0.7)\n ax2.axvline(np.datetime64('2005-02-25T03:30'), ymin=0.1, ymax=0.9)\n ax3.axvline(x=datetime.datetime(2023, 10, 24), ymin=0.4, ymax=0.7)\n\n @mpl.style.context("default")\n def test_axvspan(self):\n mpl.rcParams["date.converter"] = 'concise'\n\n start_date = datetime.datetime(2023, 1, 1)\n dates = [start_date + datetime.timedelta(days=i) for i in range(31)]\n numbers = list(range(1, 32))\n\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1,\n constrained_layout=True,\n figsize=(10, 12))\n\n ax1.plot(dates, numbers, marker='o', color='blue')\n for i in range(0, 31, 2):\n xmin = start_date + datetime.timedelta(days=i)\n xmax = xmin + datetime.timedelta(days=1)\n ax1.axvspan(xmin=xmin, xmax=xmax, facecolor='red', alpha=0.5)\n ax1.set_title('Datetime vs. Number')\n ax1.set_xlabel('Date')\n ax1.set_ylabel('Number')\n\n ax2.plot(numbers, dates, marker='o', color='blue')\n for i in range(0, 31, 2):\n ax2.axvspan(xmin=i+1, xmax=i+2, facecolor='red', alpha=0.5)\n ax2.set_title('Number vs. Datetime')\n ax2.set_xlabel('Number')\n ax2.set_ylabel('Date')\n\n ax3.plot(dates, dates, marker='o', color='blue')\n for i in range(0, 31, 2):\n xmin = start_date + datetime.timedelta(days=i)\n xmax = xmin + datetime.timedelta(days=1)\n ax3.axvspan(xmin=xmin, xmax=xmax, facecolor='red', alpha=0.5)\n ax3.set_title('Datetime vs. Datetime')\n ax3.set_xlabel('Date')\n ax3.set_ylabel('Date')\n\n @mpl.style.context("default")\n def test_bar(self):\n mpl.rcParams["date.converter"] = "concise"\n\n fig, (ax1, ax2) = plt.subplots(2, 1, layout="constrained")\n\n x_dates = np.array(\n [\n datetime.datetime(2020, 6, 30),\n datetime.datetime(2020, 7, 22),\n datetime.datetime(2020, 8, 3),\n datetime.datetime(2020, 9, 14),\n ],\n dtype=np.datetime64,\n )\n x_ranges = [8800, 2600, 8500, 7400]\n\n x = np.datetime64(datetime.datetime(2020, 6, 1))\n ax1.bar(x_dates, x_ranges, width=np.timedelta64(4, "D"))\n ax2.bar(np.arange(4), x_dates - x, bottom=x)\n\n @mpl.style.context("default")\n def test_bar_label(self):\n # Generate some example data with dateTime inputs\n date_list = [datetime.datetime(2023, 1, 1) +\n datetime.timedelta(days=i) for i in range(5)]\n values = [10, 20, 15, 25, 30]\n\n # Creating the plot\n fig, ax = plt.subplots(1, 1, figsize=(10, 8), layout='constrained')\n bars = ax.bar(date_list, values)\n\n # Add labels to the bars using bar_label\n ax.bar_label(bars, labels=[f'{val}%' for val in values],\n label_type='edge', color='black')\n\n @mpl.style.context("default")\n def test_barbs(self):\n plt.rcParams["date.converter"] = 'concise'\n\n start_date = datetime.datetime(2022, 2, 8, 22)\n dates = [start_date + datetime.timedelta(hours=i) for i in range(12)]\n\n numbers = np.sin(np.linspace(0, 2 * np.pi, 12))\n\n u = np.ones(12) * 10\n v = np.arange(0, 120, 10)\n\n fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 6))\n\n axes[0].barbs(dates, numbers, u, v, length=7)\n axes[0].set_title('Datetime vs. Numeric Data')\n axes[0].set_xlabel('Datetime')\n axes[0].set_ylabel('Numeric Data')\n\n axes[1].barbs(numbers, dates, u, v, length=7)\n axes[1].set_title('Numeric vs. Datetime Data')\n axes[1].set_xlabel('Numeric Data')\n axes[1].set_ylabel('Datetime')\n\n @mpl.style.context("default")\n def test_barh(self):\n mpl.rcParams["date.converter"] = 'concise'\n fig, (ax1, ax2) = plt.subplots(2, 1, layout='constrained')\n birth_date = np.array([datetime.datetime(2020, 4, 10),\n datetime.datetime(2020, 5, 30),\n datetime.datetime(2020, 10, 12),\n datetime.datetime(2020, 11, 15)])\n year_start = datetime.datetime(2020, 1, 1)\n year_end = datetime.datetime(2020, 12, 31)\n age = [21, 53, 20, 24]\n ax1.set_xlabel('Age')\n ax1.set_ylabel('Birth Date')\n ax1.barh(birth_date, width=age, height=datetime.timedelta(days=10))\n ax2.set_xlim(left=year_start, right=year_end)\n ax2.set_xlabel('Birth Date')\n ax2.set_ylabel('Order of Birth Dates')\n ax2.barh(np.arange(4), birth_date-year_start, left=year_start)\n\n @pytest.mark.xfail(reason="Test for boxplot not written yet")\n @mpl.style.context("default")\n def test_boxplot(self):\n fig, ax = plt.subplots()\n ax.boxplot(...)\n\n @mpl.style.context("default")\n def test_broken_barh(self):\n # Horizontal bar plot with gaps\n mpl.rcParams["date.converter"] = 'concise'\n fig, ax = plt.subplots()\n\n ax.broken_barh([(datetime.datetime(2023, 1, 4), datetime.timedelta(days=2)),\n (datetime.datetime(2023, 1, 8), datetime.timedelta(days=3))],\n (10, 9), facecolors='tab:blue')\n ax.broken_barh([(datetime.datetime(2023, 1, 2), datetime.timedelta(days=1)),\n (datetime.datetime(2023, 1, 4), datetime.timedelta(days=4))],\n (20, 9), facecolors=('tab:red'))\n\n @mpl.style.context("default")\n def test_bxp(self):\n mpl.rcParams["date.converter"] = 'concise'\n fig, ax = plt.subplots()\n data = [{\n "med": datetime.datetime(2020, 1, 15),\n "q1": datetime.datetime(2020, 1, 10),\n "q3": datetime.datetime(2020, 1, 20),\n "whislo": datetime.datetime(2020, 1, 5),\n "whishi": datetime.datetime(2020, 1, 25),\n "fliers": [\n datetime.datetime(2020, 1, 3),\n datetime.datetime(2020, 1, 27)\n ]\n }]\n ax.bxp(data, orientation='horizontal')\n ax.xaxis.set_major_formatter(mpl.dates.DateFormatter("%Y-%m-%d"))\n ax.set_title('Box plot with datetime data')\n\n @pytest.mark.xfail(reason="Test for clabel not written yet")\n @mpl.style.context("default")\n def test_clabel(self):\n fig, ax = plt.subplots()\n ax.clabel(...)\n\n @mpl.style.context("default")\n def test_contour(self):\n mpl.rcParams["date.converter"] = "concise"\n range_threshold = 10\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, layout="constrained")\n\n x_dates = np.array(\n [datetime.datetime(2023, 10, delta) for delta in range(1, range_threshold)]\n )\n y_dates = np.array(\n [datetime.datetime(2023, 10, delta) for delta in range(1, range_threshold)]\n )\n x_ranges = np.array(range(1, range_threshold))\n y_ranges = np.array(range(1, range_threshold))\n\n X_dates, Y_dates = np.meshgrid(x_dates, y_dates)\n X_ranges, Y_ranges = np.meshgrid(x_ranges, y_ranges)\n\n Z_ranges = np.cos(X_ranges / 4) + np.sin(Y_ranges / 4)\n\n ax1.contour(X_dates, Y_dates, Z_ranges)\n ax2.contour(X_dates, Y_ranges, Z_ranges)\n ax3.contour(X_ranges, Y_dates, Z_ranges)\n\n @mpl.style.context("default")\n def test_contourf(self):\n mpl.rcParams["date.converter"] = "concise"\n range_threshold = 10\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, layout="constrained")\n\n x_dates = np.array(\n [datetime.datetime(2023, 10, delta) for delta in range(1, range_threshold)]\n )\n y_dates = np.array(\n [datetime.datetime(2023, 10, delta) for delta in range(1, range_threshold)]\n )\n x_ranges = np.array(range(1, range_threshold))\n y_ranges = np.array(range(1, range_threshold))\n\n X_dates, Y_dates = np.meshgrid(x_dates, y_dates)\n X_ranges, Y_ranges = np.meshgrid(x_ranges, y_ranges)\n\n Z_ranges = np.cos(X_ranges / 4) + np.sin(Y_ranges / 4)\n\n ax1.contourf(X_dates, Y_dates, Z_ranges)\n ax2.contourf(X_dates, Y_ranges, Z_ranges)\n ax3.contourf(X_ranges, Y_dates, Z_ranges)\n\n @mpl.style.context("default")\n def test_errorbar(self):\n mpl.rcParams["date.converter"] = "concise"\n fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, layout="constrained")\n limit = 7\n start_date = datetime.datetime(2023, 1, 1)\n\n x_dates = np.array([datetime.datetime(2023, 10, d) for d in range(1, limit)])\n y_dates = np.array([datetime.datetime(2023, 10, d) for d in range(1, limit)])\n x_date_error = datetime.timedelta(days=1)\n y_date_error = datetime.timedelta(days=1)\n\n x_values = list(range(1, limit))\n y_values = list(range(1, limit))\n x_value_error = 0.5\n y_value_error = 0.5\n\n ax1.errorbar(x_dates, y_values,\n yerr=y_value_error,\n capsize=10,\n barsabove=True,\n label='Data')\n ax2.errorbar(x_values, y_dates,\n xerr=x_value_error, yerr=y_date_error,\n errorevery=(1, 2),\n fmt='-o', label='Data')\n ax3.errorbar(x_dates, y_dates,\n xerr=x_date_error, yerr=y_date_error,\n lolims=True, xlolims=True,\n label='Data')\n ax4.errorbar(x_dates, y_values,\n xerr=x_date_error, yerr=y_value_error,\n uplims=True, xuplims=True,\n label='Data')\n\n @mpl.style.context("default")\n def test_eventplot(self):\n mpl.rcParams["date.converter"] = "concise"\n\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, layout="constrained")\n\n x_dates1 = np.array([datetime.datetime(2020, 6, 30),\n datetime.datetime(2020, 7, 22),\n datetime.datetime(2020, 8, 3),\n datetime.datetime(2020, 9, 14),],\n dtype=np.datetime64,\n )\n\n ax1.eventplot(x_dates1)\n\n np.random.seed(19680801)\n\n start_date = datetime.datetime(2020, 7, 1)\n end_date = datetime.datetime(2020, 10, 15)\n date_range = end_date - start_date\n\n dates1 = start_date + np.random.rand(30) * date_range\n dates2 = start_date + np.random.rand(10) * date_range\n dates3 = start_date + np.random.rand(50) * date_range\n\n colors1 = ['C1', 'C2', 'C3']\n lineoffsets1 = np.array([1, 6, 8])\n linelengths1 = [5, 2, 3]\n\n ax2.eventplot([dates1, dates2, dates3],\n colors=colors1,\n lineoffsets=lineoffsets1,\n linelengths=linelengths1)\n\n lineoffsets2 = np.array([\n datetime.datetime(2020, 7, 1),\n datetime.datetime(2020, 7, 15),\n datetime.datetime(2020, 8, 1)\n ], dtype=np.datetime64)\n\n ax3.eventplot([dates1, dates2, dates3],\n colors=colors1,\n lineoffsets=lineoffsets2,\n linelengths=linelengths1)\n\n @mpl.style.context("default")\n def test_fill(self):\n mpl.rcParams["date.converter"] = "concise"\n fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, layout="constrained")\n\n np.random.seed(19680801)\n\n x_base_date = datetime.datetime(2023, 1, 1)\n x_dates = [x_base_date]\n for _ in range(1, 5):\n x_base_date += datetime.timedelta(days=np.random.randint(1, 5))\n x_dates.append(x_base_date)\n\n y_base_date = datetime.datetime(2023, 1, 1)\n y_dates = [y_base_date]\n for _ in range(1, 5):\n y_base_date += datetime.timedelta(days=np.random.randint(1, 5))\n y_dates.append(y_base_date)\n\n x_values = np.random.rand(5) * 5\n y_values = np.random.rand(5) * 5 - 2\n\n ax1.fill(x_dates, y_values)\n ax2.fill(x_values, y_dates)\n ax3.fill(x_values, y_values)\n ax4.fill(x_dates, y_dates)\n\n @mpl.style.context("default")\n def test_fill_between(self):\n mpl.rcParams["date.converter"] = "concise"\n np.random.seed(19680801)\n\n y_base_date = datetime.datetime(2023, 1, 1)\n y_dates1 = [y_base_date]\n for i in range(1, 10):\n y_base_date += datetime.timedelta(days=np.random.randint(1, 5))\n y_dates1.append(y_base_date)\n\n y_dates2 = [y_base_date]\n for i in range(1, 10):\n y_base_date += datetime.timedelta(days=np.random.randint(1, 5))\n y_dates2.append(y_base_date)\n x_values = np.random.rand(10) * 10\n x_values.sort()\n\n y_values1 = np.random.rand(10) * 10\n y_values2 = y_values1 + np.random.rand(10) * 10\n y_values1.sort()\n y_values2.sort()\n\n x_base_date = datetime.datetime(2023, 1, 1)\n x_dates = [x_base_date]\n for i in range(1, 10):\n x_base_date += datetime.timedelta(days=np.random.randint(1, 10))\n x_dates.append(x_base_date)\n\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, layout="constrained")\n\n ax1.fill_between(x_values, y_dates1, y_dates2)\n ax2.fill_between(x_dates, y_values1, y_values2)\n ax3.fill_between(x_dates, y_dates1, y_dates2)\n\n @mpl.style.context("default")\n def test_fill_betweenx(self):\n mpl.rcParams["date.converter"] = "concise"\n np.random.seed(19680801)\n\n x_base_date = datetime.datetime(2023, 1, 1)\n x_dates1 = [x_base_date]\n for i in range(1, 10):\n x_base_date += datetime.timedelta(days=np.random.randint(1, 5))\n x_dates1.append(x_base_date)\n\n x_dates2 = [x_base_date]\n for i in range(1, 10):\n x_base_date += datetime.timedelta(days=np.random.randint(1, 5))\n x_dates2.append(x_base_date)\n y_values = np.random.rand(10) * 10\n y_values.sort()\n\n x_values1 = np.random.rand(10) * 10\n x_values2 = x_values1 + np.random.rand(10) * 10\n x_values1.sort()\n x_values2.sort()\n\n y_base_date = datetime.datetime(2023, 1, 1)\n y_dates = [y_base_date]\n for i in range(1, 10):\n y_base_date += datetime.timedelta(days=np.random.randint(1, 10))\n y_dates.append(y_base_date)\n\n fig, (ax1, ax2, ax3) = plt.subplots(1, 3, layout="constrained")\n\n ax1.fill_betweenx(y_values, x_dates1, x_dates2)\n ax2.fill_betweenx(y_dates, x_values1, x_values2)\n ax3.fill_betweenx(y_dates, x_dates1, x_dates2)\n\n @pytest.mark.xfail(reason="Test for hexbin not written yet")\n @mpl.style.context("default")\n def test_hexbin(self):\n fig, ax = plt.subplots()\n ax.hexbin(...)\n\n @mpl.style.context("default")\n def test_hist(self):\n mpl.rcParams["date.converter"] = 'concise'\n\n start_date = datetime.datetime(2023, 10, 1)\n time_delta = datetime.timedelta(days=1)\n\n values1 = np.random.randint(1, 10, 30)\n values2 = np.random.randint(1, 10, 30)\n values3 = np.random.randint(1, 10, 30)\n\n bin_edges = [start_date + i * time_delta for i in range(31)]\n\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, constrained_layout=True)\n ax1.hist(\n [start_date + i * time_delta for i in range(30)],\n bins=10,\n weights=values1\n )\n ax2.hist(\n [start_date + i * time_delta for i in range(30)],\n bins=10,\n weights=values2\n )\n ax3.hist(\n [start_date + i * time_delta for i in range(30)],\n bins=10,\n weights=values3\n )\n\n fig, (ax4, ax5, ax6) = plt.subplots(3, 1, constrained_layout=True)\n ax4.hist(\n [start_date + i * time_delta for i in range(30)],\n bins=bin_edges,\n weights=values1\n )\n ax5.hist(\n [start_date + i * time_delta for i in range(30)],\n bins=bin_edges,\n weights=values2\n )\n ax6.hist(\n [start_date + i * time_delta for i in range(30)],\n bins=bin_edges,\n weights=values3\n )\n\n @pytest.mark.xfail(reason="Test for hist2d not written yet")\n @mpl.style.context("default")\n def test_hist2d(self):\n fig, ax = plt.subplots()\n ax.hist2d(...)\n\n @mpl.style.context("default")\n def test_hlines(self):\n mpl.rcParams["date.converter"] = 'concise'\n fig, axs = plt.subplots(2, 4, layout='constrained')\n dateStrs = ['2023-03-08',\n '2023-04-09',\n '2023-05-13',\n '2023-07-28',\n '2023-12-24']\n dates = [datetime.datetime(2023, m*2, 10) for m in range(1, 6)]\n date_start = [datetime.datetime(2023, 6, d) for d in range(5, 30, 5)]\n date_end = [datetime.datetime(2023, 7, d) for d in range(5, 30, 5)]\n npDates = [np.datetime64(s) for s in dateStrs]\n axs[0, 0].hlines(y=dates,\n xmin=[0.1, 0.2, 0.3, 0.4, 0.5],\n xmax=[0.5, 0.6, 0.7, 0.8, 0.9])\n axs[0, 1].hlines(dates,\n xmin=datetime.datetime(2020, 5, 10),\n xmax=datetime.datetime(2020, 5, 31))\n axs[0, 2].hlines(dates,\n xmin=date_start,\n xmax=date_end)\n axs[0, 3].hlines(dates,\n xmin=0.45,\n xmax=0.65)\n axs[1, 0].hlines(y=npDates,\n xmin=[0.5, 0.6, 0.7, 0.8, 0.9],\n xmax=[0.1, 0.2, 0.3, 0.4, 0.5])\n axs[1, 2].hlines(y=npDates,\n xmin=date_start,\n xmax=date_end)\n axs[1, 1].hlines(npDates,\n xmin=datetime.datetime(2020, 5, 10),\n xmax=datetime.datetime(2020, 5, 31))\n axs[1, 3].hlines(npDates,\n xmin=0.45,\n xmax=0.65)\n\n @mpl.style.context("default")\n def test_imshow(self):\n fig, ax = plt.subplots()\n a = np.diag(range(5))\n dt_start = datetime.datetime(2010, 11, 1)\n dt_end = datetime.datetime(2010, 11, 11)\n extent = (dt_start, dt_end, dt_start, dt_end)\n ax.imshow(a, extent=extent)\n ax.tick_params(axis="x", labelrotation=90)\n\n @pytest.mark.xfail(reason="Test for loglog not written yet")\n @mpl.style.context("default")\n def test_loglog(self):\n fig, ax = plt.subplots()\n ax.loglog(...)\n\n @mpl.style.context("default")\n def test_matshow(self):\n a = np.diag(range(5))\n dt_start = datetime.datetime(1980, 4, 15)\n dt_end = datetime.datetime(2020, 11, 11)\n extent = (dt_start, dt_end, dt_start, dt_end)\n fig, ax = plt.subplots()\n ax.matshow(a, extent=extent)\n for label in ax.get_xticklabels():\n label.set_rotation(90)\n\n @pytest.mark.xfail(reason="Test for pcolor not written yet")\n @mpl.style.context("default")\n def test_pcolor(self):\n fig, ax = plt.subplots()\n ax.pcolor(...)\n\n @pytest.mark.xfail(reason="Test for pcolorfast not written yet")\n @mpl.style.context("default")\n def test_pcolorfast(self):\n fig, ax = plt.subplots()\n ax.pcolorfast(...)\n\n @pytest.mark.xfail(reason="Test for pcolormesh not written yet")\n @mpl.style.context("default")\n def test_pcolormesh(self):\n fig, ax = plt.subplots()\n ax.pcolormesh(...)\n\n @mpl.style.context("default")\n def test_plot(self):\n mpl.rcParams["date.converter"] = 'concise'\n N = 6\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, layout='constrained')\n x = np.array([datetime.datetime(2023, 9, n) for n in range(1, N)])\n ax1.plot(x, range(1, N))\n ax2.plot(range(1, N), x)\n ax3.plot(x, x)\n\n @mpl.style.context("default")\n def test_plot_date(self):\n mpl.rcParams["date.converter"] = "concise"\n range_threshold = 10\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, layout="constrained")\n\n x_dates = np.array(\n [datetime.datetime(2023, 10, delta) for delta in range(1, range_threshold)]\n )\n y_dates = np.array(\n [datetime.datetime(2023, 10, delta) for delta in range(1, range_threshold)]\n )\n x_ranges = np.array(range(1, range_threshold))\n y_ranges = np.array(range(1, range_threshold))\n\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n ax1.plot_date(x_dates, y_dates)\n ax2.plot_date(x_dates, y_ranges)\n ax3.plot_date(x_ranges, y_dates)\n\n @pytest.mark.xfail(reason="Test for quiver not written yet")\n @mpl.style.context("default")\n def test_quiver(self):\n fig, ax = plt.subplots()\n ax.quiver(...)\n\n @mpl.style.context("default")\n def test_scatter(self):\n mpl.rcParams["date.converter"] = 'concise'\n base = datetime.datetime(2005, 2, 1)\n dates = [base + datetime.timedelta(hours=(2 * i)) for i in range(10)]\n N = len(dates)\n np.random.seed(19680801)\n y = np.cumsum(np.random.randn(N))\n fig, axs = plt.subplots(3, 1, layout='constrained', figsize=(6, 6))\n # datetime array on x axis\n axs[0].scatter(dates, y)\n for label in axs[0].get_xticklabels():\n label.set_rotation(40)\n label.set_horizontalalignment('right')\n # datetime on y axis\n axs[1].scatter(y, dates)\n # datetime on both x, y axes\n axs[2].scatter(dates, dates)\n for label in axs[2].get_xticklabels():\n label.set_rotation(40)\n label.set_horizontalalignment('right')\n\n @pytest.mark.xfail(reason="Test for semilogx not written yet")\n @mpl.style.context("default")\n def test_semilogx(self):\n fig, ax = plt.subplots()\n ax.semilogx(...)\n\n @pytest.mark.xfail(reason="Test for semilogy not written yet")\n @mpl.style.context("default")\n def test_semilogy(self):\n fig, ax = plt.subplots()\n ax.semilogy(...)\n\n @mpl.style.context("default")\n def test_stackplot(self):\n mpl.rcParams["date.converter"] = 'concise'\n N = 10\n stacked_nums = np.tile(np.arange(1, N), (4, 1))\n dates = np.array([datetime.datetime(2020 + i, 1, 1) for i in range(N - 1)])\n\n fig, ax = plt.subplots(layout='constrained')\n ax.stackplot(dates, stacked_nums)\n\n @mpl.style.context("default")\n def test_stairs(self):\n mpl.rcParams["date.converter"] = 'concise'\n\n start_date = datetime.datetime(2023, 12, 1)\n time_delta = datetime.timedelta(days=1)\n baseline_date = datetime.datetime(1980, 1, 1)\n\n bin_edges = [start_date + i * time_delta for i in range(31)]\n edge_int = np.arange(31)\n np.random.seed(123456)\n values1 = np.random.randint(1, 100, 30)\n values2 = [start_date + datetime.timedelta(days=int(i))\n for i in np.random.randint(1, 10000, 30)]\n values3 = [start_date + datetime.timedelta(days=int(i))\n for i in np.random.randint(-10000, 10000, 30)]\n\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, constrained_layout=True)\n ax1.stairs(values1, edges=bin_edges)\n ax2.stairs(values2, edges=edge_int, baseline=baseline_date)\n ax3.stairs(values3, edges=bin_edges, baseline=baseline_date)\n\n @mpl.style.context("default")\n def test_stem(self):\n mpl.rcParams["date.converter"] = "concise"\n\n fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, layout="constrained")\n\n limit_value = 10\n above = datetime.datetime(2023, 9, 18)\n below = datetime.datetime(2023, 11, 18)\n\n x_ranges = np.arange(1, limit_value)\n y_ranges = np.arange(1, limit_value)\n\n x_dates = np.array(\n [datetime.datetime(2023, 10, n) for n in range(1, limit_value)]\n )\n y_dates = np.array(\n [datetime.datetime(2023, 10, n) for n in range(1, limit_value)]\n )\n\n ax1.stem(x_dates, y_dates, bottom=above)\n ax2.stem(x_dates, y_ranges, bottom=5)\n ax3.stem(x_ranges, y_dates, bottom=below)\n\n ax4.stem(x_ranges, y_dates, orientation="horizontal", bottom=above)\n ax5.stem(x_dates, y_ranges, orientation="horizontal", bottom=5)\n ax6.stem(x_ranges, y_dates, orientation="horizontal", bottom=below)\n\n @mpl.style.context("default")\n def test_step(self):\n mpl.rcParams["date.converter"] = "concise"\n N = 6\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, layout='constrained')\n x = np.array([datetime.datetime(2023, 9, n) for n in range(1, N)])\n ax1.step(x, range(1, N))\n ax2.step(range(1, N), x)\n ax3.step(x, x)\n\n @pytest.mark.xfail(reason="Test for streamplot not written yet")\n @mpl.style.context("default")\n def test_streamplot(self):\n fig, ax = plt.subplots()\n ax.streamplot(...)\n\n @mpl.style.context("default")\n def test_text(self):\n mpl.rcParams["date.converter"] = 'concise'\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, layout="constrained")\n\n limit_value = 10\n font_properties = {'family': 'serif', 'size': 12, 'weight': 'bold'}\n test_date = datetime.datetime(2023, 10, 1)\n\n x_data = np.array(range(1, limit_value))\n y_data = np.array(range(1, limit_value))\n\n x_dates = np.array(\n [datetime.datetime(2023, 10, n) for n in range(1, limit_value)]\n )\n y_dates = np.array(\n [datetime.datetime(2023, 10, n) for n in range(1, limit_value)]\n )\n\n ax1.plot(x_dates, y_data)\n ax1.text(test_date, 5, "Inserted Text", **font_properties)\n\n ax2.plot(x_data, y_dates)\n ax2.text(7, test_date, "Inserted Text", **font_properties)\n\n ax3.plot(x_dates, y_dates)\n ax3.text(test_date, test_date, "Inserted Text", **font_properties)\n\n @pytest.mark.xfail(reason="Test for tricontour not written yet")\n @mpl.style.context("default")\n def test_tricontour(self):\n fig, ax = plt.subplots()\n ax.tricontour(...)\n\n @pytest.mark.xfail(reason="Test for tricontourf not written yet")\n @mpl.style.context("default")\n def test_tricontourf(self):\n fig, ax = plt.subplots()\n ax.tricontourf(...)\n\n @pytest.mark.xfail(reason="Test for tripcolor not written yet")\n @mpl.style.context("default")\n def test_tripcolor(self):\n fig, ax = plt.subplots()\n ax.tripcolor(...)\n\n @pytest.mark.xfail(reason="Test for triplot not written yet")\n @mpl.style.context("default")\n def test_triplot(self):\n fig, ax = plt.subplots()\n ax.triplot(...)\n\n @pytest.mark.xfail(reason="Test for violin not written yet")\n @mpl.style.context("default")\n def test_violin(self):\n fig, ax = plt.subplots()\n ax.violin(...)\n\n @pytest.mark.xfail(reason="Test for violinplot not written yet")\n @mpl.style.context("default")\n def test_violinplot(self):\n fig, ax = plt.subplots()\n ax.violinplot(...)\n\n @mpl.style.context("default")\n def test_vlines(self):\n mpl.rcParams["date.converter"] = 'concise'\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, layout='constrained')\n ax1.set_xlim(left=datetime.datetime(2023, 1, 1),\n right=datetime.datetime(2023, 6, 30))\n ax1.vlines(x=[datetime.datetime(2023, 2, 10),\n datetime.datetime(2023, 5, 18),\n datetime.datetime(2023, 6, 6)],\n ymin=[0, 0.25, 0.5],\n ymax=[0.25, 0.5, 0.75])\n ax2.set_xlim(left=0,\n right=0.5)\n ax2.vlines(x=[0.3, 0.35],\n ymin=[np.datetime64('2023-03-20'), np.datetime64('2023-03-31')],\n ymax=[np.datetime64('2023-05-01'), np.datetime64('2023-05-16')])\n ax3.set_xlim(left=datetime.datetime(2023, 7, 1),\n right=datetime.datetime(2023, 12, 31))\n ax3.vlines(x=[datetime.datetime(2023, 9, 1), datetime.datetime(2023, 12, 10)],\n ymin=datetime.datetime(2023, 1, 15),\n ymax=datetime.datetime(2023, 1, 30))\n | .venv\Lib\site-packages\matplotlib\tests\test_datetime.py | test_datetime.py | Python | 32,635 | 0.95 | 0.144509 | 0.009642 | python-kit | 274 | 2025-06-19T06:47:57.572258 | GPL-3.0 | true | 4f1ff33ec85c8199a4e6bd94f5356b00 |
"""\nTest output reproducibility.\n"""\n\nimport os\nimport sys\n\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nfrom matplotlib.cbook import get_sample_data\nfrom matplotlib.collections import PathCollection\nfrom matplotlib.image import BboxImage\nfrom matplotlib.offsetbox import AnchoredOffsetbox, AuxTransformBox\nfrom matplotlib.patches import Circle, PathPatch\nfrom matplotlib.path import Path\nfrom matplotlib.testing import subprocess_run_for_testing\nfrom matplotlib.testing._markers import needs_ghostscript, needs_usetex\nimport matplotlib.testing.compare\nfrom matplotlib.text import TextPath\nfrom matplotlib.transforms import IdentityTransform\n\n\ndef _save_figure(objects='mhip', fmt="pdf", usetex=False):\n mpl.use(fmt)\n mpl.rcParams.update({'svg.hashsalt': 'asdf', 'text.usetex': usetex})\n\n fig = plt.figure()\n\n if 'm' in objects:\n # use different markers...\n ax1 = fig.add_subplot(1, 6, 1)\n x = range(10)\n ax1.plot(x, [1] * 10, marker='D')\n ax1.plot(x, [2] * 10, marker='x')\n ax1.plot(x, [3] * 10, marker='^')\n ax1.plot(x, [4] * 10, marker='H')\n ax1.plot(x, [5] * 10, marker='v')\n\n if 'h' in objects:\n # also use different hatch patterns\n ax2 = fig.add_subplot(1, 6, 2)\n bars = (ax2.bar(range(1, 5), range(1, 5)) +\n ax2.bar(range(1, 5), [6] * 4, bottom=range(1, 5)))\n ax2.set_xticks([1.5, 2.5, 3.5, 4.5])\n\n patterns = ('-', '+', 'x', '\\', '*', 'o', 'O', '.')\n for bar, pattern in zip(bars, patterns):\n bar.set_hatch(pattern)\n\n if 'i' in objects:\n # also use different images\n A = [[1, 2, 3], [2, 3, 1], [3, 1, 2]]\n fig.add_subplot(1, 6, 3).imshow(A, interpolation='nearest')\n A = [[1, 3, 2], [1, 2, 3], [3, 1, 2]]\n fig.add_subplot(1, 6, 4).imshow(A, interpolation='bilinear')\n A = [[2, 3, 1], [1, 2, 3], [2, 1, 3]]\n fig.add_subplot(1, 6, 5).imshow(A, interpolation='bicubic')\n\n if 'p' in objects:\n\n # clipping support class, copied from demo_text_path.py gallery example\n class PathClippedImagePatch(PathPatch):\n """\n The given image is used to draw the face of the patch. Internally,\n it uses BboxImage whose clippath set to the path of the patch.\n\n FIXME : The result is currently dpi dependent.\n """\n\n def __init__(self, path, bbox_image, **kwargs):\n super().__init__(path, **kwargs)\n self.bbox_image = BboxImage(\n self.get_window_extent, norm=None, origin=None)\n self.bbox_image.set_data(bbox_image)\n\n def set_facecolor(self, color):\n """Simply ignore facecolor."""\n super().set_facecolor("none")\n\n def draw(self, renderer=None):\n # the clip path must be updated every draw. any solution? -JJ\n self.bbox_image.set_clip_path(self._path, self.get_transform())\n self.bbox_image.draw(renderer)\n super().draw(renderer)\n\n # add a polar projection\n px = fig.add_subplot(projection="polar")\n pimg = px.imshow([[2]])\n pimg.set_clip_path(Circle((0, 1), radius=0.3333))\n\n # add a text-based clipping path (origin: demo_text_path.py)\n (ax1, ax2) = fig.subplots(2)\n arr = plt.imread(get_sample_data("grace_hopper.jpg"))\n text_path = TextPath((0, 0), "!?", size=150)\n p = PathClippedImagePatch(text_path, arr, ec="k")\n offsetbox = AuxTransformBox(IdentityTransform())\n offsetbox.add_artist(p)\n ao = AnchoredOffsetbox(loc='upper left', child=offsetbox, frameon=True,\n borderpad=0.2)\n ax1.add_artist(ao)\n\n # add a 2x2 grid of path-clipped axes (origin: test_artist.py)\n exterior = Path.unit_rectangle().deepcopy()\n exterior.vertices *= 4\n exterior.vertices -= 2\n interior = Path.unit_circle().deepcopy()\n interior.vertices = interior.vertices[::-1]\n clip_path = Path.make_compound_path(exterior, interior)\n\n star = Path.unit_regular_star(6).deepcopy()\n star.vertices *= 2.6\n\n (row1, row2) = fig.subplots(2, 2, sharex=True, sharey=True)\n for row in (row1, row2):\n ax1, ax2 = row\n collection = PathCollection([star], lw=5, edgecolor='blue',\n facecolor='red', alpha=0.7, hatch='*')\n collection.set_clip_path(clip_path, ax1.transData)\n ax1.add_collection(collection)\n\n patch = PathPatch(star, lw=5, edgecolor='blue', facecolor='red',\n alpha=0.7, hatch='*')\n patch.set_clip_path(clip_path, ax2.transData)\n ax2.add_patch(patch)\n\n ax1.set_xlim([-3, 3])\n ax1.set_ylim([-3, 3])\n\n x = range(5)\n ax = fig.add_subplot(1, 6, 6)\n ax.plot(x, x)\n ax.set_title('A string $1+2+\\sigma$')\n ax.set_xlabel('A string $1+2+\\sigma$')\n ax.set_ylabel('A string $1+2+\\sigma$')\n\n stdout = getattr(sys.stdout, 'buffer', sys.stdout)\n fig.savefig(stdout, format=fmt)\n\n\n@pytest.mark.parametrize(\n "objects, fmt, usetex", [\n ("", "pdf", False),\n ("m", "pdf", False),\n ("h", "pdf", False),\n ("i", "pdf", False),\n ("mhip", "pdf", False),\n ("mhip", "ps", False),\n pytest.param(\n "mhip", "ps", True, marks=[needs_usetex, needs_ghostscript]),\n ("p", "svg", False),\n ("mhip", "svg", False),\n pytest.param("mhip", "svg", True, marks=needs_usetex),\n ]\n)\ndef test_determinism_check(objects, fmt, usetex):\n """\n Output three times the same graphs and checks that the outputs are exactly\n the same.\n\n Parameters\n ----------\n objects : str\n Objects to be included in the test document: 'm' for markers, 'h' for\n hatch patterns, 'i' for images, and 'p' for paths.\n fmt : {"pdf", "ps", "svg"}\n Output format.\n """\n plots = [\n subprocess_run_for_testing(\n [sys.executable, "-R", "-c",\n f"from matplotlib.tests.test_determinism import _save_figure;"\n f"_save_figure({objects!r}, {fmt!r}, {usetex})"],\n env={**os.environ, "SOURCE_DATE_EPOCH": "946684800",\n "MPLBACKEND": "Agg"},\n text=False, capture_output=True, check=True).stdout\n for _ in range(3)\n ]\n for p in plots[1:]:\n if fmt == "ps" and usetex:\n if p != plots[0]:\n pytest.skip("failed, maybe due to ghostscript timestamps")\n else:\n assert p == plots[0]\n\n\n@pytest.mark.parametrize(\n "fmt, string", [\n ("pdf", b"/CreationDate (D:20000101000000Z)"),\n # SOURCE_DATE_EPOCH support is not tested with text.usetex,\n # because the produced timestamp comes from ghostscript:\n # %%CreationDate: D:20000101000000Z00\'00\', and this could change\n # with another ghostscript version.\n ("ps", b"%%CreationDate: Sat Jan 01 00:00:00 2000"),\n ]\n)\ndef test_determinism_source_date_epoch(fmt, string):\n """\n Test SOURCE_DATE_EPOCH support. Output a document with the environment\n variable SOURCE_DATE_EPOCH set to 2000-01-01 00:00 UTC and check that the\n document contains the timestamp that corresponds to this date (given as an\n argument).\n\n Parameters\n ----------\n fmt : {"pdf", "ps", "svg"}\n Output format.\n string : bytes\n Timestamp string for 2000-01-01 00:00 UTC.\n """\n buf = subprocess_run_for_testing(\n [sys.executable, "-R", "-c",\n f"from matplotlib.tests.test_determinism import _save_figure; "\n f"_save_figure('', {fmt!r})"],\n env={**os.environ, "SOURCE_DATE_EPOCH": "946684800",\n "MPLBACKEND": "Agg"}, capture_output=True, text=False, check=True).stdout\n assert string in buf\n | .venv\Lib\site-packages\matplotlib\tests\test_determinism.py | test_determinism.py | Python | 7,958 | 0.95 | 0.105505 | 0.064171 | vue-tools | 952 | 2024-02-19T20:07:10.033899 | Apache-2.0 | true | a052c9fadf933a058ce94c28421db83d |
import pytest\n\n\ndef test_sphinx_gallery_example_header():\n """\n We have copied EXAMPLE_HEADER and modified it to include meta keywords.\n This test monitors that the version we have copied is still the same as\n the EXAMPLE_HEADER in sphinx-gallery. If sphinx-gallery changes its\n EXAMPLE_HEADER, this test will start to fail. In that case, please update\n the monkey-patching of EXAMPLE_HEADER in conf.py.\n """\n pytest.importorskip('sphinx_gallery', minversion='0.16.0')\n from sphinx_gallery import gen_rst\n\n EXAMPLE_HEADER = """\n.. DO NOT EDIT.\n.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.\n.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:\n.. "{0}"\n.. LINE NUMBERS ARE GIVEN BELOW.\n\n.. only:: html\n\n .. note::\n :class: sphx-glr-download-link-note\n\n :ref:`Go to the end <sphx_glr_download_{1}>`\n to download the full example code.{2}\n\n.. rst-class:: sphx-glr-example-title\n\n.. _sphx_glr_{1}:\n\n"""\n assert gen_rst.EXAMPLE_HEADER == EXAMPLE_HEADER\n | .venv\Lib\site-packages\matplotlib\tests\test_doc.py | test_doc.py | Python | 1,015 | 0.85 | 0.085714 | 0 | react-lib | 590 | 2024-08-09T13:06:05.654252 | MIT | true | 931af504c49c3888c68f9fb6a43e2afd |
import json\nfrom pathlib import Path\nimport shutil\n\nimport matplotlib.dviread as dr\nimport pytest\n\n\ndef test_PsfontsMap(monkeypatch):\n monkeypatch.setattr(dr, 'find_tex_file', lambda x: x.decode())\n\n filename = str(Path(__file__).parent / 'baseline_images/dviread/test.map')\n fontmap = dr.PsfontsMap(filename)\n # Check all properties of a few fonts\n for n in [1, 2, 3, 4, 5]:\n key = b'TeXfont%d' % n\n entry = fontmap[key]\n assert entry.texname == key\n assert entry.psname == b'PSfont%d' % n\n if n not in [3, 5]:\n assert entry.encoding == 'font%d.enc' % n\n elif n == 3:\n assert entry.encoding == 'enc3.foo'\n # We don't care about the encoding of TeXfont5, which specifies\n # multiple encodings.\n if n not in [1, 5]:\n assert entry.filename == 'font%d.pfa' % n\n else:\n assert entry.filename == 'font%d.pfb' % n\n if n == 4:\n assert entry.effects == {'slant': -0.1, 'extend': 1.2}\n else:\n assert entry.effects == {}\n # Some special cases\n entry = fontmap[b'TeXfont6']\n assert entry.filename is None\n assert entry.encoding is None\n entry = fontmap[b'TeXfont7']\n assert entry.filename is None\n assert entry.encoding == 'font7.enc'\n entry = fontmap[b'TeXfont8']\n assert entry.filename == 'font8.pfb'\n assert entry.encoding is None\n entry = fontmap[b'TeXfont9']\n assert entry.psname == b'TeXfont9'\n assert entry.filename == '/absolute/font9.pfb'\n # First of duplicates only.\n entry = fontmap[b'TeXfontA']\n assert entry.psname == b'PSfontA1'\n # Slant/Extend only works for T1 fonts.\n entry = fontmap[b'TeXfontB']\n assert entry.psname == b'PSfontB6'\n # Subsetted TrueType must have encoding.\n entry = fontmap[b'TeXfontC']\n assert entry.psname == b'PSfontC3'\n # Missing font\n with pytest.raises(LookupError, match='no-such-font'):\n fontmap[b'no-such-font']\n with pytest.raises(LookupError, match='%'):\n fontmap[b'%']\n\n\n@pytest.mark.skipif(shutil.which("kpsewhich") is None,\n reason="kpsewhich is not available")\ndef test_dviread():\n dirpath = Path(__file__).parent / 'baseline_images/dviread'\n with (dirpath / 'test.json').open() as f:\n correct = json.load(f)\n with dr.Dvi(str(dirpath / 'test.dvi'), None) as dvi:\n data = [{'text': [[t.x, t.y,\n chr(t.glyph),\n t.font.texname.decode('ascii'),\n round(t.font.size, 2)]\n for t in page.text],\n 'boxes': [[b.x, b.y, b.height, b.width] for b in page.boxes]}\n for page in dvi]\n assert data == correct\n | .venv\Lib\site-packages\matplotlib\tests\test_dviread.py | test_dviread.py | Python | 2,764 | 0.95 | 0.12987 | 0.112676 | awesome-app | 451 | 2025-06-18T21:58:10.497021 | MIT | true | e7d568cc87682a831b0865238c8472e3 |
import copy\nfrom datetime import datetime\nimport io\nimport pickle\nimport platform\nfrom threading import Timer\nfrom types import SimpleNamespace\nimport warnings\n\nimport numpy as np\nimport pytest\nfrom PIL import Image\n\nimport matplotlib as mpl\nfrom matplotlib import gridspec\nfrom matplotlib.testing.decorators import image_comparison, check_figures_equal\nfrom matplotlib.axes import Axes\nfrom matplotlib.backend_bases import KeyEvent, MouseEvent\nfrom matplotlib.figure import Figure, FigureBase\nfrom matplotlib.layout_engine import (ConstrainedLayoutEngine,\n TightLayoutEngine,\n PlaceHolderLayoutEngine)\nfrom matplotlib.ticker import AutoMinorLocator, FixedFormatter, ScalarFormatter\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\n\n@image_comparison(['figure_align_labels'], extensions=['png', 'svg'],\n tol=0 if platform.machine() == 'x86_64' else 0.01)\ndef test_align_labels():\n fig = plt.figure(layout='tight')\n gs = gridspec.GridSpec(3, 3)\n\n ax = fig.add_subplot(gs[0, :2])\n ax.plot(np.arange(0, 1e6, 1000))\n ax.set_ylabel('Ylabel0 0')\n ax = fig.add_subplot(gs[0, -1])\n ax.plot(np.arange(0, 1e4, 100))\n\n for i in range(3):\n ax = fig.add_subplot(gs[1, i])\n ax.set_ylabel('YLabel1 %d' % i)\n ax.set_xlabel('XLabel1 %d' % i)\n if i in [0, 2]:\n ax.xaxis.set_label_position("top")\n ax.xaxis.tick_top()\n if i == 0:\n for tick in ax.get_xticklabels():\n tick.set_rotation(90)\n if i == 2:\n ax.yaxis.set_label_position("right")\n ax.yaxis.tick_right()\n\n for i in range(3):\n ax = fig.add_subplot(gs[2, i])\n ax.set_xlabel(f'XLabel2 {i}')\n ax.set_ylabel(f'YLabel2 {i}')\n\n if i == 2:\n ax.plot(np.arange(0, 1e4, 10))\n ax.yaxis.set_label_position("right")\n ax.yaxis.tick_right()\n for tick in ax.get_xticklabels():\n tick.set_rotation(90)\n\n fig.align_labels()\n\n\n@image_comparison(['figure_align_titles_tight.png',\n 'figure_align_titles_constrained.png'],\n tol=0 if platform.machine() == 'x86_64' else 0.022,\n style='mpl20')\ndef test_align_titles():\n for layout in ['tight', 'constrained']:\n fig, axs = plt.subplots(1, 2, layout=layout, width_ratios=[2, 1])\n\n ax = axs[0]\n ax.plot(np.arange(0, 1e6, 1000))\n ax.set_title('Title0 left', loc='left')\n ax.set_title('Title0 center', loc='center')\n ax.set_title('Title0 right', loc='right')\n\n ax = axs[1]\n ax.plot(np.arange(0, 1e4, 100))\n ax.set_title('Title1')\n ax.set_xlabel('Xlabel0')\n ax.xaxis.set_label_position("top")\n ax.xaxis.tick_top()\n for tick in ax.get_xticklabels():\n tick.set_rotation(90)\n\n fig.align_titles()\n\n\ndef test_align_labels_stray_axes():\n fig, axs = plt.subplots(2, 2)\n for nn, ax in enumerate(axs.flat):\n ax.set_xlabel('Boo')\n ax.set_xlabel('Who')\n ax.plot(np.arange(4)**nn, np.arange(4)**nn)\n fig.align_ylabels()\n fig.align_xlabels()\n fig.draw_without_rendering()\n xn = np.zeros(4)\n yn = np.zeros(4)\n for nn, ax in enumerate(axs.flat):\n yn[nn] = ax.xaxis.label.get_position()[1]\n xn[nn] = ax.yaxis.label.get_position()[0]\n np.testing.assert_allclose(xn[:2], xn[2:])\n np.testing.assert_allclose(yn[::2], yn[1::2])\n\n fig, axs = plt.subplots(2, 2, constrained_layout=True)\n for nn, ax in enumerate(axs.flat):\n ax.set_xlabel('Boo')\n ax.set_xlabel('Who')\n pc = ax.pcolormesh(np.random.randn(10, 10))\n fig.colorbar(pc, ax=ax)\n fig.align_ylabels()\n fig.align_xlabels()\n fig.draw_without_rendering()\n xn = np.zeros(4)\n yn = np.zeros(4)\n for nn, ax in enumerate(axs.flat):\n yn[nn] = ax.xaxis.label.get_position()[1]\n xn[nn] = ax.yaxis.label.get_position()[0]\n np.testing.assert_allclose(xn[:2], xn[2:])\n np.testing.assert_allclose(yn[::2], yn[1::2])\n\n\ndef test_figure_label():\n # pyplot figure creation, selection, and closing with label/number/instance\n plt.close('all')\n fig_today = plt.figure('today')\n plt.figure(3)\n plt.figure('tomorrow')\n plt.figure()\n plt.figure(0)\n plt.figure(1)\n plt.figure(3)\n assert plt.get_fignums() == [0, 1, 3, 4, 5]\n assert plt.get_figlabels() == ['', 'today', '', 'tomorrow', '']\n plt.close(10)\n plt.close()\n plt.close(5)\n plt.close('tomorrow')\n assert plt.get_fignums() == [0, 1]\n assert plt.get_figlabels() == ['', 'today']\n plt.figure(fig_today)\n assert plt.gcf() == fig_today\n with pytest.raises(ValueError):\n plt.figure(Figure())\n\n\ndef test_figure_label_replaced():\n plt.close('all')\n fig = plt.figure(1)\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match="Changing 'Figure.number' is deprecated"):\n fig.number = 2\n assert fig.number == 2\n\n\ndef test_figure_no_label():\n # standalone figures do not have a figure attribute\n fig = Figure()\n with pytest.raises(AttributeError):\n fig.number\n # but one can set one\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match="Changing 'Figure.number' is deprecated"):\n fig.number = 5\n assert fig.number == 5\n # even though it's not known by pyplot\n assert not plt.fignum_exists(fig.number)\n\n\ndef test_fignum_exists():\n # pyplot figure creation, selection and closing with fignum_exists\n plt.figure('one')\n plt.figure(2)\n plt.figure('three')\n plt.figure()\n assert plt.fignum_exists('one')\n assert plt.fignum_exists(2)\n assert plt.fignum_exists('three')\n assert plt.fignum_exists(4)\n plt.close('one')\n plt.close(4)\n assert not plt.fignum_exists('one')\n assert not plt.fignum_exists(4)\n\n\ndef test_clf_keyword():\n # test if existing figure is cleared with figure() and subplots()\n text1 = 'A fancy plot'\n text2 = 'Really fancy!'\n\n fig0 = plt.figure(num=1)\n fig0.suptitle(text1)\n assert [t.get_text() for t in fig0.texts] == [text1]\n\n fig1 = plt.figure(num=1, clear=False)\n fig1.text(0.5, 0.5, text2)\n assert fig0 is fig1\n assert [t.get_text() for t in fig1.texts] == [text1, text2]\n\n fig2, ax2 = plt.subplots(2, 1, num=1, clear=True)\n assert fig0 is fig2\n assert [t.get_text() for t in fig2.texts] == []\n\n\n@image_comparison(['figure_today.png'],\n tol=0 if platform.machine() == 'x86_64' else 0.015)\ndef test_figure():\n # named figure support\n fig = plt.figure('today')\n ax = fig.add_subplot()\n ax.set_title(fig.get_label())\n ax.plot(np.arange(5))\n # plot red line in a different figure.\n plt.figure('tomorrow')\n plt.plot([0, 1], [1, 0], 'r')\n # Return to the original; make sure the red line is not there.\n plt.figure('today')\n plt.close('tomorrow')\n\n\n@image_comparison(['figure_legend.png'])\ndef test_figure_legend():\n fig, axs = plt.subplots(2)\n axs[0].plot([0, 1], [1, 0], label='x', color='g')\n axs[0].plot([0, 1], [0, 1], label='y', color='r')\n axs[0].plot([0, 1], [0.5, 0.5], label='y', color='k')\n\n axs[1].plot([0, 1], [1, 0], label='_y', color='r')\n axs[1].plot([0, 1], [0, 1], label='z', color='b')\n fig.legend()\n\n\ndef test_gca():\n fig = plt.figure()\n\n # test that gca() picks up Axes created via add_axes()\n ax0 = fig.add_axes([0, 0, 1, 1])\n assert fig.gca() is ax0\n\n # test that gca() picks up Axes created via add_subplot()\n ax1 = fig.add_subplot(111)\n assert fig.gca() is ax1\n\n # add_axes on an existing Axes should not change stored order, but will\n # make it current.\n fig.add_axes(ax0)\n assert fig.axes == [ax0, ax1]\n assert fig.gca() is ax0\n\n # sca() should not change stored order of Axes, which is order added.\n fig.sca(ax0)\n assert fig.axes == [ax0, ax1]\n\n # add_subplot on an existing Axes should not change stored order, but will\n # make it current.\n fig.add_subplot(ax1)\n assert fig.axes == [ax0, ax1]\n assert fig.gca() is ax1\n\n\ndef test_add_subplot_subclass():\n fig = plt.figure()\n fig.add_subplot(axes_class=Axes)\n with pytest.raises(ValueError):\n fig.add_subplot(axes_class=Axes, projection="3d")\n with pytest.raises(ValueError):\n fig.add_subplot(axes_class=Axes, polar=True)\n with pytest.raises(ValueError):\n fig.add_subplot(projection="3d", polar=True)\n with pytest.raises(TypeError):\n fig.add_subplot(projection=42)\n\n\ndef test_add_subplot_invalid():\n fig = plt.figure()\n with pytest.raises(ValueError,\n match='Number of columns must be a positive integer'):\n fig.add_subplot(2, 0, 1)\n with pytest.raises(ValueError,\n match='Number of rows must be a positive integer'):\n fig.add_subplot(0, 2, 1)\n with pytest.raises(ValueError, match='num must be an integer with '\n '1 <= num <= 4'):\n fig.add_subplot(2, 2, 0)\n with pytest.raises(ValueError, match='num must be an integer with '\n '1 <= num <= 4'):\n fig.add_subplot(2, 2, 5)\n with pytest.raises(ValueError, match='num must be an integer with '\n '1 <= num <= 4'):\n fig.add_subplot(2, 2, 0.5)\n\n with pytest.raises(ValueError, match='must be a three-digit integer'):\n fig.add_subplot(42)\n with pytest.raises(ValueError, match='must be a three-digit integer'):\n fig.add_subplot(1000)\n\n with pytest.raises(TypeError, match='takes 1 or 3 positional arguments '\n 'but 2 were given'):\n fig.add_subplot(2, 2)\n with pytest.raises(TypeError, match='takes 1 or 3 positional arguments '\n 'but 4 were given'):\n fig.add_subplot(1, 2, 3, 4)\n with pytest.raises(ValueError,\n match="Number of rows must be a positive integer, "\n "not '2'"):\n fig.add_subplot('2', 2, 1)\n with pytest.raises(ValueError,\n match='Number of columns must be a positive integer, '\n 'not 2.0'):\n fig.add_subplot(2, 2.0, 1)\n _, ax = plt.subplots()\n with pytest.raises(ValueError,\n match='The Axes must have been created in the '\n 'present figure'):\n fig.add_subplot(ax)\n\n\n@image_comparison(['figure_suptitle.png'])\ndef test_suptitle():\n fig, _ = plt.subplots()\n fig.suptitle('hello', color='r')\n fig.suptitle('title', color='g', rotation=30)\n\n\ndef test_suptitle_fontproperties():\n fig, ax = plt.subplots()\n fps = mpl.font_manager.FontProperties(size='large', weight='bold')\n txt = fig.suptitle('fontprops title', fontproperties=fps)\n assert txt.get_fontsize() == fps.get_size_in_points()\n assert txt.get_weight() == fps.get_weight()\n\n\ndef test_suptitle_subfigures():\n fig = plt.figure(figsize=(4, 3))\n sf1, sf2 = fig.subfigures(1, 2)\n sf2.set_facecolor('white')\n sf1.subplots()\n sf2.subplots()\n fig.suptitle("This is a visible suptitle.")\n\n # verify the first subfigure facecolor is the default transparent\n assert sf1.get_facecolor() == (0.0, 0.0, 0.0, 0.0)\n # verify the second subfigure facecolor is white\n assert sf2.get_facecolor() == (1.0, 1.0, 1.0, 1.0)\n\n\ndef test_get_suptitle_supxlabel_supylabel():\n fig, ax = plt.subplots()\n assert fig.get_suptitle() == ""\n assert fig.get_supxlabel() == ""\n assert fig.get_supylabel() == ""\n fig.suptitle('suptitle')\n assert fig.get_suptitle() == 'suptitle'\n fig.supxlabel('supxlabel')\n assert fig.get_supxlabel() == 'supxlabel'\n fig.supylabel('supylabel')\n assert fig.get_supylabel() == 'supylabel'\n\n\n@image_comparison(['alpha_background'],\n # only test png and svg. The PDF output appears correct,\n # but Ghostscript does not preserve the background color.\n extensions=['png', 'svg'],\n savefig_kwarg={'facecolor': (0, 1, 0.4),\n 'edgecolor': 'none'})\ndef test_alpha():\n # We want an image which has a background color and an alpha of 0.4.\n fig = plt.figure(figsize=[2, 1])\n fig.set_facecolor((0, 1, 0.4))\n fig.patch.set_alpha(0.4)\n fig.patches.append(mpl.patches.CirclePolygon(\n [20, 20], radius=15, alpha=0.6, facecolor='red'))\n\n\ndef test_too_many_figures():\n with pytest.warns(RuntimeWarning):\n for i in range(mpl.rcParams['figure.max_open_warning'] + 1):\n plt.figure()\n\n\ndef test_iterability_axes_argument():\n\n # This is a regression test for matplotlib/matplotlib#3196. If one of the\n # arguments returned by _as_mpl_axes defines __getitem__ but is not\n # iterable, this would raise an exception. This is because we check\n # whether the arguments are iterable, and if so we try and convert them\n # to a tuple. However, the ``iterable`` function returns True if\n # __getitem__ is present, but some classes can define __getitem__ without\n # being iterable. The tuple conversion is now done in a try...except in\n # case it fails.\n\n class MyAxes(Axes):\n def __init__(self, *args, myclass=None, **kwargs):\n Axes.__init__(self, *args, **kwargs)\n\n class MyClass:\n\n def __getitem__(self, item):\n if item != 'a':\n raise ValueError("item should be a")\n\n def _as_mpl_axes(self):\n return MyAxes, {'myclass': self}\n\n fig = plt.figure()\n fig.add_subplot(1, 1, 1, projection=MyClass())\n plt.close(fig)\n\n\ndef test_set_fig_size():\n fig = plt.figure()\n\n # check figwidth\n fig.set_figwidth(5)\n assert fig.get_figwidth() == 5\n\n # check figheight\n fig.set_figheight(1)\n assert fig.get_figheight() == 1\n\n # check using set_size_inches\n fig.set_size_inches(2, 4)\n assert fig.get_figwidth() == 2\n assert fig.get_figheight() == 4\n\n # check using tuple to first argument\n fig.set_size_inches((1, 3))\n assert fig.get_figwidth() == 1\n assert fig.get_figheight() == 3\n\n\ndef test_axes_remove():\n fig, axs = plt.subplots(2, 2)\n axs[-1, -1].remove()\n for ax in axs.ravel()[:-1]:\n assert ax in fig.axes\n assert axs[-1, -1] not in fig.axes\n assert len(fig.axes) == 3\n\n\ndef test_figaspect():\n w, h = plt.figaspect(np.float64(2) / np.float64(1))\n assert h / w == 2\n w, h = plt.figaspect(2)\n assert h / w == 2\n w, h = plt.figaspect(np.zeros((1, 2)))\n assert h / w == 0.5\n w, h = plt.figaspect(np.zeros((2, 2)))\n assert h / w == 1\n\n\n@pytest.mark.parametrize('which', ['both', 'major', 'minor'])\ndef test_autofmt_xdate(which):\n date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013',\n '7 Jan 2013', '8 Jan 2013', '9 Jan 2013', '10 Jan 2013',\n '11 Jan 2013', '12 Jan 2013', '13 Jan 2013', '14 Jan 2013']\n\n time = ['16:44:00', '16:45:00', '16:46:00', '16:47:00', '16:48:00',\n '16:49:00', '16:51:00', '16:52:00', '16:53:00', '16:55:00',\n '16:56:00', '16:57:00']\n\n angle = 60\n minors = [1, 2, 3, 4, 5, 6, 7]\n\n x = mdates.datestr2num(date)\n y = mdates.datestr2num(time)\n\n fig, ax = plt.subplots()\n\n ax.plot(x, y)\n ax.yaxis_date()\n ax.xaxis_date()\n\n ax.xaxis.set_minor_locator(AutoMinorLocator(2))\n with warnings.catch_warnings():\n warnings.filterwarnings(\n 'ignore',\n 'FixedFormatter should only be used together with FixedLocator')\n ax.xaxis.set_minor_formatter(FixedFormatter(minors))\n\n fig.autofmt_xdate(0.2, angle, 'right', which)\n\n if which in ('both', 'major'):\n for label in fig.axes[0].get_xticklabels(False, 'major'):\n assert int(label.get_rotation()) == angle\n\n if which in ('both', 'minor'):\n for label in fig.axes[0].get_xticklabels(True, 'minor'):\n assert int(label.get_rotation()) == angle\n\n\ndef test_autofmt_xdate_colorbar_constrained():\n # check works with a colorbar.\n # with constrained layout, colorbars do not have a gridspec,\n # but autofmt_xdate checks if all axes have a gridspec before being\n # applied.\n fig, ax = plt.subplots(layout="constrained")\n im = ax.imshow([[1, 4, 6], [2, 3, 5]])\n plt.colorbar(im)\n fig.autofmt_xdate()\n fig.draw_without_rendering()\n label = ax.get_xticklabels(which='major')[1]\n assert label.get_rotation() == 30.0\n\n\n@mpl.style.context('default')\ndef test_change_dpi():\n fig = plt.figure(figsize=(4, 4))\n fig.draw_without_rendering()\n assert fig.canvas.renderer.height == 400\n assert fig.canvas.renderer.width == 400\n fig.dpi = 50\n fig.draw_without_rendering()\n assert fig.canvas.renderer.height == 200\n assert fig.canvas.renderer.width == 200\n\n\n@pytest.mark.parametrize('width, height', [\n (1, np.nan),\n (-1, 1),\n (np.inf, 1)\n])\ndef test_invalid_figure_size(width, height):\n with pytest.raises(ValueError):\n plt.figure(figsize=(width, height))\n\n fig = plt.figure()\n with pytest.raises(ValueError):\n fig.set_size_inches(width, height)\n\n\ndef test_invalid_figure_add_axes():\n fig = plt.figure()\n with pytest.raises(TypeError,\n match="missing 1 required positional argument: 'rect'"):\n fig.add_axes()\n\n with pytest.raises(ValueError):\n fig.add_axes((.1, .1, .5, np.nan))\n\n with pytest.raises(TypeError, match="multiple values for argument 'rect'"):\n fig.add_axes([0, 0, 1, 1], rect=[0, 0, 1, 1])\n\n fig2, ax = plt.subplots()\n with pytest.raises(ValueError,\n match="The Axes must have been created in the present "\n "figure"):\n fig.add_axes(ax)\n\n fig2.delaxes(ax)\n with pytest.raises(TypeError, match=r"add_axes\(\) takes 1 positional arguments"):\n fig2.add_axes(ax, "extra positional argument")\n\n with pytest.raises(TypeError, match=r"add_axes\(\) takes 1 positional arguments"):\n fig.add_axes([0, 0, 1, 1], "extra positional argument")\n\n\ndef test_subplots_shareax_loglabels():\n fig, axs = plt.subplots(2, 2, sharex=True, sharey=True, squeeze=False)\n for ax in axs.flat:\n ax.plot([10, 20, 30], [10, 20, 30])\n\n ax.set_yscale("log")\n ax.set_xscale("log")\n\n for ax in axs[0, :]:\n assert 0 == len(ax.xaxis.get_ticklabels(which='both'))\n\n for ax in axs[1, :]:\n assert 0 < len(ax.xaxis.get_ticklabels(which='both'))\n\n for ax in axs[:, 1]:\n assert 0 == len(ax.yaxis.get_ticklabels(which='both'))\n\n for ax in axs[:, 0]:\n assert 0 < len(ax.yaxis.get_ticklabels(which='both'))\n\n\ndef test_savefig():\n fig = plt.figure()\n msg = r"savefig\(\) takes 2 positional arguments but 3 were given"\n with pytest.raises(TypeError, match=msg):\n fig.savefig("fname1.png", "fname2.png")\n\n\ndef test_savefig_warns():\n fig = plt.figure()\n for format in ['png', 'pdf', 'svg', 'tif', 'jpg']:\n with pytest.raises(TypeError):\n fig.savefig(io.BytesIO(), format=format, non_existent_kwarg=True)\n\n\ndef test_savefig_backend():\n fig = plt.figure()\n # Intentionally use an invalid module name.\n with pytest.raises(ModuleNotFoundError, match="No module named '@absent'"):\n fig.savefig("test", backend="module://@absent")\n with pytest.raises(ValueError,\n match="The 'pdf' backend does not support png output"):\n fig.savefig("test.png", backend="pdf")\n\n\n@pytest.mark.parametrize('backend', [\n pytest.param('Agg', marks=[pytest.mark.backend('Agg')]),\n pytest.param('Cairo', marks=[pytest.mark.backend('Cairo')]),\n])\ndef test_savefig_pixel_ratio(backend):\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3])\n with io.BytesIO() as buf:\n fig.savefig(buf, format='png')\n ratio1 = Image.open(buf)\n ratio1.load()\n\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3])\n fig.canvas._set_device_pixel_ratio(2)\n with io.BytesIO() as buf:\n fig.savefig(buf, format='png')\n ratio2 = Image.open(buf)\n ratio2.load()\n\n assert ratio1 == ratio2\n\n\ndef test_savefig_preserve_layout_engine():\n fig = plt.figure(layout='compressed')\n fig.savefig(io.BytesIO(), bbox_inches='tight')\n\n assert fig.get_layout_engine()._compress\n\n\ndef test_savefig_locate_colorbar():\n fig, ax = plt.subplots()\n pc = ax.pcolormesh(np.random.randn(2, 2))\n cbar = fig.colorbar(pc, aspect=40)\n fig.savefig(io.BytesIO(), bbox_inches=mpl.transforms.Bbox([[0, 0], [4, 4]]))\n\n # Check that an aspect ratio has been applied.\n assert (cbar.ax.get_position(original=True).bounds !=\n cbar.ax.get_position(original=False).bounds)\n\n\n@mpl.rc_context({"savefig.transparent": True})\n@check_figures_equal(extensions=["png"])\ndef test_savefig_transparent(fig_test, fig_ref):\n # create two transparent subfigures with corresponding transparent inset\n # axes. the entire background of the image should be transparent.\n gs1 = fig_test.add_gridspec(3, 3, left=0.05, wspace=0.05)\n f1 = fig_test.add_subfigure(gs1[:, :])\n f2 = f1.add_subfigure(gs1[0, 0])\n\n ax12 = f2.add_subplot(gs1[:, :])\n\n ax1 = f1.add_subplot(gs1[:-1, :])\n iax1 = ax1.inset_axes([.1, .2, .3, .4])\n iax2 = iax1.inset_axes([.1, .2, .3, .4])\n\n ax2 = fig_test.add_subplot(gs1[-1, :-1])\n ax3 = fig_test.add_subplot(gs1[-1, -1])\n\n for ax in [ax12, ax1, iax1, iax2, ax2, ax3]:\n ax.set(xticks=[], yticks=[])\n ax.spines[:].set_visible(False)\n\n\ndef test_figure_repr():\n fig = plt.figure(figsize=(10, 20), dpi=10)\n assert repr(fig) == "<Figure size 100x200 with 0 Axes>"\n\n\ndef test_valid_layouts():\n fig = Figure(layout=None)\n assert not fig.get_tight_layout()\n assert not fig.get_constrained_layout()\n\n fig = Figure(layout='tight')\n assert fig.get_tight_layout()\n assert not fig.get_constrained_layout()\n\n fig = Figure(layout='constrained')\n assert not fig.get_tight_layout()\n assert fig.get_constrained_layout()\n\n\ndef test_invalid_layouts():\n fig, ax = plt.subplots(layout="constrained")\n with pytest.warns(UserWarning):\n # this should warn,\n fig.subplots_adjust(top=0.8)\n assert isinstance(fig.get_layout_engine(), ConstrainedLayoutEngine)\n\n # Using layout + (tight|constrained)_layout warns, but the former takes\n # precedence.\n wst = "The Figure parameters 'layout' and 'tight_layout'"\n with pytest.warns(UserWarning, match=wst):\n fig = Figure(layout='tight', tight_layout=False)\n assert isinstance(fig.get_layout_engine(), TightLayoutEngine)\n wst = "The Figure parameters 'layout' and 'constrained_layout'"\n with pytest.warns(UserWarning, match=wst):\n fig = Figure(layout='constrained', constrained_layout=False)\n assert not isinstance(fig.get_layout_engine(), TightLayoutEngine)\n assert isinstance(fig.get_layout_engine(), ConstrainedLayoutEngine)\n\n with pytest.raises(ValueError,\n match="Invalid value for 'layout'"):\n Figure(layout='foobar')\n\n # test that layouts can be swapped if no colorbar:\n fig, ax = plt.subplots(layout="constrained")\n fig.set_layout_engine("tight")\n assert isinstance(fig.get_layout_engine(), TightLayoutEngine)\n fig.set_layout_engine("constrained")\n assert isinstance(fig.get_layout_engine(), ConstrainedLayoutEngine)\n\n # test that layouts cannot be swapped if there is a colorbar:\n fig, ax = plt.subplots(layout="constrained")\n pc = ax.pcolormesh(np.random.randn(2, 2))\n fig.colorbar(pc)\n with pytest.raises(RuntimeError, match='Colorbar layout of new layout'):\n fig.set_layout_engine("tight")\n fig.set_layout_engine("none")\n with pytest.raises(RuntimeError, match='Colorbar layout of new layout'):\n fig.set_layout_engine("tight")\n\n fig, ax = plt.subplots(layout="tight")\n pc = ax.pcolormesh(np.random.randn(2, 2))\n fig.colorbar(pc)\n with pytest.raises(RuntimeError, match='Colorbar layout of new layout'):\n fig.set_layout_engine("constrained")\n fig.set_layout_engine("none")\n assert isinstance(fig.get_layout_engine(), PlaceHolderLayoutEngine)\n\n with pytest.raises(RuntimeError, match='Colorbar layout of new layout'):\n fig.set_layout_engine("constrained")\n\n\n@check_figures_equal(extensions=["png"])\ndef test_tightlayout_autolayout_deconflict(fig_test, fig_ref):\n for fig, autolayout in zip([fig_ref, fig_test], [False, True]):\n with mpl.rc_context({'figure.autolayout': autolayout}):\n axes = fig.subplots(ncols=2)\n fig.tight_layout(w_pad=10)\n assert isinstance(fig.get_layout_engine(), PlaceHolderLayoutEngine)\n\n\n@pytest.mark.parametrize('layout', ['constrained', 'compressed'])\ndef test_layout_change_warning(layout):\n """\n Raise a warning when a previously assigned layout changes to tight using\n plt.tight_layout().\n """\n fig, ax = plt.subplots(layout=layout)\n with pytest.warns(UserWarning, match='The figure layout has changed to'):\n plt.tight_layout()\n\n\ndef test_repeated_tightlayout():\n fig = Figure()\n fig.tight_layout()\n # subsequent calls should not warn\n fig.tight_layout()\n fig.tight_layout()\n\n\n@check_figures_equal(extensions=["png", "pdf"])\ndef test_add_artist(fig_test, fig_ref):\n fig_test.dpi = 100\n fig_ref.dpi = 100\n\n fig_test.subplots()\n l1 = plt.Line2D([.2, .7], [.7, .7], gid='l1')\n l2 = plt.Line2D([.2, .7], [.8, .8], gid='l2')\n r1 = plt.Circle((20, 20), 100, transform=None, gid='C1')\n r2 = plt.Circle((.7, .5), .05, gid='C2')\n r3 = plt.Circle((4.5, .8), .55, transform=fig_test.dpi_scale_trans,\n facecolor='crimson', gid='C3')\n for a in [l1, l2, r1, r2, r3]:\n fig_test.add_artist(a)\n l2.remove()\n\n ax2 = fig_ref.subplots()\n l1 = plt.Line2D([.2, .7], [.7, .7], transform=fig_ref.transFigure,\n gid='l1', zorder=21)\n r1 = plt.Circle((20, 20), 100, transform=None, clip_on=False, zorder=20,\n gid='C1')\n r2 = plt.Circle((.7, .5), .05, transform=fig_ref.transFigure, gid='C2',\n zorder=20)\n r3 = plt.Circle((4.5, .8), .55, transform=fig_ref.dpi_scale_trans,\n facecolor='crimson', clip_on=False, zorder=20, gid='C3')\n for a in [l1, r1, r2, r3]:\n ax2.add_artist(a)\n\n\n@pytest.mark.parametrize("fmt", ["png", "pdf", "ps", "eps", "svg"])\ndef test_fspath(fmt, tmp_path):\n out = tmp_path / f"test.{fmt}"\n plt.savefig(out)\n with out.open("rb") as file:\n # All the supported formats include the format name (case-insensitive)\n # in the first 100 bytes.\n assert fmt.encode("ascii") in file.read(100).lower()\n\n\ndef test_tightbbox():\n fig, ax = plt.subplots()\n ax.set_xlim(0, 1)\n t = ax.text(1., 0.5, 'This dangles over end')\n renderer = fig.canvas.get_renderer()\n x1Nom0 = 9.035 # inches\n assert abs(t.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2\n assert abs(ax.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2\n assert abs(fig.get_tightbbox(renderer).x1 - x1Nom0) < 0.05\n assert abs(fig.get_tightbbox(renderer).x0 - 0.679) < 0.05\n # now exclude t from the tight bbox so now the bbox is quite a bit\n # smaller\n t.set_in_layout(False)\n x1Nom = 7.333\n assert abs(ax.get_tightbbox(renderer).x1 - x1Nom * fig.dpi) < 2\n assert abs(fig.get_tightbbox(renderer).x1 - x1Nom) < 0.05\n\n t.set_in_layout(True)\n x1Nom = 7.333\n assert abs(ax.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2\n # test bbox_extra_artists method...\n assert abs(ax.get_tightbbox(renderer, bbox_extra_artists=[]).x1\n - x1Nom * fig.dpi) < 2\n\n\ndef test_axes_removal():\n # Check that units can set the formatter after an Axes removal\n fig, axs = plt.subplots(1, 2, sharex=True)\n axs[1].remove()\n axs[0].plot([datetime(2000, 1, 1), datetime(2000, 2, 1)], [0, 1])\n assert isinstance(axs[0].xaxis.get_major_formatter(),\n mdates.AutoDateFormatter)\n\n # Check that manually setting the formatter, then removing Axes keeps\n # the set formatter.\n fig, axs = plt.subplots(1, 2, sharex=True)\n axs[1].xaxis.set_major_formatter(ScalarFormatter())\n axs[1].remove()\n axs[0].plot([datetime(2000, 1, 1), datetime(2000, 2, 1)], [0, 1])\n assert isinstance(axs[0].xaxis.get_major_formatter(),\n ScalarFormatter)\n\n\ndef test_removed_axis():\n # Simple smoke test to make sure removing a shared axis works\n fig, axs = plt.subplots(2, sharex=True)\n axs[0].remove()\n fig.canvas.draw()\n\n\n@pytest.mark.parametrize('clear_meth', ['clear', 'clf'])\ndef test_figure_clear(clear_meth):\n # we test the following figure clearing scenarios:\n fig = plt.figure()\n\n # a) an empty figure\n fig.clear()\n assert fig.axes == []\n\n # b) a figure with a single unnested axes\n ax = fig.add_subplot(111)\n getattr(fig, clear_meth)()\n assert fig.axes == []\n\n # c) a figure multiple unnested axes\n axes = [fig.add_subplot(2, 1, i+1) for i in range(2)]\n getattr(fig, clear_meth)()\n assert fig.axes == []\n\n # d) a figure with a subfigure\n gs = fig.add_gridspec(ncols=2, nrows=1)\n subfig = fig.add_subfigure(gs[0])\n subaxes = subfig.add_subplot(111)\n getattr(fig, clear_meth)()\n assert subfig not in fig.subfigs\n assert fig.axes == []\n\n # e) a figure with a subfigure and a subplot\n subfig = fig.add_subfigure(gs[0])\n subaxes = subfig.add_subplot(111)\n mainaxes = fig.add_subplot(gs[1])\n\n # e.1) removing just the axes leaves the subplot\n mainaxes.remove()\n assert fig.axes == [subaxes]\n\n # e.2) removing just the subaxes leaves the subplot\n # and subfigure\n mainaxes = fig.add_subplot(gs[1])\n subaxes.remove()\n assert fig.axes == [mainaxes]\n assert subfig in fig.subfigs\n\n # e.3) clearing the subfigure leaves the subplot\n subaxes = subfig.add_subplot(111)\n assert mainaxes in fig.axes\n assert subaxes in fig.axes\n getattr(subfig, clear_meth)()\n assert subfig in fig.subfigs\n assert subaxes not in subfig.axes\n assert subaxes not in fig.axes\n assert mainaxes in fig.axes\n\n # e.4) clearing the whole thing\n subaxes = subfig.add_subplot(111)\n getattr(fig, clear_meth)()\n assert fig.axes == []\n assert fig.subfigs == []\n\n # f) multiple subfigures\n subfigs = [fig.add_subfigure(gs[i]) for i in [0, 1]]\n subaxes = [sfig.add_subplot(111) for sfig in subfigs]\n assert all(ax in fig.axes for ax in subaxes)\n assert all(sfig in fig.subfigs for sfig in subfigs)\n\n # f.1) clearing only one subfigure\n getattr(subfigs[0], clear_meth)()\n assert subaxes[0] not in fig.axes\n assert subaxes[1] in fig.axes\n assert subfigs[1] in fig.subfigs\n\n # f.2) clearing the whole thing\n getattr(subfigs[1], clear_meth)()\n subfigs = [fig.add_subfigure(gs[i]) for i in [0, 1]]\n subaxes = [sfig.add_subplot(111) for sfig in subfigs]\n assert all(ax in fig.axes for ax in subaxes)\n assert all(sfig in fig.subfigs for sfig in subfigs)\n getattr(fig, clear_meth)()\n assert fig.subfigs == []\n assert fig.axes == []\n\n\ndef test_clf_not_redefined():\n for klass in FigureBase.__subclasses__():\n # check that subclasses do not get redefined in our Figure subclasses\n assert 'clf' not in klass.__dict__\n\n\n@mpl.style.context('mpl20')\ndef test_picking_does_not_stale():\n fig, ax = plt.subplots()\n ax.scatter([0], [0], [1000], picker=True)\n fig.canvas.draw()\n assert not fig.stale\n\n mouse_event = SimpleNamespace(x=ax.bbox.x0 + ax.bbox.width / 2,\n y=ax.bbox.y0 + ax.bbox.height / 2,\n inaxes=ax, guiEvent=None)\n fig.pick(mouse_event)\n assert not fig.stale\n\n\ndef test_add_subplot_twotuple():\n fig = plt.figure()\n ax1 = fig.add_subplot(3, 2, (3, 5))\n assert ax1.get_subplotspec().rowspan == range(1, 3)\n assert ax1.get_subplotspec().colspan == range(0, 1)\n ax2 = fig.add_subplot(3, 2, (4, 6))\n assert ax2.get_subplotspec().rowspan == range(1, 3)\n assert ax2.get_subplotspec().colspan == range(1, 2)\n ax3 = fig.add_subplot(3, 2, (3, 6))\n assert ax3.get_subplotspec().rowspan == range(1, 3)\n assert ax3.get_subplotspec().colspan == range(0, 2)\n ax4 = fig.add_subplot(3, 2, (4, 5))\n assert ax4.get_subplotspec().rowspan == range(1, 3)\n assert ax4.get_subplotspec().colspan == range(0, 2)\n with pytest.raises(IndexError):\n fig.add_subplot(3, 2, (6, 3))\n\n\n@image_comparison(['tightbbox_box_aspect.svg'], style='mpl20',\n savefig_kwarg={'bbox_inches': 'tight',\n 'facecolor': 'teal'},\n remove_text=True)\ndef test_tightbbox_box_aspect():\n fig = plt.figure()\n gs = fig.add_gridspec(1, 2)\n ax1 = fig.add_subplot(gs[0, 0])\n ax2 = fig.add_subplot(gs[0, 1], projection='3d')\n ax1.set_box_aspect(.5)\n ax2.set_box_aspect((2, 1, 1))\n\n\n@check_figures_equal(extensions=["svg", "pdf", "eps", "png"])\ndef test_animated_with_canvas_change(fig_test, fig_ref):\n ax_ref = fig_ref.subplots()\n ax_ref.plot(range(5))\n\n ax_test = fig_test.subplots()\n ax_test.plot(range(5), animated=True)\n\n\nclass TestSubplotMosaic:\n @check_figures_equal(extensions=["png"])\n @pytest.mark.parametrize(\n "x", [\n [["A", "A", "B"], ["C", "D", "B"]],\n [[1, 1, 2], [3, 4, 2]],\n (("A", "A", "B"), ("C", "D", "B")),\n ((1, 1, 2), (3, 4, 2))\n ]\n )\n def test_basic(self, fig_test, fig_ref, x):\n grid_axes = fig_test.subplot_mosaic(x)\n\n for k, ax in grid_axes.items():\n ax.set_title(k)\n\n labels = sorted(np.unique(x))\n\n assert len(labels) == len(grid_axes)\n\n gs = fig_ref.add_gridspec(2, 3)\n axA = fig_ref.add_subplot(gs[:1, :2])\n axA.set_title(labels[0])\n\n axB = fig_ref.add_subplot(gs[:, 2])\n axB.set_title(labels[1])\n\n axC = fig_ref.add_subplot(gs[1, 0])\n axC.set_title(labels[2])\n\n axD = fig_ref.add_subplot(gs[1, 1])\n axD.set_title(labels[3])\n\n @check_figures_equal(extensions=["png"])\n def test_all_nested(self, fig_test, fig_ref):\n x = [["A", "B"], ["C", "D"]]\n y = [["E", "F"], ["G", "H"]]\n\n fig_ref.set_layout_engine("constrained")\n fig_test.set_layout_engine("constrained")\n\n grid_axes = fig_test.subplot_mosaic([[x, y]])\n for ax in grid_axes.values():\n ax.set_title(ax.get_label())\n\n gs = fig_ref.add_gridspec(1, 2)\n gs_left = gs[0, 0].subgridspec(2, 2)\n for j, r in enumerate(x):\n for k, label in enumerate(r):\n fig_ref.add_subplot(gs_left[j, k]).set_title(label)\n\n gs_right = gs[0, 1].subgridspec(2, 2)\n for j, r in enumerate(y):\n for k, label in enumerate(r):\n fig_ref.add_subplot(gs_right[j, k]).set_title(label)\n\n @check_figures_equal(extensions=["png"])\n def test_nested(self, fig_test, fig_ref):\n\n fig_ref.set_layout_engine("constrained")\n fig_test.set_layout_engine("constrained")\n\n x = [["A", "B"], ["C", "D"]]\n\n y = [["F"], [x]]\n\n grid_axes = fig_test.subplot_mosaic(y)\n\n for k, ax in grid_axes.items():\n ax.set_title(k)\n\n gs = fig_ref.add_gridspec(2, 1)\n\n gs_n = gs[1, 0].subgridspec(2, 2)\n\n axA = fig_ref.add_subplot(gs_n[0, 0])\n axA.set_title("A")\n\n axB = fig_ref.add_subplot(gs_n[0, 1])\n axB.set_title("B")\n\n axC = fig_ref.add_subplot(gs_n[1, 0])\n axC.set_title("C")\n\n axD = fig_ref.add_subplot(gs_n[1, 1])\n axD.set_title("D")\n\n axF = fig_ref.add_subplot(gs[0, 0])\n axF.set_title("F")\n\n @check_figures_equal(extensions=["png"])\n def test_nested_tuple(self, fig_test, fig_ref):\n x = [["A", "B", "B"], ["C", "C", "D"]]\n xt = (("A", "B", "B"), ("C", "C", "D"))\n\n fig_ref.subplot_mosaic([["F"], [x]])\n fig_test.subplot_mosaic([["F"], [xt]])\n\n def test_nested_width_ratios(self):\n x = [["A", [["B"],\n ["C"]]]]\n width_ratios = [2, 1]\n\n fig, axd = plt.subplot_mosaic(x, width_ratios=width_ratios)\n\n assert axd["A"].get_gridspec().get_width_ratios() == width_ratios\n assert axd["B"].get_gridspec().get_width_ratios() != width_ratios\n\n def test_nested_height_ratios(self):\n x = [["A", [["B"],\n ["C"]]], ["D", "D"]]\n height_ratios = [1, 2]\n\n fig, axd = plt.subplot_mosaic(x, height_ratios=height_ratios)\n\n assert axd["D"].get_gridspec().get_height_ratios() == height_ratios\n assert axd["B"].get_gridspec().get_height_ratios() != height_ratios\n\n @check_figures_equal(extensions=["png"])\n @pytest.mark.parametrize(\n "x, empty_sentinel",\n [\n ([["A", None], [None, "B"]], None),\n ([["A", "."], [".", "B"]], "SKIP"),\n ([["A", 0], [0, "B"]], 0),\n ([[1, None], [None, 2]], None),\n ([[1, "."], [".", 2]], "SKIP"),\n ([[1, 0], [0, 2]], 0),\n ],\n )\n def test_empty(self, fig_test, fig_ref, x, empty_sentinel):\n if empty_sentinel != "SKIP":\n kwargs = {"empty_sentinel": empty_sentinel}\n else:\n kwargs = {}\n grid_axes = fig_test.subplot_mosaic(x, **kwargs)\n\n for k, ax in grid_axes.items():\n ax.set_title(k)\n\n labels = sorted(\n {name for row in x for name in row} - {empty_sentinel, "."}\n )\n\n assert len(labels) == len(grid_axes)\n\n gs = fig_ref.add_gridspec(2, 2)\n axA = fig_ref.add_subplot(gs[0, 0])\n axA.set_title(labels[0])\n\n axB = fig_ref.add_subplot(gs[1, 1])\n axB.set_title(labels[1])\n\n def test_fail_list_of_str(self):\n with pytest.raises(ValueError, match='must be 2D'):\n plt.subplot_mosaic(['foo', 'bar'])\n with pytest.raises(ValueError, match='must be 2D'):\n plt.subplot_mosaic(['foo'])\n with pytest.raises(ValueError, match='must be 2D'):\n plt.subplot_mosaic([['foo', ('bar',)]])\n with pytest.raises(ValueError, match='must be 2D'):\n plt.subplot_mosaic([['a', 'b'], [('a', 'b'), 'c']])\n\n @check_figures_equal(extensions=["png"])\n @pytest.mark.parametrize("subplot_kw", [{}, {"projection": "polar"}, None])\n def test_subplot_kw(self, fig_test, fig_ref, subplot_kw):\n x = [[1, 2]]\n grid_axes = fig_test.subplot_mosaic(x, subplot_kw=subplot_kw)\n subplot_kw = subplot_kw or {}\n\n gs = fig_ref.add_gridspec(1, 2)\n axA = fig_ref.add_subplot(gs[0, 0], **subplot_kw)\n\n axB = fig_ref.add_subplot(gs[0, 1], **subplot_kw)\n\n @check_figures_equal(extensions=["png"])\n @pytest.mark.parametrize("multi_value", ['BC', tuple('BC')])\n def test_per_subplot_kw(self, fig_test, fig_ref, multi_value):\n x = 'AB;CD'\n grid_axes = fig_test.subplot_mosaic(\n x,\n subplot_kw={'facecolor': 'red'},\n per_subplot_kw={\n 'D': {'facecolor': 'blue'},\n multi_value: {'facecolor': 'green'},\n }\n )\n\n gs = fig_ref.add_gridspec(2, 2)\n for color, spec in zip(['red', 'green', 'green', 'blue'], gs):\n fig_ref.add_subplot(spec, facecolor=color)\n\n def test_string_parser(self):\n normalize = Figure._normalize_grid_string\n\n assert normalize('ABC') == [['A', 'B', 'C']]\n assert normalize('AB;CC') == [['A', 'B'], ['C', 'C']]\n assert normalize('AB;CC;DE') == [['A', 'B'], ['C', 'C'], ['D', 'E']]\n assert normalize("""\n ABC\n """) == [['A', 'B', 'C']]\n assert normalize("""\n AB\n CC\n """) == [['A', 'B'], ['C', 'C']]\n assert normalize("""\n AB\n CC\n DE\n """) == [['A', 'B'], ['C', 'C'], ['D', 'E']]\n\n def test_per_subplot_kw_expander(self):\n normalize = Figure._norm_per_subplot_kw\n assert normalize({"A": {}, "B": {}}) == {"A": {}, "B": {}}\n assert normalize({("A", "B"): {}}) == {"A": {}, "B": {}}\n with pytest.raises(\n ValueError, match=f'The key {"B"!r} appears multiple times'\n ):\n normalize({("A", "B"): {}, "B": {}})\n with pytest.raises(\n ValueError, match=f'The key {"B"!r} appears multiple times'\n ):\n normalize({"B": {}, ("A", "B"): {}})\n\n def test_extra_per_subplot_kw(self):\n with pytest.raises(\n ValueError, match=f'The keys {set("B")!r} are in'\n ):\n Figure().subplot_mosaic("A", per_subplot_kw={"B": {}})\n\n @check_figures_equal(extensions=["png"])\n @pytest.mark.parametrize("str_pattern",\n ["AAA\nBBB", "\nAAA\nBBB\n", "ABC\nDEF"]\n )\n def test_single_str_input(self, fig_test, fig_ref, str_pattern):\n grid_axes = fig_test.subplot_mosaic(str_pattern)\n\n grid_axes = fig_ref.subplot_mosaic(\n [list(ln) for ln in str_pattern.strip().split("\n")]\n )\n\n @pytest.mark.parametrize(\n "x,match",\n [\n (\n [["A", "."], [".", "A"]],\n (\n "(?m)we found that the label .A. specifies a "\n + "non-rectangular or non-contiguous area."\n ),\n ),\n (\n [["A", "B"], [None, [["A", "B"], ["C", "D"]]]],\n "There are duplicate keys .* between the outer layout",\n ),\n ("AAA\nc\nBBB", "All of the rows must be the same length"),\n (\n [["A", [["B", "C"], ["D"]]], ["E", "E"]],\n "All of the rows must be the same length",\n ),\n ],\n )\n def test_fail(self, x, match):\n fig = plt.figure()\n with pytest.raises(ValueError, match=match):\n fig.subplot_mosaic(x)\n\n @check_figures_equal(extensions=["png"])\n def test_hashable_keys(self, fig_test, fig_ref):\n fig_test.subplot_mosaic([[object(), object()]])\n fig_ref.subplot_mosaic([["A", "B"]])\n\n @pytest.mark.parametrize('str_pattern',\n ['abc', 'cab', 'bca', 'cba', 'acb', 'bac'])\n def test_user_order(self, str_pattern):\n fig = plt.figure()\n ax_dict = fig.subplot_mosaic(str_pattern)\n assert list(str_pattern) == list(ax_dict)\n assert list(fig.axes) == list(ax_dict.values())\n\n def test_nested_user_order(self):\n layout = [\n ["A", [["B", "C"],\n ["D", "E"]]],\n ["F", "G"],\n [".", [["H", [["I"],\n ["."]]]]]\n ]\n\n fig = plt.figure()\n ax_dict = fig.subplot_mosaic(layout)\n assert list(ax_dict) == list("ABCDEFGHI")\n assert list(fig.axes) == list(ax_dict.values())\n\n def test_share_all(self):\n layout = [\n ["A", [["B", "C"],\n ["D", "E"]]],\n ["F", "G"],\n [".", [["H", [["I"],\n ["."]]]]]\n ]\n fig = plt.figure()\n ax_dict = fig.subplot_mosaic(layout, sharex=True, sharey=True)\n ax_dict["A"].set(xscale="log", yscale="logit")\n assert all(ax.get_xscale() == "log" and ax.get_yscale() == "logit"\n for ax in ax_dict.values())\n\n\ndef test_reused_gridspec():\n """Test that these all use the same gridspec"""\n fig = plt.figure()\n ax1 = fig.add_subplot(3, 2, (3, 5))\n ax2 = fig.add_subplot(3, 2, 4)\n ax3 = plt.subplot2grid((3, 2), (2, 1), colspan=2, fig=fig)\n\n gs1 = ax1.get_subplotspec().get_gridspec()\n gs2 = ax2.get_subplotspec().get_gridspec()\n gs3 = ax3.get_subplotspec().get_gridspec()\n\n assert gs1 == gs2\n assert gs1 == gs3\n\n\n@image_comparison(['test_subfigure.png'], style='mpl20',\n savefig_kwarg={'facecolor': 'teal'})\ndef test_subfigure():\n np.random.seed(19680801)\n fig = plt.figure(layout='constrained')\n sub = fig.subfigures(1, 2)\n\n axs = sub[0].subplots(2, 2)\n for ax in axs.flat:\n pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2, vmax=2)\n sub[0].colorbar(pc, ax=axs)\n sub[0].suptitle('Left Side')\n sub[0].set_facecolor('white')\n\n axs = sub[1].subplots(1, 3)\n for ax in axs.flat:\n pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2, vmax=2)\n sub[1].colorbar(pc, ax=axs, location='bottom')\n sub[1].suptitle('Right Side')\n sub[1].set_facecolor('white')\n\n fig.suptitle('Figure suptitle', fontsize='xx-large')\n\n # below tests for the draw zorder of subfigures.\n leg = fig.legend(handles=[plt.Line2D([0], [0], label='Line{}'.format(i))\n for i in range(5)], loc='center')\n sub[0].set_zorder(leg.get_zorder() - 1)\n sub[1].set_zorder(leg.get_zorder() + 1)\n\n\ndef test_subfigure_tightbbox():\n # test that we can get the tightbbox with a subfigure...\n fig = plt.figure(layout='constrained')\n sub = fig.subfigures(1, 2)\n\n np.testing.assert_allclose(\n fig.get_tightbbox(fig.canvas.get_renderer()).width,\n 8.0)\n\n\ndef test_subfigure_dpi():\n fig = plt.figure(dpi=100)\n sub_fig = fig.subfigures()\n assert sub_fig.get_dpi() == fig.get_dpi()\n\n sub_fig.set_dpi(200)\n assert sub_fig.get_dpi() == 200\n assert fig.get_dpi() == 200\n\n\n@image_comparison(['test_subfigure_ss.png'], style='mpl20',\n savefig_kwarg={'facecolor': 'teal'}, tol=0.02)\ndef test_subfigure_ss():\n # test assigning the subfigure via subplotspec\n np.random.seed(19680801)\n fig = plt.figure(layout='constrained')\n gs = fig.add_gridspec(1, 2)\n\n sub = fig.add_subfigure(gs[0], facecolor='pink')\n\n axs = sub.subplots(2, 2)\n for ax in axs.flat:\n pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2, vmax=2)\n sub.colorbar(pc, ax=axs)\n sub.suptitle('Left Side')\n\n ax = fig.add_subplot(gs[1])\n ax.plot(np.arange(20))\n ax.set_title('Axes')\n\n fig.suptitle('Figure suptitle', fontsize='xx-large')\n\n\n@image_comparison(['test_subfigure_double.png'], style='mpl20',\n savefig_kwarg={'facecolor': 'teal'})\ndef test_subfigure_double():\n # test assigning the subfigure via subplotspec\n np.random.seed(19680801)\n\n fig = plt.figure(layout='constrained', figsize=(10, 8))\n\n fig.suptitle('fig')\n\n subfigs = fig.subfigures(1, 2, wspace=0.07)\n\n subfigs[0].set_facecolor('coral')\n subfigs[0].suptitle('subfigs[0]')\n\n subfigs[1].set_facecolor('coral')\n subfigs[1].suptitle('subfigs[1]')\n\n subfigsnest = subfigs[0].subfigures(2, 1, height_ratios=[1, 1.4])\n subfigsnest[0].suptitle('subfigsnest[0]')\n subfigsnest[0].set_facecolor('r')\n axsnest0 = subfigsnest[0].subplots(1, 2, sharey=True)\n for ax in axsnest0:\n fontsize = 12\n pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2.5, vmax=2.5)\n ax.set_xlabel('x-label', fontsize=fontsize)\n ax.set_ylabel('y-label', fontsize=fontsize)\n ax.set_title('Title', fontsize=fontsize)\n subfigsnest[0].colorbar(pc, ax=axsnest0)\n\n subfigsnest[1].suptitle('subfigsnest[1]')\n subfigsnest[1].set_facecolor('g')\n axsnest1 = subfigsnest[1].subplots(3, 1, sharex=True)\n for nn, ax in enumerate(axsnest1):\n ax.set_ylabel(f'ylabel{nn}')\n subfigsnest[1].supxlabel('supxlabel')\n subfigsnest[1].supylabel('supylabel')\n\n axsRight = subfigs[1].subplots(2, 2)\n\n\ndef test_subfigure_spanning():\n # test that subfigures get laid out properly...\n fig = plt.figure(constrained_layout=True)\n gs = fig.add_gridspec(3, 3)\n sub_figs = [\n fig.add_subfigure(gs[0, 0]),\n fig.add_subfigure(gs[0:2, 1]),\n fig.add_subfigure(gs[2, 1:3]),\n fig.add_subfigure(gs[0:, 1:])\n ]\n\n w = 640\n h = 480\n np.testing.assert_allclose(sub_figs[0].bbox.min, [0., h * 2/3])\n np.testing.assert_allclose(sub_figs[0].bbox.max, [w / 3, h])\n\n np.testing.assert_allclose(sub_figs[1].bbox.min, [w / 3, h / 3])\n np.testing.assert_allclose(sub_figs[1].bbox.max, [w * 2/3, h])\n\n np.testing.assert_allclose(sub_figs[2].bbox.min, [w / 3, 0])\n np.testing.assert_allclose(sub_figs[2].bbox.max, [w, h / 3])\n\n # check here that slicing actually works. Last sub_fig\n # with open slices failed, but only on draw...\n for i in range(4):\n sub_figs[i].add_subplot()\n fig.draw_without_rendering()\n\n\n@mpl.style.context('mpl20')\ndef test_subfigure_ticks():\n # This tests a tick-spacing error that only seems applicable\n # when the subfigures are saved to file. It is very hard to replicate\n fig = plt.figure(constrained_layout=True, figsize=(10, 3))\n # create left/right subfigs nested in bottom subfig\n (subfig_bl, subfig_br) = fig.subfigures(1, 2, wspace=0.01,\n width_ratios=[7, 2])\n\n # put ax1-ax3 in gridspec of bottom-left subfig\n gs = subfig_bl.add_gridspec(nrows=1, ncols=14)\n\n ax1 = subfig_bl.add_subplot(gs[0, :1])\n ax1.scatter(x=[-56.46881504821776, 24.179891162109396], y=[1500, 3600])\n\n ax2 = subfig_bl.add_subplot(gs[0, 1:3], sharey=ax1)\n ax2.scatter(x=[-126.5357270050049, 94.68456736755368], y=[1500, 3600])\n ax3 = subfig_bl.add_subplot(gs[0, 3:14], sharey=ax1)\n\n fig.dpi = 120\n fig.draw_without_rendering()\n ticks120 = ax2.get_xticks()\n fig.dpi = 300\n fig.draw_without_rendering()\n ticks300 = ax2.get_xticks()\n np.testing.assert_allclose(ticks120, ticks300)\n\n\n@image_comparison(['test_subfigure_scatter_size.png'], style='mpl20',\n remove_text=True)\ndef test_subfigure_scatter_size():\n # markers in the left- and right-most subplots should be the same\n fig = plt.figure()\n gs = fig.add_gridspec(1, 2)\n ax0 = fig.add_subplot(gs[1])\n ax0.scatter([1, 2, 3], [1, 2, 3], s=30, marker='s')\n ax0.scatter([3, 4, 5], [1, 2, 3], s=[20, 30, 40], marker='s')\n\n sfig = fig.add_subfigure(gs[0])\n axs = sfig.subplots(1, 2)\n for ax in [ax0, axs[0]]:\n ax.scatter([1, 2, 3], [1, 2, 3], s=30, marker='s', color='r')\n ax.scatter([3, 4, 5], [1, 2, 3], s=[20, 30, 40], marker='s', color='g')\n\n\ndef test_subfigure_pdf():\n fig = plt.figure(layout='constrained')\n sub_fig = fig.subfigures()\n ax = sub_fig.add_subplot(111)\n b = ax.bar(1, 1)\n ax.bar_label(b)\n buffer = io.BytesIO()\n fig.savefig(buffer, format='pdf')\n\n\ndef test_subfigures_wspace_hspace():\n sub_figs = plt.figure().subfigures(2, 3, hspace=0.5, wspace=1/6.)\n\n w = 640\n h = 480\n\n np.testing.assert_allclose(sub_figs[0, 0].bbox.min, [0., h * 0.6])\n np.testing.assert_allclose(sub_figs[0, 0].bbox.max, [w * 0.3, h])\n\n np.testing.assert_allclose(sub_figs[0, 1].bbox.min, [w * 0.35, h * 0.6])\n np.testing.assert_allclose(sub_figs[0, 1].bbox.max, [w * 0.65, h])\n\n np.testing.assert_allclose(sub_figs[0, 2].bbox.min, [w * 0.7, h * 0.6])\n np.testing.assert_allclose(sub_figs[0, 2].bbox.max, [w, h])\n\n np.testing.assert_allclose(sub_figs[1, 0].bbox.min, [0, 0])\n np.testing.assert_allclose(sub_figs[1, 0].bbox.max, [w * 0.3, h * 0.4])\n\n np.testing.assert_allclose(sub_figs[1, 1].bbox.min, [w * 0.35, 0])\n np.testing.assert_allclose(sub_figs[1, 1].bbox.max, [w * 0.65, h * 0.4])\n\n np.testing.assert_allclose(sub_figs[1, 2].bbox.min, [w * 0.7, 0])\n np.testing.assert_allclose(sub_figs[1, 2].bbox.max, [w, h * 0.4])\n\n\ndef test_subfigure_remove():\n fig = plt.figure()\n sfs = fig.subfigures(2, 2)\n sfs[1, 1].remove()\n assert len(fig.subfigs) == 3\n\n\ndef test_add_subplot_kwargs():\n # fig.add_subplot() always creates new axes, even if axes kwargs differ.\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax1 = fig.add_subplot(1, 1, 1)\n assert ax is not None\n assert ax1 is not ax\n plt.close()\n\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1, projection='polar')\n ax1 = fig.add_subplot(1, 1, 1, projection='polar')\n assert ax is not None\n assert ax1 is not ax\n plt.close()\n\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1, projection='polar')\n ax1 = fig.add_subplot(1, 1, 1)\n assert ax is not None\n assert ax1.name == 'rectilinear'\n assert ax1 is not ax\n plt.close()\n\n\ndef test_add_axes_kwargs():\n # fig.add_axes() always creates new axes, even if axes kwargs differ.\n fig = plt.figure()\n ax = fig.add_axes([0, 0, 1, 1])\n ax1 = fig.add_axes([0, 0, 1, 1])\n assert ax is not None\n assert ax1 is not ax\n plt.close()\n\n fig = plt.figure()\n ax = fig.add_axes([0, 0, 1, 1], projection='polar')\n ax1 = fig.add_axes([0, 0, 1, 1], projection='polar')\n assert ax is not None\n assert ax1 is not ax\n plt.close()\n\n fig = plt.figure()\n ax = fig.add_axes([0, 0, 1, 1], projection='polar')\n ax1 = fig.add_axes([0, 0, 1, 1])\n assert ax is not None\n assert ax1.name == 'rectilinear'\n assert ax1 is not ax\n plt.close()\n\n\ndef test_ginput(recwarn): # recwarn undoes warn filters at exit.\n warnings.filterwarnings("ignore", "cannot show the figure")\n fig, ax = plt.subplots()\n trans = ax.transData.transform\n\n def single_press():\n MouseEvent("button_press_event", fig.canvas, *trans((.1, .2)), 1)._process()\n\n Timer(.1, single_press).start()\n assert fig.ginput() == [(.1, .2)]\n\n def multi_presses():\n MouseEvent("button_press_event", fig.canvas, *trans((.1, .2)), 1)._process()\n KeyEvent("key_press_event", fig.canvas, "backspace")._process()\n MouseEvent("button_press_event", fig.canvas, *trans((.3, .4)), 1)._process()\n MouseEvent("button_press_event", fig.canvas, *trans((.5, .6)), 1)._process()\n MouseEvent("button_press_event", fig.canvas, *trans((0, 0)), 2)._process()\n\n Timer(.1, multi_presses).start()\n np.testing.assert_allclose(fig.ginput(3), [(.3, .4), (.5, .6)])\n\n\ndef test_waitforbuttonpress(recwarn): # recwarn undoes warn filters at exit.\n warnings.filterwarnings("ignore", "cannot show the figure")\n fig = plt.figure()\n assert fig.waitforbuttonpress(timeout=.1) is None\n Timer(.1, KeyEvent("key_press_event", fig.canvas, "z")._process).start()\n assert fig.waitforbuttonpress() is True\n Timer(.1, MouseEvent("button_press_event", fig.canvas, 0, 0, 1)._process).start()\n assert fig.waitforbuttonpress() is False\n\n\ndef test_kwargs_pass():\n fig = Figure(label='whole Figure')\n sub_fig = fig.subfigures(1, 1, label='sub figure')\n\n assert fig.get_label() == 'whole Figure'\n assert sub_fig.get_label() == 'sub figure'\n\n\n@check_figures_equal(extensions=["png"])\ndef test_rcparams(fig_test, fig_ref):\n fig_ref.supxlabel("xlabel", weight='bold', size=15)\n fig_ref.supylabel("ylabel", weight='bold', size=15)\n fig_ref.suptitle("Title", weight='light', size=20)\n with mpl.rc_context({'figure.labelweight': 'bold',\n 'figure.labelsize': 15,\n 'figure.titleweight': 'light',\n 'figure.titlesize': 20}):\n fig_test.supxlabel("xlabel")\n fig_test.supylabel("ylabel")\n fig_test.suptitle("Title")\n\n\ndef test_deepcopy():\n fig1, ax = plt.subplots()\n ax.plot([0, 1], [2, 3])\n ax.set_yscale('log')\n\n fig2 = copy.deepcopy(fig1)\n\n # Make sure it is a new object\n assert fig2.axes[0] is not ax\n # And that the axis scale got propagated\n assert fig2.axes[0].get_yscale() == 'log'\n # Update the deepcopy and check the original isn't modified\n fig2.axes[0].set_yscale('linear')\n assert ax.get_yscale() == 'log'\n\n # And test the limits of the axes don't get propagated\n ax.set_xlim(1e-1, 1e2)\n # Draw these to make sure limits are updated\n fig1.draw_without_rendering()\n fig2.draw_without_rendering()\n\n assert ax.get_xlim() == (1e-1, 1e2)\n assert fig2.axes[0].get_xlim() == (0, 1)\n\n\ndef test_unpickle_with_device_pixel_ratio():\n fig = Figure(dpi=42)\n fig.canvas._set_device_pixel_ratio(7)\n assert fig.dpi == 42*7\n fig2 = pickle.loads(pickle.dumps(fig))\n assert fig2.dpi == 42\n\n\ndef test_gridspec_no_mutate_input():\n gs = {'left': .1}\n gs_orig = dict(gs)\n plt.subplots(1, 2, width_ratios=[1, 2], gridspec_kw=gs)\n assert gs == gs_orig\n plt.subplot_mosaic('AB', width_ratios=[1, 2], gridspec_kw=gs)\n\n\n@pytest.mark.parametrize('fmt', ['eps', 'pdf', 'png', 'ps', 'svg', 'svgz'])\ndef test_savefig_metadata(fmt):\n Figure().savefig(io.BytesIO(), format=fmt, metadata={})\n\n\n@pytest.mark.parametrize('fmt', ['jpeg', 'jpg', 'tif', 'tiff', 'webp', "raw", "rgba"])\ndef test_savefig_metadata_error(fmt):\n with pytest.raises(ValueError, match="metadata not supported"):\n Figure().savefig(io.BytesIO(), format=fmt, metadata={})\n\n\ndef test_get_constrained_layout_pads():\n params = {'w_pad': 0.01, 'h_pad': 0.02, 'wspace': 0.03, 'hspace': 0.04}\n expected = tuple([*params.values()])\n fig = plt.figure(layout=mpl.layout_engine.ConstrainedLayoutEngine(**params))\n with pytest.warns(PendingDeprecationWarning, match="will be deprecated"):\n assert fig.get_constrained_layout_pads() == expected\n\n\ndef test_not_visible_figure():\n fig = Figure()\n\n buf = io.StringIO()\n fig.savefig(buf, format='svg')\n buf.seek(0)\n assert '<g ' in buf.read()\n\n fig.set_visible(False)\n buf = io.StringIO()\n fig.savefig(buf, format='svg')\n buf.seek(0)\n assert '<g ' not in buf.read()\n\n\ndef test_warn_colorbar_mismatch():\n fig1, ax1 = plt.subplots()\n fig2, (ax2_1, ax2_2) = plt.subplots(2)\n im = ax1.imshow([[1, 2], [3, 4]])\n\n fig1.colorbar(im) # should not warn\n with pytest.warns(UserWarning, match="different Figure"):\n fig2.colorbar(im)\n # warn mismatch even when the host figure is not inferred\n with pytest.warns(UserWarning, match="different Figure"):\n fig2.colorbar(im, ax=ax1)\n with pytest.warns(UserWarning, match="different Figure"):\n fig2.colorbar(im, ax=ax2_1)\n with pytest.warns(UserWarning, match="different Figure"):\n fig2.colorbar(im, cax=ax2_2)\n\n # edge case: only compare top level artist in case of subfigure\n fig3 = plt.figure()\n fig4 = plt.figure()\n subfig3_1 = fig3.subfigures()\n subfig3_2 = fig3.subfigures()\n subfig4_1 = fig4.subfigures()\n ax3_1 = subfig3_1.subplots()\n ax3_2 = subfig3_1.subplots()\n ax4_1 = subfig4_1.subplots()\n im3_1 = ax3_1.imshow([[1, 2], [3, 4]])\n im3_2 = ax3_2.imshow([[1, 2], [3, 4]])\n im4_1 = ax4_1.imshow([[1, 2], [3, 4]])\n\n fig3.colorbar(im3_1) # should not warn\n subfig3_1.colorbar(im3_1) # should not warn\n subfig3_1.colorbar(im3_2) # should not warn\n with pytest.warns(UserWarning, match="different Figure"):\n subfig3_1.colorbar(im4_1)\n\n\ndef test_set_figure():\n fig = plt.figure()\n sfig1 = fig.subfigures()\n sfig2 = sfig1.subfigures()\n\n for f in fig, sfig1, sfig2:\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n f.set_figure(fig)\n\n with pytest.raises(ValueError, match="cannot be changed"):\n sfig2.set_figure(sfig1)\n\n with pytest.raises(ValueError, match="cannot be changed"):\n sfig1.set_figure(plt.figure())\n\n\ndef test_subfigure_row_order():\n # Test that subfigures are drawn in row-major order.\n fig = plt.figure()\n sf_arr = fig.subfigures(4, 3)\n for a, b in zip(sf_arr.ravel(), fig.subfigs):\n assert a is b\n\n\ndef test_subfigure_stale_propagation():\n fig = plt.figure()\n\n fig.draw_without_rendering()\n assert not fig.stale\n\n sfig1 = fig.subfigures()\n assert fig.stale\n\n fig.draw_without_rendering()\n assert not fig.stale\n assert not sfig1.stale\n\n sfig2 = sfig1.subfigures()\n assert fig.stale\n assert sfig1.stale\n\n fig.draw_without_rendering()\n assert not fig.stale\n assert not sfig1.stale\n assert not sfig2.stale\n\n sfig2.stale = True\n assert sfig1.stale\n assert fig.stale\n | .venv\Lib\site-packages\matplotlib\tests\test_figure.py | test_figure.py | Python | 60,289 | 0.75 | 0.107084 | 0.064227 | python-kit | 802 | 2024-06-01T23:12:06.610462 | GPL-3.0 | true | 5621cc146daf8c4b98f7ef90bc83b5d2 |
import pytest\n\nfrom matplotlib.font_manager import FontProperties\n\n\n# Attributes on FontProperties object to check for consistency\nkeys = [\n "get_family",\n "get_style",\n "get_variant",\n "get_weight",\n "get_size",\n ]\n\n\ndef test_fontconfig_pattern():\n """Test converting a FontProperties to string then back."""\n\n # Defaults\n test = "defaults "\n f1 = FontProperties()\n s = str(f1)\n\n f2 = FontProperties(s)\n for k in keys:\n assert getattr(f1, k)() == getattr(f2, k)(), test + k\n\n # Basic inputs\n test = "basic "\n f1 = FontProperties(family="serif", size=20, style="italic")\n s = str(f1)\n\n f2 = FontProperties(s)\n for k in keys:\n assert getattr(f1, k)() == getattr(f2, k)(), test + k\n\n # Full set of inputs.\n test = "full "\n f1 = FontProperties(family="sans-serif", size=24, weight="bold",\n style="oblique", variant="small-caps",\n stretch="expanded")\n s = str(f1)\n\n f2 = FontProperties(s)\n for k in keys:\n assert getattr(f1, k)() == getattr(f2, k)(), test + k\n\n\ndef test_fontconfig_str():\n """Test FontProperties string conversions for correctness."""\n\n # Known good strings taken from actual font config specs on a linux box\n # and modified for MPL defaults.\n\n # Default values found by inspection.\n test = "defaults "\n s = ("sans\\-serif:style=normal:variant=normal:weight=normal"\n ":stretch=normal:size=12.0")\n font = FontProperties(s)\n right = FontProperties()\n for k in keys:\n assert getattr(font, k)() == getattr(right, k)(), test + k\n\n test = "full "\n s = ("serif-24:style=oblique:variant=small-caps:weight=bold"\n ":stretch=expanded")\n font = FontProperties(s)\n right = FontProperties(family="serif", size=24, weight="bold",\n style="oblique", variant="small-caps",\n stretch="expanded")\n for k in keys:\n assert getattr(font, k)() == getattr(right, k)(), test + k\n\n\ndef test_fontconfig_unknown_constant():\n with pytest.raises(ValueError, match="ParseException"):\n FontProperties(":unknown")\n | .venv\Lib\site-packages\matplotlib\tests\test_fontconfig_pattern.py | test_fontconfig_pattern.py | Python | 2,168 | 0.95 | 0.142857 | 0.118644 | node-utils | 900 | 2025-02-02T05:36:57.966837 | Apache-2.0 | true | 85a83ff1c9362bc06b7f318cd1f2521f |
from io import BytesIO, StringIO\nimport gc\nimport multiprocessing\nimport os\nfrom pathlib import Path\nfrom PIL import Image\nimport shutil\nimport sys\nimport warnings\n\nimport numpy as np\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib.font_manager import (\n findfont, findSystemFonts, FontEntry, FontProperties, fontManager,\n json_dump, json_load, get_font, is_opentype_cff_font,\n MSUserFontDirectories, _get_fontconfig_fonts, ttfFontProperty)\nfrom matplotlib import cbook, ft2font, pyplot as plt, rc_context, figure as mfigure\nfrom matplotlib.testing import subprocess_run_helper, subprocess_run_for_testing\n\n\nhas_fclist = shutil.which('fc-list') is not None\n\n\ndef test_font_priority():\n with rc_context(rc={\n 'font.sans-serif':\n ['cmmi10', 'Bitstream Vera Sans']}):\n fontfile = findfont(FontProperties(family=["sans-serif"]))\n assert Path(fontfile).name == 'cmmi10.ttf'\n\n # Smoketest get_charmap, which isn't used internally anymore\n font = get_font(fontfile)\n cmap = font.get_charmap()\n assert len(cmap) == 131\n assert cmap[8729] == 30\n\n\ndef test_score_weight():\n assert 0 == fontManager.score_weight("regular", "regular")\n assert 0 == fontManager.score_weight("bold", "bold")\n assert (0 < fontManager.score_weight(400, 400) <\n fontManager.score_weight("normal", "bold"))\n assert (0 < fontManager.score_weight("normal", "regular") <\n fontManager.score_weight("normal", "bold"))\n assert (fontManager.score_weight("normal", "regular") ==\n fontManager.score_weight(400, 400))\n\n\ndef test_json_serialization(tmp_path):\n # Can't open a NamedTemporaryFile twice on Windows, so use a temporary\n # directory instead.\n json_dump(fontManager, tmp_path / "fontlist.json")\n copy = json_load(tmp_path / "fontlist.json")\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', 'findfont: Font family.*not found')\n for prop in ({'family': 'STIXGeneral'},\n {'family': 'Bitstream Vera Sans', 'weight': 700},\n {'family': 'no such font family'}):\n fp = FontProperties(**prop)\n assert (fontManager.findfont(fp, rebuild_if_missing=False) ==\n copy.findfont(fp, rebuild_if_missing=False))\n\n\ndef test_otf():\n fname = '/usr/share/fonts/opentype/freefont/FreeMono.otf'\n if Path(fname).exists():\n assert is_opentype_cff_font(fname)\n for f in fontManager.ttflist:\n if 'otf' in f.fname:\n with open(f.fname, 'rb') as fd:\n res = fd.read(4) == b'OTTO'\n assert res == is_opentype_cff_font(f.fname)\n\n\n@pytest.mark.skipif(sys.platform == "win32" or not has_fclist,\n reason='no fontconfig installed')\ndef test_get_fontconfig_fonts():\n assert len(_get_fontconfig_fonts()) > 1\n\n\n@pytest.mark.parametrize('factor', [2, 4, 6, 8])\ndef test_hinting_factor(factor):\n font = findfont(FontProperties(family=["sans-serif"]))\n\n font1 = get_font(font, hinting_factor=1)\n font1.clear()\n font1.set_size(12, 100)\n font1.set_text('abc')\n expected = font1.get_width_height()\n\n hinted_font = get_font(font, hinting_factor=factor)\n hinted_font.clear()\n hinted_font.set_size(12, 100)\n hinted_font.set_text('abc')\n # Check that hinting only changes text layout by a small (10%) amount.\n np.testing.assert_allclose(hinted_font.get_width_height(), expected,\n rtol=0.1)\n\n\ndef test_utf16m_sfnt():\n try:\n # seguisbi = Microsoft Segoe UI Semibold\n entry = next(entry for entry in fontManager.ttflist\n if Path(entry.fname).name == "seguisbi.ttf")\n except StopIteration:\n pytest.skip("Couldn't find seguisbi.ttf font to test against.")\n else:\n # Check that we successfully read "semibold" from the font's sfnt table\n # and set its weight accordingly.\n assert entry.weight == 600\n\n\ndef test_find_ttc():\n fp = FontProperties(family=["WenQuanYi Zen Hei"])\n if Path(findfont(fp)).name != "wqy-zenhei.ttc":\n pytest.skip("Font wqy-zenhei.ttc may be missing")\n fig, ax = plt.subplots()\n ax.text(.5, .5, "\N{KANGXI RADICAL DRAGON}", fontproperties=fp)\n for fmt in ["raw", "svg", "pdf", "ps"]:\n fig.savefig(BytesIO(), format=fmt)\n\n\ndef test_find_noto():\n fp = FontProperties(family=["Noto Sans CJK SC", "Noto Sans CJK JP"])\n name = Path(findfont(fp)).name\n if name not in ("NotoSansCJKsc-Regular.otf", "NotoSansCJK-Regular.ttc"):\n pytest.skip(f"Noto Sans CJK SC font may be missing (found {name})")\n\n fig, ax = plt.subplots()\n ax.text(0.5, 0.5, 'Hello, 你好', fontproperties=fp)\n for fmt in ["raw", "svg", "pdf", "ps"]:\n fig.savefig(BytesIO(), format=fmt)\n\n\ndef test_find_invalid(tmp_path):\n\n with pytest.raises(FileNotFoundError):\n get_font(tmp_path / 'non-existent-font-name.ttf')\n\n with pytest.raises(FileNotFoundError):\n get_font(str(tmp_path / 'non-existent-font-name.ttf'))\n\n with pytest.raises(FileNotFoundError):\n get_font(bytes(tmp_path / 'non-existent-font-name.ttf'))\n\n # Not really public, but get_font doesn't expose non-filename constructor.\n from matplotlib.ft2font import FT2Font\n with pytest.raises(TypeError, match='font file or a binary-mode file'):\n FT2Font(StringIO()) # type: ignore[arg-type]\n\n\n@pytest.mark.skipif(sys.platform != 'linux' or not has_fclist,\n reason='only Linux with fontconfig installed')\ndef test_user_fonts_linux(tmpdir, monkeypatch):\n font_test_file = 'mpltest.ttf'\n\n # Precondition: the test font should not be available\n fonts = findSystemFonts()\n if any(font_test_file in font for font in fonts):\n pytest.skip(f'{font_test_file} already exists in system fonts')\n\n # Prepare a temporary user font directory\n user_fonts_dir = tmpdir.join('fonts')\n user_fonts_dir.ensure(dir=True)\n shutil.copyfile(Path(__file__).parent / font_test_file,\n user_fonts_dir.join(font_test_file))\n\n with monkeypatch.context() as m:\n m.setenv('XDG_DATA_HOME', str(tmpdir))\n _get_fontconfig_fonts.cache_clear()\n # Now, the font should be available\n fonts = findSystemFonts()\n assert any(font_test_file in font for font in fonts)\n\n # Make sure the temporary directory is no longer cached.\n _get_fontconfig_fonts.cache_clear()\n\n\ndef test_addfont_as_path():\n """Smoke test that addfont() accepts pathlib.Path."""\n font_test_file = 'mpltest.ttf'\n path = Path(__file__).parent / font_test_file\n try:\n fontManager.addfont(path)\n added, = (font for font in fontManager.ttflist\n if font.fname.endswith(font_test_file))\n fontManager.ttflist.remove(added)\n finally:\n to_remove = [font for font in fontManager.ttflist\n if font.fname.endswith(font_test_file)]\n for font in to_remove:\n fontManager.ttflist.remove(font)\n\n\n@pytest.mark.skipif(sys.platform != 'win32', reason='Windows only')\ndef test_user_fonts_win32():\n if not (os.environ.get('APPVEYOR') or os.environ.get('TF_BUILD')):\n pytest.xfail("This test should only run on CI (appveyor or azure) "\n "as the developer's font directory should remain "\n "unchanged.")\n pytest.xfail("We need to update the registry for this test to work")\n font_test_file = 'mpltest.ttf'\n\n # Precondition: the test font should not be available\n fonts = findSystemFonts()\n if any(font_test_file in font for font in fonts):\n pytest.skip(f'{font_test_file} already exists in system fonts')\n\n user_fonts_dir = MSUserFontDirectories[0]\n\n # Make sure that the user font directory exists (this is probably not the\n # case on Windows versions < 1809)\n os.makedirs(user_fonts_dir)\n\n # Copy the test font to the user font directory\n shutil.copy(Path(__file__).parent / font_test_file, user_fonts_dir)\n\n # Now, the font should be available\n fonts = findSystemFonts()\n assert any(font_test_file in font for font in fonts)\n\n\ndef _model_handler(_):\n fig, ax = plt.subplots()\n fig.savefig(BytesIO(), format="pdf")\n plt.close()\n\n\n@pytest.mark.skipif(not hasattr(os, "register_at_fork"),\n reason="Cannot register at_fork handlers")\ndef test_fork():\n _model_handler(0) # Make sure the font cache is filled.\n ctx = multiprocessing.get_context("fork")\n with ctx.Pool(processes=2) as pool:\n pool.map(_model_handler, range(2))\n\n\ndef test_missing_family(caplog):\n plt.rcParams["font.sans-serif"] = ["this-font-does-not-exist"]\n with caplog.at_level("WARNING"):\n findfont("sans")\n assert [rec.getMessage() for rec in caplog.records] == [\n "findfont: Font family ['sans'] not found. "\n "Falling back to DejaVu Sans.",\n "findfont: Generic family 'sans' not found because none of the "\n "following families were found: this-font-does-not-exist",\n ]\n\n\ndef _test_threading():\n import threading\n from matplotlib.ft2font import LoadFlags\n import matplotlib.font_manager as fm\n\n def loud_excepthook(args):\n raise RuntimeError("error in thread!")\n\n threading.excepthook = loud_excepthook\n\n N = 10\n b = threading.Barrier(N)\n\n def bad_idea(n):\n b.wait(timeout=5)\n for j in range(100):\n font = fm.get_font(fm.findfont("DejaVu Sans"))\n font.set_text(str(n), 0.0, flags=LoadFlags.NO_HINTING)\n\n threads = [\n threading.Thread(target=bad_idea, name=f"bad_thread_{j}", args=(j,))\n for j in range(N)\n ]\n\n for t in threads:\n t.start()\n\n for t in threads:\n t.join(timeout=9)\n if t.is_alive():\n raise RuntimeError("thread failed to join")\n\n\ndef test_fontcache_thread_safe():\n pytest.importorskip('threading')\n\n subprocess_run_helper(_test_threading, timeout=10)\n\n\ndef test_lockfilefailure(tmp_path):\n # The logic here:\n # 1. get a temp directory from pytest\n # 2. import matplotlib which makes sure it exists\n # 3. get the cache dir (where we check it is writable)\n # 4. make it not writable\n # 5. try to write into it via font manager\n proc = subprocess_run_for_testing(\n [\n sys.executable,\n "-c",\n "import matplotlib;"\n "import os;"\n "p = matplotlib.get_cachedir();"\n "os.chmod(p, 0o555);"\n "import matplotlib.font_manager;"\n ],\n env={**os.environ, 'MPLCONFIGDIR': str(tmp_path)},\n check=True\n )\n\n\ndef test_fontentry_dataclass():\n fontent = FontEntry(name='font-name')\n\n png = fontent._repr_png_()\n img = Image.open(BytesIO(png))\n assert img.width > 0\n assert img.height > 0\n\n html = fontent._repr_html_()\n assert html.startswith("<img src=\"data:image/png;base64")\n\n\ndef test_fontentry_dataclass_invalid_path():\n with pytest.raises(FileNotFoundError):\n fontent = FontEntry(fname='/random', name='font-name')\n fontent._repr_html_()\n\n\n@pytest.mark.skipif(sys.platform == 'win32', reason='Linux or OS only')\ndef test_get_font_names():\n paths_mpl = [cbook._get_data_path('fonts', subdir) for subdir in ['ttf']]\n fonts_mpl = findSystemFonts(paths_mpl, fontext='ttf')\n fonts_system = findSystemFonts(fontext='ttf')\n ttf_fonts = []\n for path in fonts_mpl + fonts_system:\n try:\n font = ft2font.FT2Font(path)\n prop = ttfFontProperty(font)\n ttf_fonts.append(prop.name)\n except Exception:\n pass\n available_fonts = sorted(list(set(ttf_fonts)))\n mpl_font_names = sorted(fontManager.get_font_names())\n assert set(available_fonts) == set(mpl_font_names)\n assert len(available_fonts) == len(mpl_font_names)\n assert available_fonts == mpl_font_names\n\n\ndef test_donot_cache_tracebacks():\n\n class SomeObject:\n pass\n\n def inner():\n x = SomeObject()\n fig = mfigure.Figure()\n ax = fig.subplots()\n fig.text(.5, .5, 'aardvark', family='doesnotexist')\n with BytesIO() as out:\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore')\n fig.savefig(out, format='raw')\n\n inner()\n\n for obj in gc.get_objects():\n if isinstance(obj, SomeObject):\n pytest.fail("object from inner stack still alive")\n\n\ndef test_fontproperties_init_deprecation():\n """\n Test the deprecated API of FontProperties.__init__.\n\n The deprecation does not change behavior, it only adds a deprecation warning\n via a decorator. Therefore, the purpose of this test is limited to check\n which calls do and do not issue deprecation warnings. Behavior is still\n tested via the existing regular tests.\n """\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n # multiple positional arguments\n FontProperties("Times", "italic")\n\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n # Mixed positional and keyword arguments\n FontProperties("Times", size=10)\n\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n # passing a family list positionally\n FontProperties(["Times"])\n\n # still accepted:\n FontProperties(family="Times", style="italic")\n FontProperties(family="Times")\n FontProperties("Times") # works as pattern and family\n FontProperties("serif-24:style=oblique:weight=bold") # pattern\n\n # also still accepted:\n # passing as pattern via family kwarg was not covered by the docs but\n # historically worked. This is left unchanged for now.\n # AFAICT, we cannot detect this: We can determine whether a string\n # works as pattern, but that doesn't help, because there are strings\n # that are both pattern and family. We would need to identify, whether\n # a string is *not* a valid family.\n # Since this case is not covered by docs, I've refrained from jumping\n # extra hoops to detect this possible API misuse.\n FontProperties(family="serif-24:style=oblique:weight=bold")\n | .venv\Lib\site-packages\matplotlib\tests\test_font_manager.py | test_font_manager.py | Python | 14,136 | 0.95 | 0.161369 | 0.11215 | vue-tools | 628 | 2025-03-25T13:46:55.773629 | MIT | true | 4557620b33fd4651136c0559a50cec86 |
import itertools\nimport io\nfrom pathlib import Path\n\nimport numpy as np\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib import ft2font\nfrom matplotlib.testing.decorators import check_figures_equal\nimport matplotlib.font_manager as fm\nimport matplotlib.path as mpath\nimport matplotlib.pyplot as plt\n\n\ndef test_ft2image_draw_rect_filled():\n width = 23\n height = 42\n for x0, y0, x1, y1 in itertools.product([1, 100], [2, 200], [4, 400], [8, 800]):\n im = ft2font.FT2Image(width, height)\n im.draw_rect_filled(x0, y0, x1, y1)\n a = np.asarray(im)\n assert a.dtype == np.uint8\n assert a.shape == (height, width)\n if x0 == 100 or y0 == 200:\n # All the out-of-bounds starts should get automatically clipped.\n assert np.sum(a) == 0\n else:\n # Otherwise, ends are clipped to the dimension, but are also _inclusive_.\n filled = (min(x1 + 1, width) - x0) * (min(y1 + 1, height) - y0)\n assert np.sum(a) == 255 * filled\n\n\ndef test_ft2font_dejavu_attrs():\n file = fm.findfont('DejaVu Sans')\n font = ft2font.FT2Font(file)\n assert font.fname == file\n # Names extracted from FontForge: Font Information → PS Names tab.\n assert font.postscript_name == 'DejaVuSans'\n assert font.family_name == 'DejaVu Sans'\n assert font.style_name == 'Book'\n assert font.num_faces == 1 # Single TTF.\n assert font.num_named_instances == 0 # Not a variable font.\n assert font.num_glyphs == 6241 # From compact encoding view in FontForge.\n assert font.num_fixed_sizes == 0 # All glyphs are scalable.\n assert font.num_charmaps == 5\n # Other internal flags are set, so only check the ones we're allowed to test.\n expected_flags = (ft2font.FaceFlags.SCALABLE | ft2font.FaceFlags.SFNT |\n ft2font.FaceFlags.HORIZONTAL | ft2font.FaceFlags.KERNING |\n ft2font.FaceFlags.GLYPH_NAMES)\n assert expected_flags in font.face_flags\n assert font.style_flags == ft2font.StyleFlags.NORMAL\n assert font.scalable\n # From FontForge: Font Information → General tab → entry name below.\n assert font.units_per_EM == 2048 # Em Size.\n assert font.underline_position == -175 # Underline position.\n assert font.underline_thickness == 90 # Underline height.\n # From FontForge: Font Information → OS/2 tab → Metrics tab → entry name below.\n assert font.ascender == 1901 # HHead Ascent.\n assert font.descender == -483 # HHead Descent.\n # Unconfirmed values.\n assert font.height == 2384\n assert font.max_advance_width == 3838\n assert font.max_advance_height == 2384\n assert font.bbox == (-2090, -948, 3673, 2524)\n\n\ndef test_ft2font_cm_attrs():\n file = fm.findfont('cmtt10')\n font = ft2font.FT2Font(file)\n assert font.fname == file\n # Names extracted from FontForge: Font Information → PS Names tab.\n assert font.postscript_name == 'Cmtt10'\n assert font.family_name == 'cmtt10'\n assert font.style_name == 'Regular'\n assert font.num_faces == 1 # Single TTF.\n assert font.num_named_instances == 0 # Not a variable font.\n assert font.num_glyphs == 133 # From compact encoding view in FontForge.\n assert font.num_fixed_sizes == 0 # All glyphs are scalable.\n assert font.num_charmaps == 2\n # Other internal flags are set, so only check the ones we're allowed to test.\n expected_flags = (ft2font.FaceFlags.SCALABLE | ft2font.FaceFlags.SFNT |\n ft2font.FaceFlags.HORIZONTAL | ft2font.FaceFlags.GLYPH_NAMES)\n assert expected_flags in font.face_flags\n assert font.style_flags == ft2font.StyleFlags.NORMAL\n assert font.scalable\n # From FontForge: Font Information → General tab → entry name below.\n assert font.units_per_EM == 2048 # Em Size.\n assert font.underline_position == -143 # Underline position.\n assert font.underline_thickness == 20 # Underline height.\n # From FontForge: Font Information → OS/2 tab → Metrics tab → entry name below.\n assert font.ascender == 1276 # HHead Ascent.\n assert font.descender == -489 # HHead Descent.\n # Unconfirmed values.\n assert font.height == 1765\n assert font.max_advance_width == 1536\n assert font.max_advance_height == 1765\n assert font.bbox == (-12, -477, 1280, 1430)\n\n\ndef test_ft2font_stix_bold_attrs():\n file = fm.findfont('STIXSizeTwoSym:bold')\n font = ft2font.FT2Font(file)\n assert font.fname == file\n # Names extracted from FontForge: Font Information → PS Names tab.\n assert font.postscript_name == 'STIXSizeTwoSym-Bold'\n assert font.family_name == 'STIXSizeTwoSym'\n assert font.style_name == 'Bold'\n assert font.num_faces == 1 # Single TTF.\n assert font.num_named_instances == 0 # Not a variable font.\n assert font.num_glyphs == 20 # From compact encoding view in FontForge.\n assert font.num_fixed_sizes == 0 # All glyphs are scalable.\n assert font.num_charmaps == 3\n # Other internal flags are set, so only check the ones we're allowed to test.\n expected_flags = (ft2font.FaceFlags.SCALABLE | ft2font.FaceFlags.SFNT |\n ft2font.FaceFlags.HORIZONTAL | ft2font.FaceFlags.GLYPH_NAMES)\n assert expected_flags in font.face_flags\n assert font.style_flags == ft2font.StyleFlags.BOLD\n assert font.scalable\n # From FontForge: Font Information → General tab → entry name below.\n assert font.units_per_EM == 1000 # Em Size.\n assert font.underline_position == -133 # Underline position.\n assert font.underline_thickness == 20 # Underline height.\n # From FontForge: Font Information → OS/2 tab → Metrics tab → entry name below.\n assert font.ascender == 2095 # HHead Ascent.\n assert font.descender == -404 # HHead Descent.\n # Unconfirmed values.\n assert font.height == 2499\n assert font.max_advance_width == 1130\n assert font.max_advance_height == 2499\n assert font.bbox == (4, -355, 1185, 2095)\n\n\ndef test_ft2font_invalid_args(tmp_path):\n # filename argument.\n with pytest.raises(TypeError, match='to a font file or a binary-mode file object'):\n ft2font.FT2Font(None)\n with pytest.raises(TypeError, match='to a font file or a binary-mode file object'):\n ft2font.FT2Font(object()) # Not bytes or string, and has no read() method.\n file = tmp_path / 'invalid-font.ttf'\n file.write_text('This is not a valid font file.')\n with (pytest.raises(TypeError, match='to a font file or a binary-mode file object'),\n file.open('rt') as fd):\n ft2font.FT2Font(fd)\n with (pytest.raises(TypeError, match='to a font file or a binary-mode file object'),\n file.open('wt') as fd):\n ft2font.FT2Font(fd)\n with (pytest.raises(TypeError, match='to a font file or a binary-mode file object'),\n file.open('wb') as fd):\n ft2font.FT2Font(fd)\n\n file = fm.findfont('DejaVu Sans')\n\n # hinting_factor argument.\n with pytest.raises(TypeError, match='incompatible constructor arguments'):\n ft2font.FT2Font(file, 1.3)\n with pytest.raises(ValueError, match='hinting_factor must be greater than 0'):\n ft2font.FT2Font(file, 0)\n\n with pytest.raises(TypeError, match='incompatible constructor arguments'):\n # failing to be a list will fail before the 0\n ft2font.FT2Font(file, _fallback_list=(0,)) # type: ignore[arg-type]\n with pytest.raises(TypeError, match='incompatible constructor arguments'):\n ft2font.FT2Font(file, _fallback_list=[0]) # type: ignore[list-item]\n\n # kerning_factor argument.\n with pytest.raises(TypeError, match='incompatible constructor arguments'):\n ft2font.FT2Font(file, _kerning_factor=1.3)\n\n\ndef test_ft2font_clear():\n file = fm.findfont('DejaVu Sans')\n font = ft2font.FT2Font(file)\n assert font.get_num_glyphs() == 0\n assert font.get_width_height() == (0, 0)\n assert font.get_bitmap_offset() == (0, 0)\n font.set_text('ABabCDcd')\n assert font.get_num_glyphs() == 8\n assert font.get_width_height() != (0, 0)\n assert font.get_bitmap_offset() != (0, 0)\n font.clear()\n assert font.get_num_glyphs() == 0\n assert font.get_width_height() == (0, 0)\n assert font.get_bitmap_offset() == (0, 0)\n\n\ndef test_ft2font_set_size():\n file = fm.findfont('DejaVu Sans')\n # Default is 12pt @ 72 dpi.\n font = ft2font.FT2Font(file, hinting_factor=1, _kerning_factor=1)\n font.set_text('ABabCDcd')\n orig = font.get_width_height()\n font.set_size(24, 72)\n font.set_text('ABabCDcd')\n assert font.get_width_height() == tuple(pytest.approx(2 * x, 1e-1) for x in orig)\n font.set_size(12, 144)\n font.set_text('ABabCDcd')\n assert font.get_width_height() == tuple(pytest.approx(2 * x, 1e-1) for x in orig)\n\n\ndef test_ft2font_charmaps():\n def enc(name):\n # We don't expose the encoding enum from FreeType, but can generate it here.\n # For DejaVu, there are 5 charmaps, but only 2 have enum entries in FreeType.\n e = 0\n for x in name:\n e <<= 8\n e += ord(x)\n return e\n\n file = fm.findfont('DejaVu Sans')\n font = ft2font.FT2Font(file)\n assert font.num_charmaps == 5\n\n # Unicode.\n font.select_charmap(enc('unic'))\n unic = font.get_charmap()\n font.set_charmap(0) # Unicode platform, Unicode BMP only.\n after = font.get_charmap()\n assert len(after) <= len(unic)\n for chr, glyph in after.items():\n assert unic[chr] == glyph == font.get_char_index(chr)\n font.set_charmap(1) # Unicode platform, modern subtable.\n after = font.get_charmap()\n assert unic == after\n font.set_charmap(3) # Windows platform, Unicode BMP only.\n after = font.get_charmap()\n assert len(after) <= len(unic)\n for chr, glyph in after.items():\n assert unic[chr] == glyph == font.get_char_index(chr)\n font.set_charmap(4) # Windows platform, Unicode full repertoire, modern subtable.\n after = font.get_charmap()\n assert unic == after\n\n # This is just a random sample from FontForge.\n glyph_names = {\n 'non-existent-glyph-name': 0,\n 'plusminus': 115,\n 'Racute': 278,\n 'perthousand': 2834,\n 'seveneighths': 3057,\n 'triagup': 3721,\n 'uni01D3': 405,\n 'uni0417': 939,\n 'uni2A02': 4464,\n 'u1D305': 5410,\n 'u1F0A1': 5784,\n }\n for name, index in glyph_names.items():\n assert font.get_name_index(name) == index\n if name == 'non-existent-glyph-name':\n name = '.notdef'\n # This doesn't always apply, but it does for DejaVu Sans.\n assert font.get_glyph_name(index) == name\n\n # Apple Roman.\n font.select_charmap(enc('armn'))\n armn = font.get_charmap()\n font.set_charmap(2) # Macintosh platform, Roman.\n after = font.get_charmap()\n assert armn == after\n assert len(armn) <= 256 # 8-bit encoding.\n # The first 128 characters of Apple Roman match ASCII, which also matches Unicode.\n for o in range(1, 128):\n if o not in armn or o not in unic:\n continue\n assert unic[o] == armn[o]\n # Check a couple things outside the ASCII set that are different in each charset.\n examples = [\n # (Unicode, Macintosh)\n (0x2020, 0xA0), # Dagger.\n (0x00B0, 0xA1), # Degree symbol.\n (0x00A3, 0xA3), # Pound sign.\n (0x00A7, 0xA4), # Section sign.\n (0x00B6, 0xA6), # Pilcrow.\n (0x221E, 0xB0), # Infinity symbol.\n ]\n for u, m in examples:\n # Though the encoding is different, the glyph should be the same.\n assert unic[u] == armn[m]\n\n\n_expected_sfnt_names = {\n 'DejaVu Sans': {\n 0: 'Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved.\n'\n 'Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.\n'\n 'DejaVu changes are in public domain\n',\n 1: 'DejaVu Sans',\n 2: 'Book',\n 3: 'DejaVu Sans',\n 4: 'DejaVu Sans',\n 5: 'Version 2.35',\n 6: 'DejaVuSans',\n 8: 'DejaVu fonts team',\n 11: 'http://dejavu.sourceforge.net',\n 13: 'Fonts are (c) Bitstream (see below). '\n 'DejaVu changes are in public domain. '\n '''Glyphs imported from Arev fonts are (c) Tavmjung Bah (see below)\n\nBitstream Vera Fonts Copyright\n------------------------------\n\nCopyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is\na trademark of Bitstream, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof the fonts accompanying this license ("Fonts") and associated\ndocumentation files (the "Font Software"), to reproduce and distribute the\nFont Software, including without limitation the rights to use, copy, merge,\npublish, distribute, and/or sell copies of the Font Software, and to permit\npersons to whom the Font Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright and trademark notices and this permission notice shall\nbe included in all copies of one or more of the Font Software typefaces.\n\nThe Font Software may be modified, altered, or added to, and in particular\nthe designs of glyphs or characters in the Fonts may be modified and\nadditional glyphs or characters may be added to the Fonts, only if the fonts\nare renamed to names not containing either the words "Bitstream" or the word\n"Vera".\n\nThis License becomes null and void to the extent applicable to Fonts or Font\nSoftware that has been modified and is distributed under the "Bitstream\nVera" names.\n\nThe Font Software may be sold as part of a larger software package but no\ncopy of one or more of the Font Software typefaces may be sold by itself.\n\nTHE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,\nTRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME\nFOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING\nANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF\nTHE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE\nFONT SOFTWARE.\n\nExcept as contained in this notice, the names of Gnome, the Gnome\nFoundation, and Bitstream Inc., shall not be used in advertising or\notherwise to promote the sale, use or other dealings in this Font Software\nwithout prior written authorization from the Gnome Foundation or Bitstream\nInc., respectively. For further information, contact: fonts at gnome dot\norg. ''' '''\n\nArev Fonts Copyright\n------------------------------\n\nCopyright (c) 2006 by Tavmjong Bah. All Rights Reserved.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of the fonts accompanying this license ("Fonts") and\nassociated documentation files (the "Font Software"), to reproduce\nand distribute the modifications to the Bitstream Vera Font Software,\nincluding without limitation the rights to use, copy, merge, publish,\ndistribute, and/or sell copies of the Font Software, and to permit\npersons to whom the Font Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright and trademark notices and this permission notice\nshall be included in all copies of one or more of the Font Software\ntypefaces.\n\nThe Font Software may be modified, altered, or added to, and in\nparticular the designs of glyphs or characters in the Fonts may be\nmodified and additional glyphs or characters may be added to the\nFonts, only if the fonts are renamed to names not containing either\nthe words "Tavmjong Bah" or the word "Arev".\n\nThis License becomes null and void to the extent applicable to Fonts\nor Font Software that has been modified and is distributed under the ''' '''\n"Tavmjong Bah Arev" names.\n\nThe Font Software may be sold as part of a larger software package but\nno copy of one or more of the Font Software typefaces may be sold by\nitself.\n\nTHE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\nOF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL\nTAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nINCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL\nDAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM\nOTHER DEALINGS IN THE FONT SOFTWARE.\n\nExcept as contained in this notice, the name of Tavmjong Bah shall not\nbe used in advertising or otherwise to promote the sale, use or other\ndealings in this Font Software without prior written authorization\nfrom Tavmjong Bah. For further information, contact: tavmjong @ free\n. fr.''',\n 14: 'http://dejavu.sourceforge.net/wiki/index.php/License',\n 16: 'DejaVu Sans',\n 17: 'Book',\n },\n 'cmtt10': {\n 0: 'Copyright (C) 1994, Basil K. Malyshev. All Rights Reserved.'\n '012BaKoMa Fonts Collection, Level-B.',\n 1: 'cmtt10',\n 2: 'Regular',\n 3: 'FontMonger:cmtt10',\n 4: 'cmtt10',\n 5: '1.1/12-Nov-94',\n 6: 'Cmtt10',\n },\n 'STIXSizeTwoSym:bold': {\n 0: 'Copyright (c) 2001-2010 by the STI Pub Companies, consisting of the '\n 'American Chemical Society, the American Institute of Physics, the American '\n 'Mathematical Society, the American Physical Society, Elsevier, Inc., and '\n 'The Institute of Electrical and Electronic Engineers, Inc. Portions '\n 'copyright (c) 1998-2003 by MicroPress, Inc. Portions copyright (c) 1990 by '\n 'Elsevier, Inc. All rights reserved.',\n 1: 'STIXSizeTwoSym',\n 2: 'Bold',\n 3: 'FontMaster:STIXSizeTwoSym-Bold:1.0.0',\n 4: 'STIXSizeTwoSym-Bold',\n 5: 'Version 1.0.0',\n 6: 'STIXSizeTwoSym-Bold',\n 7: 'STIX Fonts(TM) is a trademark of The Institute of Electrical and '\n 'Electronics Engineers, Inc.',\n 9: 'MicroPress Inc., with final additions and corrections provided by Coen '\n 'Hoffman, Elsevier (retired)',\n 10: 'Arie de Ruiter, who in 1995 was Head of Information Technology '\n 'Development at Elsevier Science, made a proposal to the STI Pub group, an '\n 'informal group of publishers consisting of representatives from the '\n 'American Chemical Society (ACS), American Institute of Physics (AIP), '\n 'American Mathematical Society (AMS), American Physical Society (APS), '\n 'Elsevier, and Institute of Electrical and Electronics Engineers (IEEE). '\n 'De Ruiter encouraged the members to consider development of a series of '\n 'Web fonts, which he proposed should be called the Scientific and '\n 'Technical Information eXchange, or STIX, Fonts. All STI Pub member '\n 'organizations enthusiastically endorsed this proposal, and the STI Pub '\n 'group agreed to embark on what has become a twelve-year project. The goal '\n 'of the project was to identify all alphabetic, symbolic, and other '\n 'special characters used in any facet of scientific publishing and to '\n 'create a set of Unicode-based fonts that would be distributed free to '\n 'every scientist, student, and other interested party worldwide. The fonts '\n 'would be consistent with the emerging Unicode standard, and would permit '\n 'universal representation of every character. With the release of the STIX '\n "fonts, de Ruiter's vision has been realized.",\n 11: 'http://www.stixfonts.org',\n 12: 'http://www.micropress-inc.com',\n 13: 'As a condition for receiving these fonts at no charge, each person '\n 'downloading the fonts must agree to some simple license terms. The '\n 'license is based on the SIL Open Font License '\n '<http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL>. The '\n 'SIL License is a free and open source license specifically designed for '\n 'fonts and related software. The basic terms are that the recipient will '\n 'not remove the copyright and trademark statements from the fonts and '\n 'that, if the person decides to create a derivative work based on the STIX '\n 'Fonts but incorporating some changes or enhancements, the derivative work '\n '("Modified Version") will carry a different name. The copyright and '\n 'trademark restrictions are part of the agreement between the STI Pub '\n 'companies and the typeface designer. The "renaming" restriction results '\n 'from the desire of the STI Pub companies to assure that the STIX Fonts '\n 'will continue to function in a predictable fashion for all that use them. '\n 'No copy of one or more of the individual Font typefaces that form the '\n 'STIX Fonts(TM) set may be sold by itself, but other than this one '\n 'restriction, licensees are free to sell the fonts either separately or as '\n 'part of a package that combines other software or fonts with this font '\n 'set.',\n 14: 'http://www.stixfonts.org/user_license.html',\n },\n}\n\n\n@pytest.mark.parametrize('font_name, expected', _expected_sfnt_names.items(),\n ids=_expected_sfnt_names.keys())\ndef test_ft2font_get_sfnt(font_name, expected):\n file = fm.findfont(font_name)\n font = ft2font.FT2Font(file)\n sfnt = font.get_sfnt()\n for name, value in expected.items():\n # Macintosh, Unicode 1.0, English, name.\n assert sfnt.pop((1, 0, 0, name)) == value.encode('ascii')\n # Microsoft, Unicode, English United States, name.\n assert sfnt.pop((3, 1, 1033, name)) == value.encode('utf-16be')\n assert sfnt == {}\n\n\n_expected_sfnt_tables = {\n 'DejaVu Sans': {\n 'invalid': None,\n 'head': {\n 'version': (1, 0),\n 'fontRevision': (2, 22937),\n 'checkSumAdjustment': -175678572,\n 'magicNumber': 0x5F0F3CF5,\n 'flags': 31,\n 'unitsPerEm': 2048,\n 'created': (0, 3514699492), 'modified': (0, 3514699492),\n 'xMin': -2090, 'yMin': -948, 'xMax': 3673, 'yMax': 2524,\n 'macStyle': 0,\n 'lowestRecPPEM': 8,\n 'fontDirectionHint': 0,\n 'indexToLocFormat': 1,\n 'glyphDataFormat': 0,\n },\n 'maxp': {\n 'version': (1, 0),\n 'numGlyphs': 6241,\n 'maxPoints': 852, 'maxComponentPoints': 104, 'maxTwilightPoints': 16,\n 'maxContours': 43, 'maxComponentContours': 12,\n 'maxZones': 2,\n 'maxStorage': 153,\n 'maxFunctionDefs': 64,\n 'maxInstructionDefs': 0,\n 'maxStackElements': 1045,\n 'maxSizeOfInstructions': 534,\n 'maxComponentElements': 8,\n 'maxComponentDepth': 4,\n },\n 'OS/2': {\n 'version': 1,\n 'xAvgCharWidth': 1038,\n 'usWeightClass': 400, 'usWidthClass': 5,\n 'fsType': 0,\n 'ySubscriptXSize': 1331, 'ySubscriptYSize': 1433,\n 'ySubscriptXOffset': 0, 'ySubscriptYOffset': 286,\n 'ySuperscriptXSize': 1331, 'ySuperscriptYSize': 1433,\n 'ySuperscriptXOffset': 0, 'ySuperscriptYOffset': 983,\n 'yStrikeoutSize': 102, 'yStrikeoutPosition': 530,\n 'sFamilyClass': 0,\n 'panose': b'\x02\x0b\x06\x03\x03\x08\x04\x02\x02\x04',\n 'ulCharRange': (3875565311, 3523280383, 170156073, 67117068),\n 'achVendID': b'PfEd',\n 'fsSelection': 64, 'fsFirstCharIndex': 32, 'fsLastCharIndex': 65535,\n },\n 'hhea': {\n 'version': (1, 0),\n 'ascent': 1901, 'descent': -483, 'lineGap': 0,\n 'advanceWidthMax': 3838,\n 'minLeftBearing': -2090, 'minRightBearing': -1455,\n 'xMaxExtent': 3673,\n 'caretSlopeRise': 1, 'caretSlopeRun': 0, 'caretOffset': 0,\n 'metricDataFormat': 0, 'numOfLongHorMetrics': 6226,\n },\n 'vhea': None,\n 'post': {\n 'format': (2, 0),\n 'isFixedPitch': 0, 'italicAngle': (0, 0),\n 'underlinePosition': -130, 'underlineThickness': 90,\n 'minMemType42': 0, 'maxMemType42': 0,\n 'minMemType1': 0, 'maxMemType1': 0,\n },\n 'pclt': None,\n },\n 'cmtt10': {\n 'invalid': None,\n 'head': {\n 'version': (1, 0),\n 'fontRevision': (1, 0),\n 'checkSumAdjustment': 555110277,\n 'magicNumber': 0x5F0F3CF5,\n 'flags': 3,\n 'unitsPerEm': 2048,\n 'created': (0, 0), 'modified': (0, 0),\n 'xMin': -12, 'yMin': -477, 'xMax': 1280, 'yMax': 1430,\n 'macStyle': 0,\n 'lowestRecPPEM': 6,\n 'fontDirectionHint': 2,\n 'indexToLocFormat': 1,\n 'glyphDataFormat': 0,\n },\n 'maxp': {\n 'version': (1, 0),\n 'numGlyphs': 133,\n 'maxPoints': 94, 'maxComponentPoints': 0, 'maxTwilightPoints': 12,\n 'maxContours': 5, 'maxComponentContours': 0,\n 'maxZones': 2,\n 'maxStorage': 6,\n 'maxFunctionDefs': 64,\n 'maxInstructionDefs': 0,\n 'maxStackElements': 200,\n 'maxSizeOfInstructions': 100,\n 'maxComponentElements': 4,\n 'maxComponentDepth': 1,\n },\n 'OS/2': {\n 'version': 0,\n 'xAvgCharWidth': 1075,\n 'usWeightClass': 400, 'usWidthClass': 5,\n 'fsType': 0,\n 'ySubscriptXSize': 410, 'ySubscriptYSize': 369,\n 'ySubscriptXOffset': 0, 'ySubscriptYOffset': -469,\n 'ySuperscriptXSize': 410, 'ySuperscriptYSize': 369,\n 'ySuperscriptXOffset': 0, 'ySuperscriptYOffset': 1090,\n 'yStrikeoutSize': 102, 'yStrikeoutPosition': 530,\n 'sFamilyClass': 0,\n 'panose': b'\x02\x0b\x05\x00\x00\x00\x00\x00\x00\x00',\n 'ulCharRange': (0, 0, 0, 0),\n 'achVendID': b'\x00\x00\x00\x00',\n 'fsSelection': 64, 'fsFirstCharIndex': 32, 'fsLastCharIndex': 9835,\n },\n 'hhea': {\n 'version': (1, 0),\n 'ascent': 1276, 'descent': -489, 'lineGap': 0,\n 'advanceWidthMax': 1536,\n 'minLeftBearing': -12, 'minRightBearing': -29,\n 'xMaxExtent': 1280,\n 'caretSlopeRise': 1, 'caretSlopeRun': 0, 'caretOffset': 0,\n 'metricDataFormat': 0, 'numOfLongHorMetrics': 133,\n },\n 'vhea': None,\n 'post': {\n 'format': (2, 0),\n 'isFixedPitch': 0, 'italicAngle': (0, 0),\n 'underlinePosition': -133, 'underlineThickness': 20,\n 'minMemType42': 0, 'maxMemType42': 0,\n 'minMemType1': 0, 'maxMemType1': 0,\n },\n 'pclt': {\n 'version': (1, 0),\n 'fontNumber': 2147483648,\n 'pitch': 1075,\n 'xHeight': 905,\n 'style': 0,\n 'typeFamily': 0,\n 'capHeight': 1276,\n 'symbolSet': 0,\n 'typeFace': b'cmtt10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',\n 'characterComplement': b'\xff\xff\xff\xff7\xff\xff\xfe',\n 'strokeWeight': 0,\n 'widthType': -5,\n 'serifStyle': 64,\n },\n },\n 'STIXSizeTwoSym:bold': {\n 'invalid': None,\n 'head': {\n 'version': (1, 0),\n 'fontRevision': (1, 0),\n 'checkSumAdjustment': 1803408080,\n 'magicNumber': 0x5F0F3CF5,\n 'flags': 11,\n 'unitsPerEm': 1000,\n 'created': (0, 3359035786), 'modified': (0, 3359035786),\n 'xMin': 4, 'yMin': -355, 'xMax': 1185, 'yMax': 2095,\n 'macStyle': 1,\n 'lowestRecPPEM': 8,\n 'fontDirectionHint': 2,\n 'indexToLocFormat': 0,\n 'glyphDataFormat': 0,\n },\n 'maxp': {\n 'version': (1, 0),\n 'numGlyphs': 20,\n 'maxPoints': 37, 'maxComponentPoints': 0, 'maxTwilightPoints': 0,\n 'maxContours': 1, 'maxComponentContours': 0,\n 'maxZones': 2,\n 'maxStorage': 1,\n 'maxFunctionDefs': 64,\n 'maxInstructionDefs': 0,\n 'maxStackElements': 64,\n 'maxSizeOfInstructions': 0,\n 'maxComponentElements': 0,\n 'maxComponentDepth': 0,\n },\n 'OS/2': {\n 'version': 2,\n 'xAvgCharWidth': 598,\n 'usWeightClass': 700, 'usWidthClass': 5,\n 'fsType': 0,\n 'ySubscriptXSize': 500, 'ySubscriptYSize': 500,\n 'ySubscriptXOffset': 0, 'ySubscriptYOffset': 250,\n 'ySuperscriptXSize': 500, 'ySuperscriptYSize': 500,\n 'ySuperscriptXOffset': 0, 'ySuperscriptYOffset': 500,\n 'yStrikeoutSize': 20, 'yStrikeoutPosition': 1037,\n 'sFamilyClass': 0,\n 'panose': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',\n 'ulCharRange': (3, 192, 0, 0),\n 'achVendID': b'STIX',\n 'fsSelection': 32, 'fsFirstCharIndex': 32, 'fsLastCharIndex': 10217,\n },\n 'hhea': {\n 'version': (1, 0),\n 'ascent': 2095, 'descent': -404, 'lineGap': 0,\n 'advanceWidthMax': 1130,\n 'minLeftBearing': 0, 'minRightBearing': -55,\n 'xMaxExtent': 1185,\n 'caretSlopeRise': 1, 'caretSlopeRun': 0, 'caretOffset': 0,\n 'metricDataFormat': 0, 'numOfLongHorMetrics': 19,\n },\n 'vhea': None,\n 'post': {\n 'format': (2, 0),\n 'isFixedPitch': 0, 'italicAngle': (0, 0),\n 'underlinePosition': -123, 'underlineThickness': 20,\n 'minMemType42': 0, 'maxMemType42': 0,\n 'minMemType1': 0, 'maxMemType1': 0,\n },\n 'pclt': None,\n },\n}\n\n\n@pytest.mark.parametrize('font_name', _expected_sfnt_tables.keys())\n@pytest.mark.parametrize('header', _expected_sfnt_tables['DejaVu Sans'].keys())\ndef test_ft2font_get_sfnt_table(font_name, header):\n file = fm.findfont(font_name)\n font = ft2font.FT2Font(file)\n assert font.get_sfnt_table(header) == _expected_sfnt_tables[font_name][header]\n\n\n@pytest.mark.parametrize('left, right, unscaled, unfitted, default', [\n # These are all the same class.\n ('A', 'A', 57, 248, 256), ('A', 'À', 57, 248, 256), ('A', 'Á', 57, 248, 256),\n ('A', 'Â', 57, 248, 256), ('A', 'Ã', 57, 248, 256), ('A', 'Ä', 57, 248, 256),\n # And a few other random ones.\n ('D', 'A', -36, -156, -128), ('T', '.', -243, -1056, -1024),\n ('X', 'C', -149, -647, -640), ('-', 'J', 114, 495, 512),\n])\ndef test_ft2font_get_kerning(left, right, unscaled, unfitted, default):\n file = fm.findfont('DejaVu Sans')\n # With unscaled, these settings should produce exact values found in FontForge.\n font = ft2font.FT2Font(file, hinting_factor=1, _kerning_factor=0)\n font.set_size(100, 100)\n assert font.get_kerning(font.get_char_index(ord(left)),\n font.get_char_index(ord(right)),\n ft2font.Kerning.UNSCALED) == unscaled\n assert font.get_kerning(font.get_char_index(ord(left)),\n font.get_char_index(ord(right)),\n ft2font.Kerning.UNFITTED) == unfitted\n assert font.get_kerning(font.get_char_index(ord(left)),\n font.get_char_index(ord(right)),\n ft2font.Kerning.DEFAULT) == default\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match='Use Kerning.UNSCALED instead'):\n k = ft2font.KERNING_UNSCALED\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match='Use Kerning enum values instead'):\n assert font.get_kerning(font.get_char_index(ord(left)),\n font.get_char_index(ord(right)),\n int(k)) == unscaled\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match='Use Kerning.UNFITTED instead'):\n k = ft2font.KERNING_UNFITTED\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match='Use Kerning enum values instead'):\n assert font.get_kerning(font.get_char_index(ord(left)),\n font.get_char_index(ord(right)),\n int(k)) == unfitted\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match='Use Kerning.DEFAULT instead'):\n k = ft2font.KERNING_DEFAULT\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match='Use Kerning enum values instead'):\n assert font.get_kerning(font.get_char_index(ord(left)),\n font.get_char_index(ord(right)),\n int(k)) == default\n\n\ndef test_ft2font_set_text():\n file = fm.findfont('DejaVu Sans')\n font = ft2font.FT2Font(file, hinting_factor=1, _kerning_factor=0)\n xys = font.set_text('')\n np.testing.assert_array_equal(xys, np.empty((0, 2)))\n assert font.get_width_height() == (0, 0)\n assert font.get_num_glyphs() == 0\n assert font.get_descent() == 0\n assert font.get_bitmap_offset() == (0, 0)\n # This string uses all the kerning pairs defined for test_ft2font_get_kerning.\n xys = font.set_text('AADAT.XC-J')\n np.testing.assert_array_equal(\n xys,\n [(0, 0), (512, 0), (1024, 0), (1600, 0), (2112, 0), (2496, 0), (2688, 0),\n (3200, 0), (3712, 0), (4032, 0)])\n assert font.get_width_height() == (4288, 768)\n assert font.get_num_glyphs() == 10\n assert font.get_descent() == 192\n assert font.get_bitmap_offset() == (6, 0)\n\n\ndef test_ft2font_loading():\n file = fm.findfont('DejaVu Sans')\n font = ft2font.FT2Font(file, hinting_factor=1, _kerning_factor=0)\n for glyph in [font.load_char(ord('M')),\n font.load_glyph(font.get_char_index(ord('M')))]:\n assert glyph is not None\n assert glyph.width == 576\n assert glyph.height == 576\n assert glyph.horiBearingX == 0\n assert glyph.horiBearingY == 576\n assert glyph.horiAdvance == 640\n assert glyph.linearHoriAdvance == 678528\n assert glyph.vertBearingX == -384\n assert glyph.vertBearingY == 64\n assert glyph.vertAdvance == 832\n assert glyph.bbox == (54, 0, 574, 576)\n assert font.get_num_glyphs() == 2 # Both count as loaded.\n # But neither has been placed anywhere.\n assert font.get_width_height() == (0, 0)\n assert font.get_descent() == 0\n assert font.get_bitmap_offset() == (0, 0)\n\n\ndef test_ft2font_drawing():\n expected_str = (\n ' ',\n '11 11 ',\n '11 11 ',\n '1 1 1 1 ',\n '1 1 1 1 ',\n '1 1 1 1 ',\n '1 11 1 ',\n '1 11 1 ',\n '1 1 ',\n '1 1 ',\n ' ',\n )\n expected = np.array([\n [int(c) for c in line.replace(' ', '0')] for line in expected_str\n ])\n expected *= 255\n file = fm.findfont('DejaVu Sans')\n font = ft2font.FT2Font(file, hinting_factor=1, _kerning_factor=0)\n font.set_text('M')\n font.draw_glyphs_to_bitmap(antialiased=False)\n image = font.get_image()\n np.testing.assert_array_equal(image, expected)\n font = ft2font.FT2Font(file, hinting_factor=1, _kerning_factor=0)\n glyph = font.load_char(ord('M'))\n image = ft2font.FT2Image(expected.shape[1], expected.shape[0])\n font.draw_glyph_to_bitmap(image, -1, 1, glyph, antialiased=False)\n np.testing.assert_array_equal(image, expected)\n\n\ndef test_ft2font_get_path():\n file = fm.findfont('DejaVu Sans')\n font = ft2font.FT2Font(file, hinting_factor=1, _kerning_factor=0)\n vertices, codes = font.get_path()\n assert vertices.shape == (0, 2)\n assert codes.shape == (0, )\n font.load_char(ord('M'))\n vertices, codes = font.get_path()\n expected_vertices = np.array([\n (0.843750, 9.000000), (2.609375, 9.000000), # Top left.\n (4.906250, 2.875000), # Top of midpoint.\n (7.218750, 9.000000), (8.968750, 9.000000), # Top right.\n (8.968750, 0.000000), (7.843750, 0.000000), # Bottom right.\n (7.843750, 7.906250), # Point under top right.\n (5.531250, 1.734375), (4.296875, 1.734375), # Bar under midpoint.\n (1.984375, 7.906250), # Point under top left.\n (1.984375, 0.000000), (0.843750, 0.000000), # Bottom left.\n (0.843750, 9.000000), # Back to top left corner.\n (0.000000, 0.000000),\n ])\n np.testing.assert_array_equal(vertices, expected_vertices)\n expected_codes = np.full(expected_vertices.shape[0], mpath.Path.LINETO,\n dtype=mpath.Path.code_type)\n expected_codes[0] = mpath.Path.MOVETO\n expected_codes[-1] = mpath.Path.CLOSEPOLY\n np.testing.assert_array_equal(codes, expected_codes)\n\n\n@pytest.mark.parametrize('family_name, file_name',\n [("WenQuanYi Zen Hei", "wqy-zenhei.ttc"),\n ("Noto Sans CJK JP", "NotoSansCJK.ttc"),\n ("Noto Sans TC", "NotoSansTC-Regular.otf")]\n )\ndef test_fallback_smoke(family_name, file_name):\n fp = fm.FontProperties(family=[family_name])\n if Path(fm.findfont(fp)).name != file_name:\n pytest.skip(f"Font {family_name} ({file_name}) is missing")\n plt.rcParams['font.size'] = 20\n fig = plt.figure(figsize=(4.75, 1.85))\n fig.text(0.05, 0.45, "There are 几个汉字 in between!",\n family=['DejaVu Sans', family_name])\n fig.text(0.05, 0.85, "There are 几个汉字 in between!",\n family=[family_name])\n\n # TODO enable fallback for other backends!\n for fmt in ['png', 'raw']: # ["svg", "pdf", "ps"]:\n fig.savefig(io.BytesIO(), format=fmt)\n\n\n@pytest.mark.parametrize('family_name, file_name',\n [("WenQuanYi Zen Hei", "wqy-zenhei"),\n ("Noto Sans CJK JP", "NotoSansCJK"),\n ("Noto Sans TC", "NotoSansTC-Regular.otf")]\n )\n@check_figures_equal(extensions=["png", "pdf", "eps", "svg"])\ndef test_font_fallback_chinese(fig_test, fig_ref, family_name, file_name):\n fp = fm.FontProperties(family=[family_name])\n if file_name not in Path(fm.findfont(fp)).name:\n pytest.skip(f"Font {family_name} ({file_name}) is missing")\n\n text = ["There are", "几个汉字", "in between!"]\n\n plt.rcParams["font.size"] = 20\n test_fonts = [["DejaVu Sans", family_name]] * 3\n ref_fonts = [["DejaVu Sans"], [family_name], ["DejaVu Sans"]]\n\n for j, (txt, test_font, ref_font) in enumerate(\n zip(text, test_fonts, ref_fonts)\n ):\n fig_ref.text(0.05, .85 - 0.15*j, txt, family=ref_font)\n fig_test.text(0.05, .85 - 0.15*j, txt, family=test_font)\n\n\n@pytest.mark.parametrize("font_list",\n [['DejaVu Serif', 'DejaVu Sans'],\n ['DejaVu Sans Mono']],\n ids=["two fonts", "one font"])\ndef test_fallback_missing(recwarn, font_list):\n fig = plt.figure()\n fig.text(.5, .5, "Hello 🙃 World!", family=font_list)\n fig.canvas.draw()\n assert all(isinstance(warn.message, UserWarning) for warn in recwarn)\n # not sure order is guaranteed on the font listing so\n assert recwarn[0].message.args[0].startswith(\n "Glyph 128579 (\\N{UPSIDE-DOWN FACE}) missing from font(s)")\n assert all([font in recwarn[0].message.args[0] for font in font_list])\n\n\n@pytest.mark.parametrize(\n "family_name, file_name",\n [\n ("WenQuanYi Zen Hei", "wqy-zenhei"),\n ("Noto Sans CJK JP", "NotoSansCJK"),\n ("Noto Sans TC", "NotoSansTC-Regular.otf")\n ],\n)\ndef test__get_fontmap(family_name, file_name):\n fp = fm.FontProperties(family=[family_name])\n found_file_name = Path(fm.findfont(fp)).name\n if file_name not in found_file_name:\n pytest.skip(f"Font {family_name} ({file_name}) is missing")\n\n text = "There are 几个汉字 in between!"\n ft = fm.get_font(\n fm.fontManager._find_fonts_by_props(\n fm.FontProperties(family=["DejaVu Sans", family_name])\n )\n )\n fontmap = ft._get_fontmap(text)\n for char, font in fontmap.items():\n if ord(char) > 127:\n assert Path(font.fname).name == found_file_name\n else:\n assert Path(font.fname).name == "DejaVuSans.ttf"\n | .venv\Lib\site-packages\matplotlib\tests\test_ft2font.py | test_ft2font.py | Python | 40,838 | 0.95 | 0.059385 | 0.047235 | vue-tools | 829 | 2023-11-24T00:51:57.103056 | Apache-2.0 | true | 98ab7625d8652e5605cf43a0742a091e |
from importlib import import_module\nfrom pkgutil import walk_packages\n\nimport matplotlib\nimport pytest\n\n# Get the names of all matplotlib submodules,\n# except for the unit tests and private modules.\nmodule_names = [\n m.name\n for m in walk_packages(\n path=matplotlib.__path__, prefix=f'{matplotlib.__name__}.'\n )\n if not m.name.startswith(__package__)\n and not any(x.startswith('_') for x in m.name.split('.'))\n]\n\n\n@pytest.mark.parametrize('module_name', module_names)\n@pytest.mark.filterwarnings('ignore::DeprecationWarning')\n@pytest.mark.filterwarnings('ignore::ImportWarning')\ndef test_getattr(module_name):\n """\n Test that __getattr__ methods raise AttributeError for unknown keys.\n See #20822, #20855.\n """\n try:\n module = import_module(module_name)\n except (ImportError, RuntimeError, OSError) as e:\n # Skip modules that cannot be imported due to missing dependencies\n pytest.skip(f'Cannot import {module_name} due to {e}')\n\n key = 'THIS_SYMBOL_SHOULD_NOT_EXIST'\n if hasattr(module, key):\n delattr(module, key)\n | .venv\Lib\site-packages\matplotlib\tests\test_getattr.py | test_getattr.py | Python | 1,090 | 0.95 | 0.228571 | 0.1 | awesome-app | 611 | 2024-03-02T16:53:51.894940 | BSD-3-Clause | true | aa87b1efa86d4d8b60581afbb01d6ad2 |
import matplotlib.gridspec as gridspec\nimport matplotlib.pyplot as plt\nimport pytest\n\n\ndef test_equal():\n gs = gridspec.GridSpec(2, 1)\n assert gs[0, 0] == gs[0, 0]\n assert gs[:, 0] == gs[:, 0]\n\n\ndef test_width_ratios():\n """\n Addresses issue #5835.\n See at https://github.com/matplotlib/matplotlib/issues/5835.\n """\n with pytest.raises(ValueError):\n gridspec.GridSpec(1, 1, width_ratios=[2, 1, 3])\n\n\ndef test_height_ratios():\n """\n Addresses issue #5835.\n See at https://github.com/matplotlib/matplotlib/issues/5835.\n """\n with pytest.raises(ValueError):\n gridspec.GridSpec(1, 1, height_ratios=[2, 1, 3])\n\n\ndef test_repr():\n ss = gridspec.GridSpec(3, 3)[2, 1:3]\n assert repr(ss) == "GridSpec(3, 3)[2:3, 1:3]"\n\n ss = gridspec.GridSpec(2, 2,\n height_ratios=(3, 1),\n width_ratios=(1, 3))\n assert repr(ss) == \\n "GridSpec(2, 2, height_ratios=(3, 1), width_ratios=(1, 3))"\n\n\ndef test_subplotspec_args():\n fig, axs = plt.subplots(1, 2)\n # should work:\n gs = gridspec.GridSpecFromSubplotSpec(2, 1,\n subplot_spec=axs[0].get_subplotspec())\n assert gs.get_topmost_subplotspec() == axs[0].get_subplotspec()\n with pytest.raises(TypeError, match="subplot_spec must be type SubplotSpec"):\n gs = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=axs[0])\n with pytest.raises(TypeError, match="subplot_spec must be type SubplotSpec"):\n gs = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=axs)\n | .venv\Lib\site-packages\matplotlib\tests\test_gridspec.py | test_gridspec.py | Python | 1,580 | 0.95 | 0.1 | 0.025641 | vue-tools | 194 | 2024-01-05T01:49:49.035478 | Apache-2.0 | true | 9fb632c2608db7a5a95d2f9cb596bc59 |
from contextlib import ExitStack\nfrom copy import copy\nimport functools\nimport io\nimport os\nfrom pathlib import Path\nimport platform\nimport sys\nimport urllib.request\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nfrom PIL import Image\n\nimport matplotlib as mpl\nfrom matplotlib import (\n colors, image as mimage, patches, pyplot as plt, style, rcParams)\nfrom matplotlib.image import (AxesImage, BboxImage, FigureImage,\n NonUniformImage, PcolorImage)\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\nfrom matplotlib.transforms import Bbox, Affine2D, TransformedBbox\nimport matplotlib.ticker as mticker\n\nimport pytest\n\n\n@image_comparison(['interp_alpha.png'], remove_text=True)\ndef test_alpha_interp():\n """Test the interpolation of the alpha channel on RGBA images"""\n fig, (axl, axr) = plt.subplots(1, 2)\n # full green image\n img = np.zeros((5, 5, 4))\n img[..., 1] = np.ones((5, 5))\n # transparent under main diagonal\n img[..., 3] = np.tril(np.ones((5, 5), dtype=np.uint8))\n axl.imshow(img, interpolation="none")\n axr.imshow(img, interpolation="bilinear")\n\n\n@image_comparison(['interp_nearest_vs_none'],\n extensions=['pdf', 'svg'], remove_text=True)\ndef test_interp_nearest_vs_none():\n """Test the effect of "nearest" and "none" interpolation"""\n # Setting dpi to something really small makes the difference very\n # visible. This works fine with pdf, since the dpi setting doesn't\n # affect anything but images, but the agg output becomes unusably\n # small.\n rcParams['savefig.dpi'] = 3\n X = np.array([[[218, 165, 32], [122, 103, 238]],\n [[127, 255, 0], [255, 99, 71]]], dtype=np.uint8)\n fig, (ax1, ax2) = plt.subplots(1, 2)\n ax1.imshow(X, interpolation='none')\n ax1.set_title('interpolation none')\n ax2.imshow(X, interpolation='nearest')\n ax2.set_title('interpolation nearest')\n\n\n@pytest.mark.parametrize('suppressComposite', [False, True])\n@image_comparison(['figimage'], extensions=['png', 'pdf'])\ndef test_figimage(suppressComposite):\n fig = plt.figure(figsize=(2, 2), dpi=100)\n fig.suppressComposite = suppressComposite\n x, y = np.ix_(np.arange(100) / 100.0, np.arange(100) / 100)\n z = np.sin(x**2 + y**2 - x*y)\n c = np.sin(20*x**2 + 50*y**2)\n img = z + c/5\n\n fig.figimage(img, xo=0, yo=0, origin='lower')\n fig.figimage(img[::-1, :], xo=0, yo=100, origin='lower')\n fig.figimage(img[:, ::-1], xo=100, yo=0, origin='lower')\n fig.figimage(img[::-1, ::-1], xo=100, yo=100, origin='lower')\n\n\ndef test_image_python_io():\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3])\n buffer = io.BytesIO()\n fig.savefig(buffer)\n buffer.seek(0)\n plt.imread(buffer)\n\n\n@pytest.mark.parametrize(\n "img_size, fig_size, interpolation",\n [(5, 2, "hanning"), # data larger than figure.\n (5, 5, "nearest"), # exact resample.\n (5, 10, "nearest"), # double sample.\n (3, 2.9, "hanning"), # <3 upsample.\n (3, 9.1, "nearest"), # >3 upsample.\n ])\n@check_figures_equal(extensions=['png'])\ndef test_imshow_antialiased(fig_test, fig_ref,\n img_size, fig_size, interpolation):\n np.random.seed(19680801)\n dpi = plt.rcParams["savefig.dpi"]\n A = np.random.rand(int(dpi * img_size), int(dpi * img_size))\n for fig in [fig_test, fig_ref]:\n fig.set_size_inches(fig_size, fig_size)\n ax = fig_test.subplots()\n ax.set_position([0, 0, 1, 1])\n ax.imshow(A, interpolation='auto')\n ax = fig_ref.subplots()\n ax.set_position([0, 0, 1, 1])\n ax.imshow(A, interpolation=interpolation)\n\n\n@check_figures_equal(extensions=['png'])\ndef test_imshow_zoom(fig_test, fig_ref):\n # should be less than 3 upsample, so should be nearest...\n np.random.seed(19680801)\n dpi = plt.rcParams["savefig.dpi"]\n A = np.random.rand(int(dpi * 3), int(dpi * 3))\n for fig in [fig_test, fig_ref]:\n fig.set_size_inches(2.9, 2.9)\n ax = fig_test.subplots()\n ax.imshow(A, interpolation='auto')\n ax.set_xlim([10, 20])\n ax.set_ylim([10, 20])\n ax = fig_ref.subplots()\n ax.imshow(A, interpolation='nearest')\n ax.set_xlim([10, 20])\n ax.set_ylim([10, 20])\n\n\n@check_figures_equal(extensions=['png'])\ndef test_imshow_pil(fig_test, fig_ref):\n style.use("default")\n png_path = Path(__file__).parent / "baseline_images/pngsuite/basn3p04.png"\n tiff_path = Path(__file__).parent / "baseline_images/test_image/uint16.tif"\n axs = fig_test.subplots(2)\n axs[0].imshow(Image.open(png_path))\n axs[1].imshow(Image.open(tiff_path))\n axs = fig_ref.subplots(2)\n axs[0].imshow(plt.imread(png_path))\n axs[1].imshow(plt.imread(tiff_path))\n\n\ndef test_imread_pil_uint16():\n img = plt.imread(os.path.join(os.path.dirname(__file__),\n 'baseline_images', 'test_image', 'uint16.tif'))\n assert img.dtype == np.uint16\n assert np.sum(img) == 134184960\n\n\ndef test_imread_fspath():\n img = plt.imread(\n Path(__file__).parent / 'baseline_images/test_image/uint16.tif')\n assert img.dtype == np.uint16\n assert np.sum(img) == 134184960\n\n\n@pytest.mark.parametrize("fmt", ["png", "jpg", "jpeg", "tiff"])\ndef test_imsave(fmt):\n has_alpha = fmt not in ["jpg", "jpeg"]\n\n # The goal here is that the user can specify an output logical DPI\n # for the image, but this will not actually add any extra pixels\n # to the image, it will merely be used for metadata purposes.\n\n # So we do the traditional case (dpi == 1), and the new case (dpi\n # == 100) and read the resulting PNG files back in and make sure\n # the data is 100% identical.\n np.random.seed(1)\n # The height of 1856 pixels was selected because going through creating an\n # actual dpi=100 figure to save the image to a Pillow-provided format would\n # cause a rounding error resulting in a final image of shape 1855.\n data = np.random.rand(1856, 2)\n\n buff_dpi1 = io.BytesIO()\n plt.imsave(buff_dpi1, data, format=fmt, dpi=1)\n\n buff_dpi100 = io.BytesIO()\n plt.imsave(buff_dpi100, data, format=fmt, dpi=100)\n\n buff_dpi1.seek(0)\n arr_dpi1 = plt.imread(buff_dpi1, format=fmt)\n\n buff_dpi100.seek(0)\n arr_dpi100 = plt.imread(buff_dpi100, format=fmt)\n\n assert arr_dpi1.shape == (1856, 2, 3 + has_alpha)\n assert arr_dpi100.shape == (1856, 2, 3 + has_alpha)\n\n assert_array_equal(arr_dpi1, arr_dpi100)\n\n\ndef test_imsave_python_sequences():\n # Tests saving an image with data passed using Python sequence types\n # such as lists or tuples.\n\n # RGB image: 3 rows × 2 columns, with float values in [0.0, 1.0]\n img_data = [\n [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)],\n [(0.0, 0.0, 1.0), (1.0, 1.0, 0.0)],\n [(0.0, 1.0, 1.0), (1.0, 0.0, 1.0)],\n ]\n\n buff = io.BytesIO()\n plt.imsave(buff, img_data, format="png")\n buff.seek(0)\n read_img = plt.imread(buff)\n\n assert_array_equal(\n np.array(img_data),\n read_img[:, :, :3] # Drop alpha if present\n )\n\n\n@pytest.mark.parametrize("origin", ["upper", "lower"])\ndef test_imsave_rgba_origin(origin):\n # test that imsave always passes c-contiguous arrays down to pillow\n buf = io.BytesIO()\n result = np.zeros((10, 10, 4), dtype='uint8')\n mimage.imsave(buf, arr=result, format="png", origin=origin)\n\n\n@pytest.mark.parametrize("fmt", ["png", "pdf", "ps", "eps", "svg"])\ndef test_imsave_fspath(fmt):\n plt.imsave(Path(os.devnull), np.array([[0, 1]]), format=fmt)\n\n\ndef test_imsave_color_alpha():\n # Test that imsave accept arrays with ndim=3 where the third dimension is\n # color and alpha without raising any exceptions, and that the data is\n # acceptably preserved through a save/read roundtrip.\n np.random.seed(1)\n\n for origin in ['lower', 'upper']:\n data = np.random.rand(16, 16, 4)\n buff = io.BytesIO()\n plt.imsave(buff, data, origin=origin, format="png")\n\n buff.seek(0)\n arr_buf = plt.imread(buff)\n\n # Recreate the float -> uint8 conversion of the data\n # We can only expect to be the same with 8 bits of precision,\n # since that's what the PNG file used.\n data = (255*data).astype('uint8')\n if origin == 'lower':\n data = data[::-1]\n arr_buf = (255*arr_buf).astype('uint8')\n\n assert_array_equal(data, arr_buf)\n\n\ndef test_imsave_pil_kwargs_png():\n from PIL.PngImagePlugin import PngInfo\n buf = io.BytesIO()\n pnginfo = PngInfo()\n pnginfo.add_text("Software", "test")\n plt.imsave(buf, [[0, 1], [2, 3]],\n format="png", pil_kwargs={"pnginfo": pnginfo})\n im = Image.open(buf)\n assert im.info["Software"] == "test"\n\n\ndef test_imsave_pil_kwargs_tiff():\n from PIL.TiffTags import TAGS_V2 as TAGS\n buf = io.BytesIO()\n pil_kwargs = {"description": "test image"}\n plt.imsave(buf, [[0, 1], [2, 3]], format="tiff", pil_kwargs=pil_kwargs)\n assert len(pil_kwargs) == 1\n im = Image.open(buf)\n tags = {TAGS[k].name: v for k, v in im.tag_v2.items()}\n assert tags["ImageDescription"] == "test image"\n\n\n@image_comparison(['image_alpha'], remove_text=True)\ndef test_image_alpha():\n np.random.seed(0)\n Z = np.random.rand(6, 6)\n\n fig, (ax1, ax2, ax3) = plt.subplots(1, 3)\n ax1.imshow(Z, alpha=1.0, interpolation='none')\n ax2.imshow(Z, alpha=0.5, interpolation='none')\n ax3.imshow(Z, alpha=0.5, interpolation='nearest')\n\n\n@mpl.style.context('mpl20')\n@check_figures_equal(extensions=['png'])\ndef test_imshow_alpha(fig_test, fig_ref):\n np.random.seed(19680801)\n\n rgbf = np.random.rand(6, 6, 3)\n rgbu = np.uint8(rgbf * 255)\n ((ax0, ax1), (ax2, ax3)) = fig_test.subplots(2, 2)\n ax0.imshow(rgbf, alpha=0.5)\n ax1.imshow(rgbf, alpha=0.75)\n ax2.imshow(rgbu, alpha=0.5)\n ax3.imshow(rgbu, alpha=0.75)\n\n rgbaf = np.concatenate((rgbf, np.ones((6, 6, 1))), axis=2)\n rgbau = np.concatenate((rgbu, np.full((6, 6, 1), 255, np.uint8)), axis=2)\n ((ax0, ax1), (ax2, ax3)) = fig_ref.subplots(2, 2)\n rgbaf[:, :, 3] = 0.5\n ax0.imshow(rgbaf)\n rgbaf[:, :, 3] = 0.75\n ax1.imshow(rgbaf)\n rgbau[:, :, 3] = 127\n ax2.imshow(rgbau)\n rgbau[:, :, 3] = 191\n ax3.imshow(rgbau)\n\n\ndef test_cursor_data():\n from matplotlib.backend_bases import MouseEvent\n\n fig, ax = plt.subplots()\n im = ax.imshow(np.arange(100).reshape(10, 10), origin='upper')\n\n x, y = 4, 4\n xdisp, ydisp = ax.transData.transform([x, y])\n\n event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)\n assert im.get_cursor_data(event) == 44\n\n # Now try for a point outside the image\n # Tests issue #4957\n x, y = 10.1, 4\n xdisp, ydisp = ax.transData.transform([x, y])\n\n event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)\n assert im.get_cursor_data(event) is None\n\n # Hmm, something is wrong here... I get 0, not None...\n # But, this works further down in the tests with extents flipped\n # x, y = 0.1, -0.1\n # xdisp, ydisp = ax.transData.transform([x, y])\n # event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)\n # z = im.get_cursor_data(event)\n # assert z is None, "Did not get None, got %d" % z\n\n ax.clear()\n # Now try with the extents flipped.\n im = ax.imshow(np.arange(100).reshape(10, 10), origin='lower')\n\n x, y = 4, 4\n xdisp, ydisp = ax.transData.transform([x, y])\n\n event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)\n assert im.get_cursor_data(event) == 44\n\n fig, ax = plt.subplots()\n im = ax.imshow(np.arange(100).reshape(10, 10), extent=[0, 0.5, 0, 0.5])\n\n x, y = 0.25, 0.25\n xdisp, ydisp = ax.transData.transform([x, y])\n\n event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)\n assert im.get_cursor_data(event) == 55\n\n # Now try for a point outside the image\n # Tests issue #4957\n x, y = 0.75, 0.25\n xdisp, ydisp = ax.transData.transform([x, y])\n\n event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)\n assert im.get_cursor_data(event) is None\n\n x, y = 0.01, -0.01\n xdisp, ydisp = ax.transData.transform([x, y])\n\n event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)\n assert im.get_cursor_data(event) is None\n\n # Now try with additional transform applied to the image artist\n trans = Affine2D().scale(2).rotate(0.5)\n im = ax.imshow(np.arange(100).reshape(10, 10),\n transform=trans + ax.transData)\n x, y = 3, 10\n xdisp, ydisp = ax.transData.transform([x, y])\n event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)\n assert im.get_cursor_data(event) == 44\n\n\n@pytest.mark.parametrize("xy, data", [\n # x/y coords chosen to be 0.5 above boundaries so they lie within image pixels\n [[0.5, 0.5], 0 + 0],\n [[0.5, 1.5], 0 + 1],\n [[4.5, 0.5], 16 + 0],\n [[8.5, 0.5], 16 + 0],\n [[9.5, 2.5], 81 + 4],\n [[-1, 0.5], None],\n [[0.5, -1], None],\n ]\n)\ndef test_cursor_data_nonuniform(xy, data):\n from matplotlib.backend_bases import MouseEvent\n\n # Non-linear set of x-values\n x = np.array([0, 1, 4, 9, 16])\n y = np.array([0, 1, 2, 3, 4])\n z = x[np.newaxis, :]**2 + y[:, np.newaxis]**2\n\n fig, ax = plt.subplots()\n im = NonUniformImage(ax, extent=(x.min(), x.max(), y.min(), y.max()))\n im.set_data(x, y, z)\n ax.add_image(im)\n # Set lower min lim so we can test cursor outside image\n ax.set_xlim(x.min() - 2, x.max())\n ax.set_ylim(y.min() - 2, y.max())\n\n xdisp, ydisp = ax.transData.transform(xy)\n event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)\n assert im.get_cursor_data(event) == data, (im.get_cursor_data(event), data)\n\n\n@pytest.mark.parametrize(\n "data, text", [\n ([[10001, 10000]], "[10001.000]"),\n ([[.123, .987]], "[0.123]"),\n ([[np.nan, 1, 2]], "[]"),\n ([[1, 1+1e-15]], "[1.0000000000000000]"),\n ([[-1, -1]], "[-1.0]"),\n ([[0, 0]], "[0.00]"),\n ])\ndef test_format_cursor_data(data, text):\n from matplotlib.backend_bases import MouseEvent\n\n fig, ax = plt.subplots()\n im = ax.imshow(data)\n\n xdisp, ydisp = ax.transData.transform([0, 0])\n event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)\n assert im.format_cursor_data(im.get_cursor_data(event)) == text\n\n\n@image_comparison(['image_clip'], style='mpl20')\ndef test_image_clip():\n d = [[1, 2], [3, 4]]\n\n fig, ax = plt.subplots()\n im = ax.imshow(d)\n patch = patches.Circle((0, 0), radius=1, transform=ax.transData)\n im.set_clip_path(patch)\n\n\n@image_comparison(['image_cliprect'], style='mpl20')\ndef test_image_cliprect():\n fig, ax = plt.subplots()\n d = [[1, 2], [3, 4]]\n\n im = ax.imshow(d, extent=(0, 5, 0, 5))\n\n rect = patches.Rectangle(\n xy=(1, 1), width=2, height=2, transform=im.axes.transData)\n im.set_clip_path(rect)\n\n\n@check_figures_equal(extensions=['png'])\ndef test_imshow_10_10_1(fig_test, fig_ref):\n # 10x10x1 should be the same as 10x10\n arr = np.arange(100).reshape((10, 10, 1))\n ax = fig_ref.subplots()\n ax.imshow(arr[:, :, 0], interpolation="bilinear", extent=(1, 2, 1, 2))\n ax.set_xlim(0, 3)\n ax.set_ylim(0, 3)\n\n ax = fig_test.subplots()\n ax.imshow(arr, interpolation="bilinear", extent=(1, 2, 1, 2))\n ax.set_xlim(0, 3)\n ax.set_ylim(0, 3)\n\n\ndef test_imshow_10_10_2():\n fig, ax = plt.subplots()\n arr = np.arange(200).reshape((10, 10, 2))\n with pytest.raises(TypeError):\n ax.imshow(arr)\n\n\ndef test_imshow_10_10_5():\n fig, ax = plt.subplots()\n arr = np.arange(500).reshape((10, 10, 5))\n with pytest.raises(TypeError):\n ax.imshow(arr)\n\n\n@image_comparison(['no_interpolation_origin'], remove_text=True)\ndef test_no_interpolation_origin():\n fig, axs = plt.subplots(2)\n axs[0].imshow(np.arange(100).reshape((2, 50)), origin="lower",\n interpolation='none')\n axs[1].imshow(np.arange(100).reshape((2, 50)), interpolation='none')\n\n\n@image_comparison(['image_shift'], remove_text=True, extensions=['pdf', 'svg'])\ndef test_image_shift():\n imgData = [[1 / x + 1 / y for x in range(1, 100)] for y in range(1, 100)]\n tMin = 734717.945208\n tMax = 734717.946366\n\n fig, ax = plt.subplots()\n ax.imshow(imgData, norm=colors.LogNorm(), interpolation='none',\n extent=(tMin, tMax, 1, 100))\n ax.set_aspect('auto')\n\n\ndef test_image_edges():\n fig = plt.figure(figsize=[1, 1])\n ax = fig.add_axes([0, 0, 1, 1], frameon=False)\n\n data = np.tile(np.arange(12), 15).reshape(20, 9)\n\n im = ax.imshow(data, origin='upper', extent=[-10, 10, -10, 10],\n interpolation='none', cmap='gray')\n\n x = y = 2\n ax.set_xlim([-x, x])\n ax.set_ylim([-y, y])\n\n ax.set_xticks([])\n ax.set_yticks([])\n\n buf = io.BytesIO()\n fig.savefig(buf, facecolor=(0, 1, 0))\n\n buf.seek(0)\n\n im = plt.imread(buf)\n r, g, b, a = sum(im[:, 0])\n r, g, b, a = sum(im[:, -1])\n\n assert g != 100, 'Expected a non-green edge - but sadly, it was.'\n\n\n@image_comparison(['image_composite_background'],\n remove_text=True, style='mpl20')\ndef test_image_composite_background():\n fig, ax = plt.subplots()\n arr = np.arange(12).reshape(4, 3)\n ax.imshow(arr, extent=[0, 2, 15, 0])\n ax.imshow(arr, extent=[4, 6, 15, 0])\n ax.set_facecolor((1, 0, 0, 0.5))\n ax.set_xlim([0, 12])\n\n\n@image_comparison(['image_composite_alpha'], remove_text=True)\ndef test_image_composite_alpha():\n """\n Tests that the alpha value is recognized and correctly applied in the\n process of compositing images together.\n """\n fig, ax = plt.subplots()\n arr = np.zeros((11, 21, 4))\n arr[:, :, 0] = 1\n arr[:, :, 3] = np.concatenate(\n (np.arange(0, 1.1, 0.1), np.arange(0, 1, 0.1)[::-1]))\n arr2 = np.zeros((21, 11, 4))\n arr2[:, :, 0] = 1\n arr2[:, :, 1] = 1\n arr2[:, :, 3] = np.concatenate(\n (np.arange(0, 1.1, 0.1), np.arange(0, 1, 0.1)[::-1]))[:, np.newaxis]\n ax.imshow(arr, extent=[1, 2, 5, 0], alpha=0.3)\n ax.imshow(arr, extent=[2, 3, 5, 0], alpha=0.6)\n ax.imshow(arr, extent=[3, 4, 5, 0])\n ax.imshow(arr2, extent=[0, 5, 1, 2])\n ax.imshow(arr2, extent=[0, 5, 2, 3], alpha=0.6)\n ax.imshow(arr2, extent=[0, 5, 3, 4], alpha=0.3)\n ax.set_facecolor((0, 0.5, 0, 1))\n ax.set_xlim([0, 5])\n ax.set_ylim([5, 0])\n\n\n@check_figures_equal(extensions=["pdf"])\ndef test_clip_path_disables_compositing(fig_test, fig_ref):\n t = np.arange(9).reshape((3, 3))\n for fig in [fig_test, fig_ref]:\n ax = fig.add_subplot()\n ax.imshow(t, clip_path=(mpl.path.Path([(0, 0), (0, 1), (1, 0)]),\n ax.transData))\n ax.imshow(t, clip_path=(mpl.path.Path([(1, 1), (1, 2), (2, 1)]),\n ax.transData))\n fig_ref.suppressComposite = True\n\n\n@image_comparison(['rasterize_10dpi'],\n extensions=['pdf', 'svg'], remove_text=True, style='mpl20')\ndef test_rasterize_dpi():\n # This test should check rasterized rendering with high output resolution.\n # It plots a rasterized line and a normal image with imshow. So it will\n # catch when images end up in the wrong place in case of non-standard dpi\n # setting. Instead of high-res rasterization I use low-res. Therefore\n # the fact that the resolution is non-standard is easily checked by\n # image_comparison.\n img = np.asarray([[1, 2], [3, 4]])\n\n fig, axs = plt.subplots(1, 3, figsize=(3, 1))\n\n axs[0].imshow(img)\n\n axs[1].plot([0, 1], [0, 1], linewidth=20., rasterized=True)\n axs[1].set(xlim=(0, 1), ylim=(-1, 2))\n\n axs[2].plot([0, 1], [0, 1], linewidth=20.)\n axs[2].set(xlim=(0, 1), ylim=(-1, 2))\n\n # Low-dpi PDF rasterization errors prevent proper image comparison tests.\n # Hide detailed structures like the axes spines.\n for ax in axs:\n ax.set_xticks([])\n ax.set_yticks([])\n ax.spines[:].set_visible(False)\n\n rcParams['savefig.dpi'] = 10\n\n\n@image_comparison(['bbox_image_inverted'], remove_text=True, style='mpl20')\ndef test_bbox_image_inverted():\n # This is just used to produce an image to feed to BboxImage\n image = np.arange(100).reshape((10, 10))\n\n fig, ax = plt.subplots()\n bbox_im = BboxImage(\n TransformedBbox(Bbox([[100, 100], [0, 0]]), ax.transData),\n interpolation='nearest')\n bbox_im.set_data(image)\n bbox_im.set_clip_on(False)\n ax.set_xlim(0, 100)\n ax.set_ylim(0, 100)\n ax.add_artist(bbox_im)\n\n image = np.identity(10)\n\n bbox_im = BboxImage(TransformedBbox(Bbox([[0.1, 0.2], [0.3, 0.25]]),\n ax.get_figure().transFigure),\n interpolation='nearest')\n bbox_im.set_data(image)\n bbox_im.set_clip_on(False)\n ax.add_artist(bbox_im)\n\n\ndef test_get_window_extent_for_AxisImage():\n # Create a figure of known size (1000x1000 pixels), place an image\n # object at a given location and check that get_window_extent()\n # returns the correct bounding box values (in pixels).\n\n im = np.array([[0.25, 0.75, 1.0, 0.75], [0.1, 0.65, 0.5, 0.4],\n [0.6, 0.3, 0.0, 0.2], [0.7, 0.9, 0.4, 0.6]])\n fig, ax = plt.subplots(figsize=(10, 10), dpi=100)\n ax.set_position([0, 0, 1, 1])\n ax.set_xlim(0, 1)\n ax.set_ylim(0, 1)\n im_obj = ax.imshow(\n im, extent=[0.4, 0.7, 0.2, 0.9], interpolation='nearest')\n\n fig.canvas.draw()\n renderer = fig.canvas.renderer\n im_bbox = im_obj.get_window_extent(renderer)\n\n assert_array_equal(im_bbox.get_points(), [[400, 200], [700, 900]])\n\n fig, ax = plt.subplots(figsize=(10, 10), dpi=100)\n ax.set_position([0, 0, 1, 1])\n ax.set_xlim(1, 2)\n ax.set_ylim(0, 1)\n im_obj = ax.imshow(\n im, extent=[0.4, 0.7, 0.2, 0.9], interpolation='nearest',\n transform=ax.transAxes)\n\n fig.canvas.draw()\n renderer = fig.canvas.renderer\n im_bbox = im_obj.get_window_extent(renderer)\n\n assert_array_equal(im_bbox.get_points(), [[400, 200], [700, 900]])\n\n\n@image_comparison(['zoom_and_clip_upper_origin.png'],\n remove_text=True, style='mpl20')\ndef test_zoom_and_clip_upper_origin():\n image = np.arange(100)\n image = image.reshape((10, 10))\n\n fig, ax = plt.subplots()\n ax.imshow(image)\n ax.set_ylim(2.0, -0.5)\n ax.set_xlim(-0.5, 2.0)\n\n\ndef test_nonuniformimage_setcmap():\n ax = plt.gca()\n im = NonUniformImage(ax)\n im.set_cmap('Blues')\n\n\ndef test_nonuniformimage_setnorm():\n ax = plt.gca()\n im = NonUniformImage(ax)\n im.set_norm(plt.Normalize())\n\n\ndef test_jpeg_2d():\n # smoke test that mode-L pillow images work.\n imd = np.ones((10, 10), dtype='uint8')\n for i in range(10):\n imd[i, :] = np.linspace(0.0, 1.0, 10) * 255\n im = Image.new('L', (10, 10))\n im.putdata(imd.flatten())\n fig, ax = plt.subplots()\n ax.imshow(im)\n\n\ndef test_jpeg_alpha():\n plt.figure(figsize=(1, 1), dpi=300)\n # Create an image that is all black, with a gradient from 0-1 in\n # the alpha channel from left to right.\n im = np.zeros((300, 300, 4), dtype=float)\n im[..., 3] = np.linspace(0.0, 1.0, 300)\n\n plt.figimage(im)\n\n buff = io.BytesIO()\n plt.savefig(buff, facecolor="red", format='jpg', dpi=300)\n\n buff.seek(0)\n image = Image.open(buff)\n\n # If this fails, there will be only one color (all black). If this\n # is working, we should have all 256 shades of grey represented.\n num_colors = len(image.getcolors(256))\n assert 175 <= num_colors <= 230\n # The fully transparent part should be red.\n corner_pixel = image.getpixel((0, 0))\n assert corner_pixel == (254, 0, 0)\n\n\ndef test_axesimage_setdata():\n ax = plt.gca()\n im = AxesImage(ax)\n z = np.arange(12, dtype=float).reshape((4, 3))\n im.set_data(z)\n z[0, 0] = 9.9\n assert im._A[0, 0] == 0, 'value changed'\n\n\ndef test_figureimage_setdata():\n fig = plt.gcf()\n im = FigureImage(fig)\n z = np.arange(12, dtype=float).reshape((4, 3))\n im.set_data(z)\n z[0, 0] = 9.9\n assert im._A[0, 0] == 0, 'value changed'\n\n\n@pytest.mark.parametrize(\n "image_cls,x,y,a", [\n (NonUniformImage,\n np.arange(3.), np.arange(4.), np.arange(12.).reshape((4, 3))),\n (PcolorImage,\n np.arange(3.), np.arange(4.), np.arange(6.).reshape((3, 2))),\n ])\ndef test_setdata_xya(image_cls, x, y, a):\n ax = plt.gca()\n im = image_cls(ax)\n im.set_data(x, y, a)\n x[0] = y[0] = a[0, 0] = 9.9\n assert im._A[0, 0] == im._Ax[0] == im._Ay[0] == 0, 'value changed'\n im.set_data(x, y, a.reshape((*a.shape, -1))) # Just a smoketest.\n\n\ndef test_minimized_rasterized():\n # This ensures that the rasterized content in the colorbars is\n # only as thick as the colorbar, and doesn't extend to other parts\n # of the image. See #5814. While the original bug exists only\n # in Postscript, the best way to detect it is to generate SVG\n # and then parse the output to make sure the two colorbar images\n # are the same size.\n from xml.etree import ElementTree\n\n np.random.seed(0)\n data = np.random.rand(10, 10)\n\n fig, ax = plt.subplots(1, 2)\n p1 = ax[0].pcolormesh(data)\n p2 = ax[1].pcolormesh(data)\n\n plt.colorbar(p1, ax=ax[0])\n plt.colorbar(p2, ax=ax[1])\n\n buff = io.BytesIO()\n plt.savefig(buff, format='svg')\n\n buff = io.BytesIO(buff.getvalue())\n tree = ElementTree.parse(buff)\n width = None\n for image in tree.iter('image'):\n if width is None:\n width = image['width']\n else:\n if image['width'] != width:\n assert False\n\n\ndef test_load_from_url():\n path = Path(__file__).parent / "baseline_images/pngsuite/basn3p04.png"\n url = ('file:'\n + ('///' if sys.platform == 'win32' else '')\n + path.resolve().as_posix())\n with pytest.raises(ValueError, match="Please open the URL"):\n plt.imread(url)\n with urllib.request.urlopen(url) as file:\n plt.imread(file)\n\n\n@image_comparison(['log_scale_image'], remove_text=True)\ndef test_log_scale_image():\n Z = np.zeros((10, 10))\n Z[::2] = 1\n\n fig, ax = plt.subplots()\n ax.imshow(Z, extent=[1, 100, 1, 100], cmap='viridis', vmax=1, vmin=-1,\n aspect='auto')\n ax.set(yscale='log')\n\n\n@image_comparison(['rotate_image'], remove_text=True)\ndef test_rotate_image():\n delta = 0.25\n x = y = np.arange(-3.0, 3.0, delta)\n X, Y = np.meshgrid(x, y)\n Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi)\n Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) /\n (2 * np.pi * 0.5 * 1.5))\n Z = Z2 - Z1 # difference of Gaussians\n\n fig, ax1 = plt.subplots(1, 1)\n im1 = ax1.imshow(Z, interpolation='none', cmap='viridis',\n origin='lower',\n extent=[-2, 4, -3, 2], clip_on=True)\n\n trans_data2 = Affine2D().rotate_deg(30) + ax1.transData\n im1.set_transform(trans_data2)\n\n # display intended extent of the image\n x1, x2, y1, y2 = im1.get_extent()\n\n ax1.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], "r--", lw=3,\n transform=trans_data2)\n\n ax1.set_xlim(2, 5)\n ax1.set_ylim(0, 4)\n\n\ndef test_image_preserve_size():\n buff = io.BytesIO()\n\n im = np.zeros((481, 321))\n plt.imsave(buff, im, format="png")\n\n buff.seek(0)\n img = plt.imread(buff)\n\n assert img.shape[:2] == im.shape\n\n\ndef test_image_preserve_size2():\n n = 7\n data = np.identity(n, float)\n\n fig = plt.figure(figsize=(n, n), frameon=False)\n ax = fig.add_axes((0.0, 0.0, 1.0, 1.0))\n ax.set_axis_off()\n ax.imshow(data, interpolation='nearest', origin='lower', aspect='auto')\n buff = io.BytesIO()\n fig.savefig(buff, dpi=1)\n\n buff.seek(0)\n img = plt.imread(buff)\n\n assert img.shape == (7, 7, 4)\n\n assert_array_equal(np.asarray(img[:, :, 0], bool),\n np.identity(n, bool)[::-1])\n\n\n@image_comparison(['mask_image_over_under.png'], remove_text=True, tol=1.0)\ndef test_mask_image_over_under():\n\n delta = 0.025\n x = y = np.arange(-3.0, 3.0, delta)\n X, Y = np.meshgrid(x, y)\n Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi)\n Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) /\n (2 * np.pi * 0.5 * 1.5))\n Z = 10*(Z2 - Z1) # difference of Gaussians\n\n palette = plt.cm.gray.with_extremes(over='r', under='g', bad='b')\n Zm = np.ma.masked_where(Z > 1.2, Z)\n fig, (ax1, ax2) = plt.subplots(1, 2)\n im = ax1.imshow(Zm, interpolation='bilinear',\n cmap=palette,\n norm=colors.Normalize(vmin=-1.0, vmax=1.0, clip=False),\n origin='lower', extent=[-3, 3, -3, 3])\n ax1.set_title('Green=low, Red=high, Blue=bad')\n fig.colorbar(im, extend='both', orientation='horizontal',\n ax=ax1, aspect=10)\n\n im = ax2.imshow(Zm, interpolation='nearest',\n cmap=palette,\n norm=colors.BoundaryNorm([-1, -0.5, -0.2, 0, 0.2, 0.5, 1],\n ncolors=256, clip=False),\n origin='lower', extent=[-3, 3, -3, 3])\n ax2.set_title('With BoundaryNorm')\n fig.colorbar(im, extend='both', spacing='proportional',\n orientation='horizontal', ax=ax2, aspect=10)\n\n\n@image_comparison(['mask_image'], remove_text=True)\ndef test_mask_image():\n # Test mask image two ways: Using nans and using a masked array.\n\n fig, (ax1, ax2) = plt.subplots(1, 2)\n\n A = np.ones((5, 5))\n A[1:2, 1:2] = np.nan\n\n ax1.imshow(A, interpolation='nearest')\n\n A = np.zeros((5, 5), dtype=bool)\n A[1:2, 1:2] = True\n A = np.ma.masked_array(np.ones((5, 5), dtype=np.uint16), A)\n\n ax2.imshow(A, interpolation='nearest')\n\n\ndef test_mask_image_all():\n # Test behavior with an image that is entirely masked does not warn\n data = np.full((2, 2), np.nan)\n fig, ax = plt.subplots()\n ax.imshow(data)\n fig.canvas.draw_idle() # would emit a warning\n\n\n@image_comparison(['imshow_endianess.png'], remove_text=True)\ndef test_imshow_endianess():\n x = np.arange(10)\n X, Y = np.meshgrid(x, x)\n Z = np.hypot(X - 5, Y - 5)\n\n fig, (ax1, ax2) = plt.subplots(1, 2)\n\n kwargs = dict(origin="lower", interpolation='nearest', cmap='viridis')\n\n ax1.imshow(Z.astype('<f8'), **kwargs)\n ax2.imshow(Z.astype('>f8'), **kwargs)\n\n\n@image_comparison(['imshow_masked_interpolation'],\n tol=0 if platform.machine() == 'x86_64' else 0.01,\n remove_text=True, style='mpl20')\ndef test_imshow_masked_interpolation():\n\n cmap = mpl.colormaps['viridis'].with_extremes(over='r', under='b', bad='k')\n\n N = 20\n n = colors.Normalize(vmin=0, vmax=N*N-1)\n\n data = np.arange(N*N, dtype=float).reshape(N, N)\n\n data[5, 5] = -1\n # This will cause crazy ringing for the higher-order\n # interpolations\n data[15, 5] = 1e5\n\n # data[3, 3] = np.nan\n\n data[15, 15] = np.inf\n\n mask = np.zeros_like(data).astype('bool')\n mask[5, 15] = True\n\n data = np.ma.masked_array(data, mask)\n\n fig, ax_grid = plt.subplots(3, 6)\n interps = sorted(mimage._interpd_)\n interps.remove('auto')\n interps.remove('antialiased')\n\n for interp, ax in zip(interps, ax_grid.ravel()):\n ax.set_title(interp)\n ax.imshow(data, norm=n, cmap=cmap, interpolation=interp)\n ax.axis('off')\n\n\ndef test_imshow_no_warn_invalid():\n plt.imshow([[1, 2], [3, np.nan]]) # Check that no warning is emitted.\n\n\n@pytest.mark.parametrize(\n 'dtype', [np.dtype(s) for s in 'u2 u4 i2 i4 i8 f4 f8'.split()])\ndef test_imshow_clips_rgb_to_valid_range(dtype):\n arr = np.arange(300, dtype=dtype).reshape((10, 10, 3))\n if dtype.kind != 'u':\n arr -= 10\n too_low = arr < 0\n too_high = arr > 255\n if dtype.kind == 'f':\n arr = arr / 255\n _, ax = plt.subplots()\n out = ax.imshow(arr).get_array()\n assert (out[too_low] == 0).all()\n if dtype.kind == 'f':\n assert (out[too_high] == 1).all()\n assert out.dtype.kind == 'f'\n else:\n assert (out[too_high] == 255).all()\n assert out.dtype == np.uint8\n\n\n@image_comparison(['imshow_flatfield.png'], remove_text=True, style='mpl20')\ndef test_imshow_flatfield():\n fig, ax = plt.subplots()\n im = ax.imshow(np.ones((5, 5)), interpolation='nearest')\n im.set_clim(.5, 1.5)\n\n\n@image_comparison(['imshow_bignumbers.png'], remove_text=True, style='mpl20')\ndef test_imshow_bignumbers():\n rcParams['image.interpolation'] = 'nearest'\n # putting a big number in an array of integers shouldn't\n # ruin the dynamic range of the resolved bits.\n fig, ax = plt.subplots()\n img = np.array([[1, 2, 1e12], [3, 1, 4]], dtype=np.uint64)\n pc = ax.imshow(img)\n pc.set_clim(0, 5)\n\n\n@image_comparison(['imshow_bignumbers_real.png'],\n remove_text=True, style='mpl20')\ndef test_imshow_bignumbers_real():\n rcParams['image.interpolation'] = 'nearest'\n # putting a big number in an array of integers shouldn't\n # ruin the dynamic range of the resolved bits.\n fig, ax = plt.subplots()\n img = np.array([[2., 1., 1.e22], [4., 1., 3.]])\n pc = ax.imshow(img)\n pc.set_clim(0, 5)\n\n\n@pytest.mark.parametrize(\n "make_norm",\n [colors.Normalize,\n colors.LogNorm,\n lambda: colors.SymLogNorm(1),\n lambda: colors.PowerNorm(1)])\ndef test_empty_imshow(make_norm):\n fig, ax = plt.subplots()\n with pytest.warns(UserWarning,\n match="Attempting to set identical low and high xlims"):\n im = ax.imshow([[]], norm=make_norm())\n im.set_extent([-5, 5, -5, 5])\n fig.canvas.draw()\n\n with pytest.raises(RuntimeError):\n im.make_image(fig.canvas.get_renderer())\n\n\ndef test_imshow_float16():\n fig, ax = plt.subplots()\n ax.imshow(np.zeros((3, 3), dtype=np.float16))\n # Ensure that drawing doesn't cause crash.\n fig.canvas.draw()\n\n\ndef test_imshow_float128():\n fig, ax = plt.subplots()\n ax.imshow(np.zeros((3, 3), dtype=np.longdouble))\n with (ExitStack() if np.can_cast(np.longdouble, np.float64, "equiv")\n else pytest.warns(UserWarning)):\n # Ensure that drawing doesn't cause crash.\n fig.canvas.draw()\n\n\ndef test_imshow_bool():\n fig, ax = plt.subplots()\n ax.imshow(np.array([[True, False], [False, True]], dtype=bool))\n\n\ndef test_full_invalid():\n fig, ax = plt.subplots()\n ax.imshow(np.full((10, 10), np.nan))\n\n fig.canvas.draw()\n\n\n@pytest.mark.parametrize("fmt,counted",\n [("ps", b" colorimage"), ("svg", b"<image")])\n@pytest.mark.parametrize("composite_image,count", [(True, 1), (False, 2)])\ndef test_composite(fmt, counted, composite_image, count):\n # Test that figures can be saved with and without combining multiple images\n # (on a single set of axes) into a single composite image.\n X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1))\n Z = np.sin(Y ** 2)\n\n fig, ax = plt.subplots()\n ax.set_xlim(0, 3)\n ax.imshow(Z, extent=[0, 1, 0, 1])\n ax.imshow(Z[::-1], extent=[2, 3, 0, 1])\n plt.rcParams['image.composite_image'] = composite_image\n buf = io.BytesIO()\n fig.savefig(buf, format=fmt)\n assert buf.getvalue().count(counted) == count\n\n\ndef test_relim():\n fig, ax = plt.subplots()\n ax.imshow([[0]], extent=(0, 1, 0, 1))\n ax.relim()\n ax.autoscale()\n assert ax.get_xlim() == ax.get_ylim() == (0, 1)\n\n\ndef test_unclipped():\n fig, ax = plt.subplots()\n ax.set_axis_off()\n im = ax.imshow([[0, 0], [0, 0]], aspect="auto", extent=(-10, 10, -10, 10),\n cmap='gray', clip_on=False)\n ax.set(xlim=(0, 1), ylim=(0, 1))\n fig.canvas.draw()\n # The unclipped image should fill the *entire* figure and be black.\n # Ignore alpha for this comparison.\n assert (np.array(fig.canvas.buffer_rgba())[..., :3] == 0).all()\n\n\ndef test_respects_bbox():\n fig, axs = plt.subplots(2)\n for ax in axs:\n ax.set_axis_off()\n im = axs[1].imshow([[0, 1], [2, 3]], aspect="auto", extent=(0, 1, 0, 1))\n im.set_clip_path(None)\n # Make the image invisible in axs[1], but visible in axs[0] if we pan\n # axs[1] up.\n im.set_clip_box(axs[0].bbox)\n buf_before = io.BytesIO()\n fig.savefig(buf_before, format="rgba")\n assert {*buf_before.getvalue()} == {0xff} # All white.\n axs[1].set(ylim=(-1, 0))\n buf_after = io.BytesIO()\n fig.savefig(buf_after, format="rgba")\n assert buf_before.getvalue() != buf_after.getvalue() # Not all white.\n\n\ndef test_image_cursor_formatting():\n fig, ax = plt.subplots()\n # Create a dummy image to be able to call format_cursor_data\n im = ax.imshow(np.zeros((4, 4)))\n\n data = np.ma.masked_array([0], mask=[True])\n assert im.format_cursor_data(data) == '[]'\n\n data = np.ma.masked_array([0], mask=[False])\n assert im.format_cursor_data(data) == '[0]'\n\n data = np.nan\n assert im.format_cursor_data(data) == '[nan]'\n\n\n@check_figures_equal()\ndef test_image_array_alpha(fig_test, fig_ref):\n """Per-pixel alpha channel test."""\n x = np.linspace(0, 1)\n xx, yy = np.meshgrid(x, x)\n\n zz = np.exp(- 3 * ((xx - 0.5) ** 2) + (yy - 0.7 ** 2))\n alpha = zz / zz.max()\n\n cmap = mpl.colormaps['viridis']\n ax = fig_test.add_subplot()\n ax.imshow(zz, alpha=alpha, cmap=cmap, interpolation='nearest')\n\n ax = fig_ref.add_subplot()\n rgba = cmap(colors.Normalize()(zz))\n rgba[..., -1] = alpha\n ax.imshow(rgba, interpolation='nearest')\n\n\ndef test_image_array_alpha_validation():\n with pytest.raises(TypeError, match="alpha must be a float, two-d"):\n plt.imshow(np.zeros((2, 2)), alpha=[1, 1])\n\n\n@mpl.style.context('mpl20')\ndef test_exact_vmin():\n cmap = copy(mpl.colormaps["autumn_r"])\n cmap.set_under(color="lightgrey")\n\n # make the image exactly 190 pixels wide\n fig = plt.figure(figsize=(1.9, 0.1), dpi=100)\n ax = fig.add_axes([0, 0, 1, 1])\n\n data = np.array(\n [[-1, -1, -1, 0, 0, 0, 0, 43, 79, 95, 66, 1, -1, -1, -1, 0, 0, 0, 34]],\n dtype=float,\n )\n\n im = ax.imshow(data, aspect="auto", cmap=cmap, vmin=0, vmax=100)\n ax.axis("off")\n fig.canvas.draw()\n\n # get the RGBA slice from the image\n from_image = im.make_image(fig.canvas.renderer)[0][0]\n # expand the input to be 190 long and run through norm / cmap\n direct_computation = (\n im.cmap(im.norm((data * ([[1]] * 10)).T.ravel())) * 255\n ).astype(int)\n\n # check than the RBGA values are the same\n assert np.all(from_image == direct_computation)\n\n\n@image_comparison(['image_placement'], extensions=['svg', 'pdf'],\n remove_text=True, style='mpl20')\ndef test_image_placement():\n """\n The red box should line up exactly with the outside of the image.\n """\n fig, ax = plt.subplots()\n ax.plot([0, 0, 1, 1, 0], [0, 1, 1, 0, 0], color='r', lw=0.1)\n np.random.seed(19680801)\n ax.imshow(np.random.randn(16, 16), cmap='Blues', extent=(0, 1, 0, 1),\n interpolation='none', vmin=-1, vmax=1)\n ax.set_xlim(-0.1, 1+0.1)\n ax.set_ylim(-0.1, 1+0.1)\n\n\n# A basic ndarray subclass that implements a quantity\n# It does not implement an entire unit system or all quantity math.\n# There is just enough implemented to test handling of ndarray\n# subclasses.\nclass QuantityND(np.ndarray):\n def __new__(cls, input_array, units):\n obj = np.asarray(input_array).view(cls)\n obj.units = units\n return obj\n\n def __array_finalize__(self, obj):\n self.units = getattr(obj, "units", None)\n\n def __getitem__(self, item):\n units = getattr(self, "units", None)\n ret = super().__getitem__(item)\n if isinstance(ret, QuantityND) or units is not None:\n ret = QuantityND(ret, units)\n return ret\n\n def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):\n func = getattr(ufunc, method)\n if "out" in kwargs:\n return NotImplemented\n if len(inputs) == 1:\n i0 = inputs[0]\n unit = getattr(i0, "units", "dimensionless")\n out_arr = func(np.asarray(i0), **kwargs)\n elif len(inputs) == 2:\n i0 = inputs[0]\n i1 = inputs[1]\n u0 = getattr(i0, "units", "dimensionless")\n u1 = getattr(i1, "units", "dimensionless")\n u0 = u1 if u0 is None else u0\n u1 = u0 if u1 is None else u1\n if ufunc in [np.add, np.subtract]:\n if u0 != u1:\n raise ValueError\n unit = u0\n elif ufunc == np.multiply:\n unit = f"{u0}*{u1}"\n elif ufunc == np.divide:\n unit = f"{u0}/({u1})"\n elif ufunc in (np.greater, np.greater_equal,\n np.equal, np.not_equal,\n np.less, np.less_equal):\n # Comparisons produce unitless booleans for output\n unit = None\n else:\n return NotImplemented\n out_arr = func(i0.view(np.ndarray), i1.view(np.ndarray), **kwargs)\n else:\n return NotImplemented\n if unit is None:\n out_arr = np.array(out_arr)\n else:\n out_arr = QuantityND(out_arr, unit)\n return out_arr\n\n @property\n def v(self):\n return self.view(np.ndarray)\n\n\ndef test_quantitynd():\n q = QuantityND([1, 2], "m")\n q0, q1 = q[:]\n assert np.all(q.v == np.asarray([1, 2]))\n assert q.units == "m"\n assert np.all((q0 + q1).v == np.asarray([3]))\n assert (q0 * q1).units == "m*m"\n assert (q1 / q0).units == "m/(m)"\n with pytest.raises(ValueError):\n q0 + QuantityND(1, "s")\n\n\ndef test_imshow_quantitynd():\n # generate a dummy ndarray subclass\n arr = QuantityND(np.ones((2, 2)), "m")\n fig, ax = plt.subplots()\n ax.imshow(arr)\n # executing the draw should not raise an exception\n fig.canvas.draw()\n\n\n@check_figures_equal(extensions=['png'])\ndef test_norm_change(fig_test, fig_ref):\n # LogNorm should not mask anything invalid permanently.\n data = np.full((5, 5), 1, dtype=np.float64)\n data[0:2, :] = -1\n\n masked_data = np.ma.array(data, mask=False)\n masked_data.mask[0:2, 0:2] = True\n\n cmap = mpl.colormaps['viridis'].with_extremes(under='w')\n\n ax = fig_test.subplots()\n im = ax.imshow(data, norm=colors.LogNorm(vmin=0.5, vmax=1),\n extent=(0, 5, 0, 5), interpolation='nearest', cmap=cmap)\n im.set_norm(colors.Normalize(vmin=-2, vmax=2))\n im = ax.imshow(masked_data, norm=colors.LogNorm(vmin=0.5, vmax=1),\n extent=(5, 10, 5, 10), interpolation='nearest', cmap=cmap)\n im.set_norm(colors.Normalize(vmin=-2, vmax=2))\n ax.set(xlim=(0, 10), ylim=(0, 10))\n\n ax = fig_ref.subplots()\n ax.imshow(data, norm=colors.Normalize(vmin=-2, vmax=2),\n extent=(0, 5, 0, 5), interpolation='nearest', cmap=cmap)\n ax.imshow(masked_data, norm=colors.Normalize(vmin=-2, vmax=2),\n extent=(5, 10, 5, 10), interpolation='nearest', cmap=cmap)\n ax.set(xlim=(0, 10), ylim=(0, 10))\n\n\n@pytest.mark.parametrize('x', [-1, 1])\n@check_figures_equal(extensions=['png'])\ndef test_huge_range_log(fig_test, fig_ref, x):\n # parametrize over bad lognorm -1 values and large range 1 -> 1e20\n data = np.full((5, 5), x, dtype=np.float64)\n data[0:2, :] = 1E20\n\n ax = fig_test.subplots()\n ax.imshow(data, norm=colors.LogNorm(vmin=1, vmax=data.max()),\n interpolation='nearest', cmap='viridis')\n\n data = np.full((5, 5), x, dtype=np.float64)\n data[0:2, :] = 1000\n\n ax = fig_ref.subplots()\n cmap = mpl.colormaps['viridis'].with_extremes(under='w')\n ax.imshow(data, norm=colors.Normalize(vmin=1, vmax=data.max()),\n interpolation='nearest', cmap=cmap)\n\n\n@check_figures_equal(extensions=['png'])\ndef test_spy_box(fig_test, fig_ref):\n # setting up reference and test\n ax_test = fig_test.subplots(1, 3)\n ax_ref = fig_ref.subplots(1, 3)\n\n plot_data = (\n [[1, 1], [1, 1]],\n [[0, 0], [0, 0]],\n [[0, 1], [1, 0]],\n )\n plot_titles = ["ones", "zeros", "mixed"]\n\n for i, (z, title) in enumerate(zip(plot_data, plot_titles)):\n ax_test[i].set_title(title)\n ax_test[i].spy(z)\n ax_ref[i].set_title(title)\n ax_ref[i].imshow(z, interpolation='nearest',\n aspect='equal', origin='upper', cmap='Greys',\n vmin=0, vmax=1)\n ax_ref[i].set_xlim(-0.5, 1.5)\n ax_ref[i].set_ylim(1.5, -0.5)\n ax_ref[i].xaxis.tick_top()\n ax_ref[i].title.set_y(1.05)\n ax_ref[i].xaxis.set_ticks_position('both')\n ax_ref[i].xaxis.set_major_locator(\n mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)\n )\n ax_ref[i].yaxis.set_major_locator(\n mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)\n )\n\n\n@image_comparison(["nonuniform_and_pcolor.png"], style="mpl20")\ndef test_nonuniform_and_pcolor():\n axs = plt.figure(figsize=(3, 3)).subplots(3, sharex=True, sharey=True)\n for ax, interpolation in zip(axs, ["nearest", "bilinear"]):\n im = NonUniformImage(ax, interpolation=interpolation)\n im.set_data(np.arange(3) ** 2, np.arange(3) ** 2,\n np.arange(9).reshape((3, 3)))\n ax.add_image(im)\n axs[2].pcolorfast( # PcolorImage\n np.arange(4) ** 2, np.arange(4) ** 2, np.arange(9).reshape((3, 3)))\n for ax in axs:\n ax.set_axis_off()\n # NonUniformImage "leaks" out of extents, not PColorImage.\n ax.set(xlim=(0, 10))\n\n\n@image_comparison(["nonuniform_logscale.png"], style="mpl20")\ndef test_nonuniform_logscale():\n _, axs = plt.subplots(ncols=3, nrows=1)\n\n for i in range(3):\n ax = axs[i]\n im = NonUniformImage(ax)\n im.set_data(np.arange(1, 4) ** 2, np.arange(1, 4) ** 2,\n np.arange(9).reshape((3, 3)))\n ax.set_xlim(1, 16)\n ax.set_ylim(1, 16)\n ax.set_box_aspect(1)\n if i == 1:\n ax.set_xscale("log", base=2)\n ax.set_yscale("log", base=2)\n if i == 2:\n ax.set_xscale("log", base=4)\n ax.set_yscale("log", base=4)\n ax.add_image(im)\n\n\n@image_comparison(['rgba_antialias.png'], style='mpl20', remove_text=True, tol=0.02)\ndef test_rgba_antialias():\n fig, axs = plt.subplots(2, 2, figsize=(3.5, 3.5), sharex=False,\n sharey=False, constrained_layout=True)\n N = 250\n aa = np.ones((N, N))\n aa[::2, :] = -1\n\n x = np.arange(N) / N - 0.5\n y = np.arange(N) / N - 0.5\n\n X, Y = np.meshgrid(x, y)\n R = np.sqrt(X**2 + Y**2)\n f0 = 10\n k = 75\n # aliased concentric circles\n a = np.sin(np.pi * 2 * (f0 * R + k * R**2 / 2))\n\n # stripes on lhs\n a[:int(N/2), :][R[:int(N/2), :] < 0.4] = -1\n a[:int(N/2), :][R[:int(N/2), :] < 0.3] = 1\n aa[:, int(N/2):] = a[:, int(N/2):]\n\n # set some over/unders and NaNs\n aa[20:50, 20:50] = np.nan\n aa[70:90, 70:90] = 1e6\n aa[70:90, 20:30] = -1e6\n aa[70:90, 195:215] = 1e6\n aa[20:30, 195:215] = -1e6\n\n cmap = copy(plt.cm.RdBu_r)\n cmap.set_over('yellow')\n cmap.set_under('cyan')\n\n axs = axs.flatten()\n # zoom in\n axs[0].imshow(aa, interpolation='nearest', cmap=cmap, vmin=-1.2, vmax=1.2)\n axs[0].set_xlim([N/2-25, N/2+25])\n axs[0].set_ylim([N/2+50, N/2-10])\n\n # no anti-alias\n axs[1].imshow(aa, interpolation='nearest', cmap=cmap, vmin=-1.2, vmax=1.2)\n\n # data antialias: Note no purples, and white in circle. Note\n # that alternating red and blue stripes become white.\n axs[2].imshow(aa, interpolation='auto', interpolation_stage='data',\n cmap=cmap, vmin=-1.2, vmax=1.2)\n\n # rgba antialias: Note purples at boundary with circle. Note that\n # alternating red and blue stripes become purple\n axs[3].imshow(aa, interpolation='auto', interpolation_stage='rgba',\n cmap=cmap, vmin=-1.2, vmax=1.2)\n\n\n@check_figures_equal(extensions=('png', ))\ndef test_upsample_interpolation_stage(fig_test, fig_ref):\n """\n Show that interpolation_stage='auto' gives the same as 'data'\n for upsampling.\n """\n # Fixing random state for reproducibility. This non-standard seed\n # gives red splotches for 'rgba'.\n np.random.seed(19680801+9)\n\n grid = np.random.rand(4, 4)\n ax = fig_ref.subplots()\n ax.imshow(grid, interpolation='bilinear', cmap='viridis',\n interpolation_stage='data')\n\n ax = fig_test.subplots()\n ax.imshow(grid, interpolation='bilinear', cmap='viridis',\n interpolation_stage='auto')\n\n\n@check_figures_equal(extensions=('png', ))\ndef test_downsample_interpolation_stage(fig_test, fig_ref):\n """\n Show that interpolation_stage='auto' gives the same as 'rgba'\n for downsampling.\n """\n # Fixing random state for reproducibility\n np.random.seed(19680801)\n\n grid = np.random.rand(4000, 4000)\n ax = fig_ref.subplots()\n ax.imshow(grid, interpolation='auto', cmap='viridis',\n interpolation_stage='rgba')\n\n ax = fig_test.subplots()\n ax.imshow(grid, interpolation='auto', cmap='viridis',\n interpolation_stage='auto')\n\n\ndef test_rc_interpolation_stage():\n for val in ["data", "rgba"]:\n with mpl.rc_context({"image.interpolation_stage": val}):\n assert plt.imshow([[1, 2]]).get_interpolation_stage() == val\n for val in ["DATA", "foo", None]:\n with pytest.raises(ValueError):\n mpl.rcParams["image.interpolation_stage"] = val\n\n\n# We check for the warning with a draw() in the test, but we also need to\n# filter the warning as it is emitted by the figure test decorator\n@pytest.mark.filterwarnings(r'ignore:Data with more than .* '\n 'cannot be accurately displayed')\n@pytest.mark.parametrize('origin', ['upper', 'lower'])\n@pytest.mark.parametrize(\n 'dim, size, msg', [['row', 2**23, r'2\*\*23 columns'],\n ['col', 2**24, r'2\*\*24 rows']])\n@check_figures_equal(extensions=('png', ))\ndef test_large_image(fig_test, fig_ref, dim, size, msg, origin):\n # Check that Matplotlib downsamples images that are too big for AGG\n # See issue #19276. Currently the fix only works for png output but not\n # pdf or svg output.\n ax_test = fig_test.subplots()\n ax_ref = fig_ref.subplots()\n\n array = np.zeros((1, size + 2))\n array[:, array.size // 2:] = 1\n if dim == 'col':\n array = array.T\n im = ax_test.imshow(array, vmin=0, vmax=1,\n aspect='auto', extent=(0, 1, 0, 1),\n interpolation='none',\n origin=origin)\n\n with pytest.warns(UserWarning,\n match=f'Data with more than {msg} cannot be '\n 'accurately displayed.'):\n fig_test.canvas.draw()\n\n array = np.zeros((1, 2))\n array[:, 1] = 1\n if dim == 'col':\n array = array.T\n im = ax_ref.imshow(array, vmin=0, vmax=1, aspect='auto',\n extent=(0, 1, 0, 1),\n interpolation='none',\n origin=origin)\n\n\n@check_figures_equal(extensions=["png"])\ndef test_str_norms(fig_test, fig_ref):\n t = np.random.rand(10, 10) * .8 + .1 # between 0 and 1\n axts = fig_test.subplots(1, 5)\n axts[0].imshow(t, norm="log")\n axts[1].imshow(t, norm="log", vmin=.2)\n axts[2].imshow(t, norm="symlog")\n axts[3].imshow(t, norm="symlog", vmin=.3, vmax=.7)\n axts[4].imshow(t, norm="logit", vmin=.3, vmax=.7)\n axrs = fig_ref.subplots(1, 5)\n axrs[0].imshow(t, norm=colors.LogNorm())\n axrs[1].imshow(t, norm=colors.LogNorm(vmin=.2))\n # same linthresh as SymmetricalLogScale's default.\n axrs[2].imshow(t, norm=colors.SymLogNorm(linthresh=2))\n axrs[3].imshow(t, norm=colors.SymLogNorm(linthresh=2, vmin=.3, vmax=.7))\n axrs[4].imshow(t, norm="logit", clim=(.3, .7))\n\n assert type(axts[0].images[0].norm) is colors.LogNorm # Exactly that class\n with pytest.raises(ValueError):\n axts[0].imshow(t, norm="foobar")\n\n\ndef test__resample_valid_output():\n resample = functools.partial(mpl._image.resample, transform=Affine2D())\n with pytest.raises(TypeError, match="incompatible function arguments"):\n resample(np.zeros((9, 9)), None)\n with pytest.raises(ValueError, match="different dimensionalities"):\n resample(np.zeros((9, 9)), np.zeros((9, 9, 4)))\n with pytest.raises(ValueError, match="different dimensionalities"):\n resample(np.zeros((9, 9, 4)), np.zeros((9, 9)))\n with pytest.raises(ValueError, match="3D input array must be RGBA"):\n resample(np.zeros((9, 9, 3)), np.zeros((9, 9, 4)))\n with pytest.raises(ValueError, match="3D output array must be RGBA"):\n resample(np.zeros((9, 9, 4)), np.zeros((9, 9, 3)))\n with pytest.raises(ValueError, match="mismatched types"):\n resample(np.zeros((9, 9), np.uint8), np.zeros((9, 9)))\n with pytest.raises(ValueError, match="must be C-contiguous"):\n resample(np.zeros((9, 9)), np.zeros((9, 9)).T)\n\n out = np.zeros((9, 9))\n out.flags.writeable = False\n with pytest.raises(ValueError, match="Output array must be writeable"):\n resample(np.zeros((9, 9)), out)\n\n\ndef test_axesimage_get_shape():\n # generate dummy image to test get_shape method\n ax = plt.gca()\n im = AxesImage(ax)\n with pytest.raises(RuntimeError, match="You must first set the image array"):\n im.get_shape()\n z = np.arange(12, dtype=float).reshape((4, 3))\n im.set_data(z)\n assert im.get_shape() == (4, 3)\n assert im.get_size() == im.get_shape()\n\n\ndef test_non_transdata_image_does_not_touch_aspect():\n ax = plt.figure().add_subplot()\n im = np.arange(4).reshape((2, 2))\n ax.imshow(im, transform=ax.transAxes)\n assert ax.get_aspect() == "auto"\n ax.imshow(im, transform=Affine2D().scale(2) + ax.transData)\n assert ax.get_aspect() == 1\n ax.imshow(im, transform=ax.transAxes, aspect=2)\n assert ax.get_aspect() == 2\n\n\n@image_comparison(\n ['downsampling.png'], style='mpl20', remove_text=True, tol=0.09)\ndef test_downsampling():\n N = 450\n x = np.arange(N) / N - 0.5\n y = np.arange(N) / N - 0.5\n aa = np.ones((N, N))\n aa[::2, :] = -1\n\n X, Y = np.meshgrid(x, y)\n R = np.sqrt(X**2 + Y**2)\n f0 = 5\n k = 100\n a = np.sin(np.pi * 2 * (f0 * R + k * R**2 / 2))\n # make the left hand side of this\n a[:int(N / 2), :][R[:int(N / 2), :] < 0.4] = -1\n a[:int(N / 2), :][R[:int(N / 2), :] < 0.3] = 1\n aa[:, int(N / 3):] = a[:, int(N / 3):]\n a = aa\n\n fig, axs = plt.subplots(2, 3, figsize=(7, 6), layout='compressed')\n axs[0, 0].imshow(a, interpolation='nearest', interpolation_stage='rgba',\n cmap='RdBu_r')\n axs[0, 0].set_xlim(125, 175)\n axs[0, 0].set_ylim(250, 200)\n axs[0, 0].set_title('Zoom')\n\n for ax, interp, space in zip(axs.flat[1:], ['nearest', 'nearest', 'hanning',\n 'hanning', 'auto'],\n ['data', 'rgba', 'data', 'rgba', 'auto']):\n ax.imshow(a, interpolation=interp, interpolation_stage=space,\n cmap='RdBu_r')\n ax.set_title(f"interpolation='{interp}'\nspace='{space}'")\n\n\n@image_comparison(\n ['downsampling_speckle.png'], style='mpl20', remove_text=True, tol=0.09)\ndef test_downsampling_speckle():\n fig, axs = plt.subplots(1, 2, figsize=(5, 2.7), sharex=True, sharey=True,\n layout="compressed")\n axs = axs.flatten()\n img = ((np.arange(1024).reshape(-1, 1) * np.ones(720)) // 50).T\n\n cm = plt.get_cmap("viridis")\n cm.set_over("m")\n norm = colors.LogNorm(vmin=3, vmax=11)\n\n # old default cannot be tested because it creates over/under speckles\n # in the following that are machine dependent.\n\n axs[0].set_title("interpolation='auto', stage='rgba'")\n axs[0].imshow(np.triu(img), cmap=cm, norm=norm, interpolation_stage='rgba')\n\n # Should be same as previous\n axs[1].set_title("interpolation='auto', stage='auto'")\n axs[1].imshow(np.triu(img), cmap=cm, norm=norm)\n\n\n@image_comparison(\n ['upsampling.png'], style='mpl20', remove_text=True)\ndef test_upsampling():\n\n np.random.seed(19680801+9) # need this seed to get yellow next to blue\n a = np.random.rand(4, 4)\n\n fig, axs = plt.subplots(1, 3, figsize=(6.5, 3), layout='compressed')\n im = axs[0].imshow(a, cmap='viridis')\n axs[0].set_title(\n "interpolation='auto'\nstage='antialaised'\n(default for upsampling)")\n\n # probably what people want:\n axs[1].imshow(a, cmap='viridis', interpolation='sinc')\n axs[1].set_title(\n "interpolation='sinc'\nstage='auto'\n(default for upsampling)")\n\n # probably not what people want:\n axs[2].imshow(a, cmap='viridis', interpolation='sinc', interpolation_stage='rgba')\n axs[2].set_title("interpolation='sinc'\nstage='rgba'")\n fig.colorbar(im, ax=axs, shrink=0.7, extend='both')\n\n\n@pytest.mark.parametrize(\n 'dtype',\n ('float64', 'float32', 'int16', 'uint16', 'int8', 'uint8'),\n)\n@pytest.mark.parametrize('ndim', (2, 3))\ndef test_resample_dtypes(dtype, ndim):\n # Issue 28448, incorrect dtype comparisons in C++ image_resample can raise\n # ValueError: arrays must be of dtype byte, short, float32 or float64\n rng = np.random.default_rng(4181)\n shape = (2, 2) if ndim == 2 else (2, 2, 3)\n data = rng.uniform(size=shape).astype(np.dtype(dtype, copy=True))\n fig, ax = plt.subplots()\n axes_image = ax.imshow(data)\n # Before fix the following raises ValueError for some dtypes.\n axes_image.make_image(None)[0]\n\n\n@pytest.mark.parametrize('intp_stage', ('data', 'rgba'))\n@check_figures_equal()\ndef test_interpolation_stage_rgba_respects_alpha_param(fig_test, fig_ref, intp_stage):\n axs_tst = fig_test.subplots(2, 3)\n axs_ref = fig_ref.subplots(2, 3)\n ny, nx = 3, 3\n scalar_alpha = 0.5\n array_alpha = np.random.rand(ny, nx)\n\n # When the image does not have an alpha channel, alpha should be specified\n # by the user or default to 1.0\n im_rgb = np.random.rand(ny, nx, 3)\n im_concat_default_a = np.ones((ny, nx, 1)) # alpha defaults to 1.0\n im_rgba = np.concatenate( # combine rgb channels with array alpha\n (im_rgb, array_alpha.reshape((ny, nx, 1))), axis=-1\n )\n axs_tst[0][0].imshow(im_rgb)\n axs_ref[0][0].imshow(np.concatenate((im_rgb, im_concat_default_a), axis=-1))\n axs_tst[0][1].imshow(im_rgb, interpolation_stage=intp_stage, alpha=scalar_alpha)\n axs_ref[0][1].imshow(\n np.concatenate( # combine rgb channels with broadcasted scalar alpha\n (im_rgb, scalar_alpha * im_concat_default_a), axis=-1\n ), interpolation_stage=intp_stage\n )\n axs_tst[0][2].imshow(im_rgb, interpolation_stage=intp_stage, alpha=array_alpha)\n axs_ref[0][2].imshow(im_rgba, interpolation_stage=intp_stage)\n\n # When the image already has an alpha channel, multiply it by the\n # scalar alpha param, or replace it by the array alpha param\n axs_tst[1][0].imshow(im_rgba)\n axs_ref[1][0].imshow(im_rgb, alpha=array_alpha)\n axs_tst[1][1].imshow(im_rgba, interpolation_stage=intp_stage, alpha=scalar_alpha)\n axs_ref[1][1].imshow(\n np.concatenate( # combine rgb channels with scaled array alpha\n (im_rgb, scalar_alpha * array_alpha.reshape((ny, nx, 1))), axis=-1\n ), interpolation_stage=intp_stage\n )\n new_array_alpha = np.random.rand(ny, nx)\n axs_tst[1][2].imshow(im_rgba, interpolation_stage=intp_stage, alpha=new_array_alpha)\n axs_ref[1][2].imshow(\n np.concatenate( # combine rgb channels with new array alpha\n (im_rgb, new_array_alpha.reshape((ny, nx, 1))), axis=-1\n ), interpolation_stage=intp_stage\n )\n | .venv\Lib\site-packages\matplotlib\tests\test_image.py | test_image.py | Python | 59,562 | 0.75 | 0.094891 | 0.093927 | vue-tools | 241 | 2023-07-28T11:00:41.308111 | MIT | true | 86d134fbd598a19bf1a02510a278b4b7 |
import collections\nimport io\nimport itertools\nimport platform\nimport time\nfrom unittest import mock\nimport warnings\n\nimport numpy as np\nfrom numpy.testing import assert_allclose\nimport pytest\n\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\nfrom matplotlib.testing._markers import needs_usetex\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport matplotlib.patches as mpatches\nimport matplotlib.transforms as mtransforms\nimport matplotlib.collections as mcollections\nimport matplotlib.lines as mlines\nfrom matplotlib.legend_handler import HandlerTuple\nimport matplotlib.legend as mlegend\nfrom matplotlib import rc_context\nfrom matplotlib.font_manager import FontProperties\n\n\ndef test_legend_ordereddict():\n # smoketest that ordereddict inputs work...\n\n X = np.random.randn(10)\n Y = np.random.randn(10)\n labels = ['a'] * 5 + ['b'] * 5\n colors = ['r'] * 5 + ['g'] * 5\n\n fig, ax = plt.subplots()\n for x, y, label, color in zip(X, Y, labels, colors):\n ax.scatter(x, y, label=label, c=color)\n\n handles, labels = ax.get_legend_handles_labels()\n legend = collections.OrderedDict(zip(labels, handles))\n ax.legend(legend.values(), legend.keys(),\n loc='center left', bbox_to_anchor=(1, .5))\n\n\n@image_comparison(['legend_auto1.png'], remove_text=True)\ndef test_legend_auto1():\n """Test automatic legend placement"""\n fig, ax = plt.subplots()\n x = np.arange(100)\n ax.plot(x, 50 - x, 'o', label='y=1')\n ax.plot(x, x - 50, 'o', label='y=-1')\n ax.legend(loc='best')\n\n\n@image_comparison(['legend_auto2.png'], remove_text=True)\ndef test_legend_auto2():\n """Test automatic legend placement"""\n fig, ax = plt.subplots()\n x = np.arange(100)\n b1 = ax.bar(x, x, align='edge', color='m')\n b2 = ax.bar(x, x[::-1], align='edge', color='g')\n ax.legend([b1[0], b2[0]], ['up', 'down'], loc='best')\n\n\n@image_comparison(['legend_auto3.png'])\ndef test_legend_auto3():\n """Test automatic legend placement"""\n fig, ax = plt.subplots()\n x = [0.9, 0.1, 0.1, 0.9, 0.9, 0.5]\n y = [0.95, 0.95, 0.05, 0.05, 0.5, 0.5]\n ax.plot(x, y, 'o-', label='line')\n ax.set_xlim(0.0, 1.0)\n ax.set_ylim(0.0, 1.0)\n ax.legend(loc='best')\n\n\ndef test_legend_auto4():\n """\n Check that the legend location with automatic placement is the same,\n whatever the histogram type is. Related to issue #9580.\n """\n # NB: barstacked is pointless with a single dataset.\n fig, axs = plt.subplots(ncols=3, figsize=(6.4, 2.4))\n leg_bboxes = []\n for ax, ht in zip(axs.flat, ('bar', 'step', 'stepfilled')):\n ax.set_title(ht)\n # A high bar on the left but an even higher one on the right.\n ax.hist([0] + 5*[9], bins=range(10), label="Legend", histtype=ht)\n leg = ax.legend(loc="best")\n fig.canvas.draw()\n leg_bboxes.append(\n leg.get_window_extent().transformed(ax.transAxes.inverted()))\n\n # The histogram type "bar" is assumed to be the correct reference.\n assert_allclose(leg_bboxes[1].bounds, leg_bboxes[0].bounds)\n assert_allclose(leg_bboxes[2].bounds, leg_bboxes[0].bounds)\n\n\ndef test_legend_auto5():\n """\n Check that the automatic placement handle a rather complex\n case with non rectangular patch. Related to issue #9580.\n """\n fig, axs = plt.subplots(ncols=2, figsize=(9.6, 4.8))\n\n leg_bboxes = []\n for ax, loc in zip(axs.flat, ("center", "best")):\n # An Ellipse patch at the top, a U-shaped Polygon patch at the\n # bottom and a ring-like Wedge patch: the correct placement of\n # the legend should be in the center.\n for _patch in [\n mpatches.Ellipse(\n xy=(0.5, 0.9), width=0.8, height=0.2, fc="C1"),\n mpatches.Polygon(np.array([\n [0, 1], [0, 0], [1, 0], [1, 1], [0.9, 1.0], [0.9, 0.1],\n [0.1, 0.1], [0.1, 1.0], [0.1, 1.0]]), fc="C1"),\n mpatches.Wedge((0.5, 0.5), 0.5, 0, 360, width=0.05, fc="C0")\n ]:\n ax.add_patch(_patch)\n\n ax.plot([0.1, 0.9], [0.9, 0.9], label="A segment") # sthg to label\n\n leg = ax.legend(loc=loc)\n fig.canvas.draw()\n leg_bboxes.append(\n leg.get_window_extent().transformed(ax.transAxes.inverted()))\n\n assert_allclose(leg_bboxes[1].bounds, leg_bboxes[0].bounds)\n\n\n@image_comparison(['legend_various_labels.png'], remove_text=True)\ndef test_various_labels():\n # tests all sorts of label types\n fig = plt.figure()\n ax = fig.add_subplot(121)\n ax.plot(np.arange(4), 'o', label=1)\n ax.plot(np.linspace(4, 4.1), 'o', label='Développés')\n ax.plot(np.arange(4, 1, -1), 'o', label='__nolegend__')\n ax.legend(numpoints=1, loc='best')\n\n\n@image_comparison(['legend_labels_first.png'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.013)\ndef test_labels_first():\n # test labels to left of markers\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), '-o', label=1)\n ax.plot(np.ones(10)*5, ':x', label="x")\n ax.plot(np.arange(20, 10, -1), 'd', label="diamond")\n ax.legend(loc='best', markerfirst=False)\n\n\n@image_comparison(['legend_multiple_keys.png'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.013)\ndef test_multiple_keys():\n # test legend entries with multiple keys\n fig, ax = plt.subplots()\n p1, = ax.plot([1, 2, 3], '-o')\n p2, = ax.plot([2, 3, 4], '-x')\n p3, = ax.plot([3, 4, 5], '-d')\n ax.legend([(p1, p2), (p2, p1), p3], ['two keys', 'pad=0', 'one key'],\n numpoints=1,\n handler_map={(p1, p2): HandlerTuple(ndivide=None),\n (p2, p1): HandlerTuple(ndivide=None, pad=0)})\n\n\n@image_comparison(['rgba_alpha.png'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.03)\ndef test_alpha_rgba():\n fig, ax = plt.subplots()\n ax.plot(range(10), lw=5)\n leg = plt.legend(['Longlabel that will go away'], loc='center')\n leg.legendPatch.set_facecolor([1, 0, 0, 0.5])\n\n\n@image_comparison(['rcparam_alpha.png'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.03)\ndef test_alpha_rcparam():\n fig, ax = plt.subplots()\n ax.plot(range(10), lw=5)\n with mpl.rc_context(rc={'legend.framealpha': .75}):\n leg = plt.legend(['Longlabel that will go away'], loc='center')\n # this alpha is going to be over-ridden by the rcparam with\n # sets the alpha of the patch to be non-None which causes the alpha\n # value of the face color to be discarded. This behavior may not be\n # ideal, but it is what it is and we should keep track of it changing\n leg.legendPatch.set_facecolor([1, 0, 0, 0.5])\n\n\n@image_comparison(['fancy.png'], remove_text=True, tol=0.05)\ndef test_fancy():\n # Tolerance caused by changing default shadow "shade" from 0.3 to 1 - 0.7 =\n # 0.30000000000000004\n # using subplot triggers some offsetbox functionality untested elsewhere\n plt.subplot(121)\n plt.plot([5] * 10, 'o--', label='XX')\n plt.scatter(np.arange(10), np.arange(10, 0, -1), label='XX\nXX')\n plt.errorbar(np.arange(10), np.arange(10), xerr=0.5,\n yerr=0.5, label='XX')\n plt.legend(loc="center left", bbox_to_anchor=[1.0, 0.5],\n ncols=2, shadow=True, title="My legend", numpoints=1)\n\n\n@image_comparison(['framealpha'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.024)\ndef test_framealpha():\n x = np.linspace(1, 100, 100)\n y = x\n plt.plot(x, y, label='mylabel', lw=10)\n plt.legend(framealpha=0.5)\n\n\n@image_comparison(['scatter_rc3.png', 'scatter_rc1.png'], remove_text=True)\ndef test_rc():\n # using subplot triggers some offsetbox functionality untested elsewhere\n plt.figure()\n ax = plt.subplot(121)\n ax.scatter(np.arange(10), np.arange(10, 0, -1), label='three')\n ax.legend(loc="center left", bbox_to_anchor=[1.0, 0.5],\n title="My legend")\n\n mpl.rcParams['legend.scatterpoints'] = 1\n plt.figure()\n ax = plt.subplot(121)\n ax.scatter(np.arange(10), np.arange(10, 0, -1), label='one')\n ax.legend(loc="center left", bbox_to_anchor=[1.0, 0.5],\n title="My legend")\n\n\n@image_comparison(['legend_expand.png'], remove_text=True)\ndef test_legend_expand():\n """Test expand mode"""\n legend_modes = [None, "expand"]\n fig, axs = plt.subplots(len(legend_modes), 1)\n x = np.arange(100)\n for ax, mode in zip(axs, legend_modes):\n ax.plot(x, 50 - x, 'o', label='y=1')\n l1 = ax.legend(loc='upper left', mode=mode)\n ax.add_artist(l1)\n ax.plot(x, x - 50, 'o', label='y=-1')\n l2 = ax.legend(loc='right', mode=mode)\n ax.add_artist(l2)\n ax.legend(loc='lower left', mode=mode, ncols=2)\n\n\n@image_comparison(['hatching'], remove_text=True, style='default')\ndef test_hatching():\n # Remove legend texts when this image is regenerated.\n # Remove this line when this test image is regenerated.\n plt.rcParams['text.kerning_factor'] = 6\n\n fig, ax = plt.subplots()\n\n # Patches\n patch = plt.Rectangle((0, 0), 0.3, 0.3, hatch='xx',\n label='Patch\ndefault color\nfilled')\n ax.add_patch(patch)\n patch = plt.Rectangle((0.33, 0), 0.3, 0.3, hatch='||', edgecolor='C1',\n label='Patch\nexplicit color\nfilled')\n ax.add_patch(patch)\n patch = plt.Rectangle((0, 0.4), 0.3, 0.3, hatch='xx', fill=False,\n label='Patch\ndefault color\nunfilled')\n ax.add_patch(patch)\n patch = plt.Rectangle((0.33, 0.4), 0.3, 0.3, hatch='||', fill=False,\n edgecolor='C1',\n label='Patch\nexplicit color\nunfilled')\n ax.add_patch(patch)\n\n # Paths\n ax.fill_between([0, .15, .3], [.8, .8, .8], [.9, 1.0, .9],\n hatch='+', label='Path\ndefault color')\n ax.fill_between([.33, .48, .63], [.8, .8, .8], [.9, 1.0, .9],\n hatch='+', edgecolor='C2', label='Path\nexplicit color')\n\n ax.set_xlim(-0.01, 1.1)\n ax.set_ylim(-0.01, 1.1)\n ax.legend(handlelength=4, handleheight=4)\n\n\ndef test_legend_remove():\n fig, ax = plt.subplots()\n lines = ax.plot(range(10))\n leg = fig.legend(lines, "test")\n leg.remove()\n assert fig.legends == []\n leg = ax.legend("test")\n leg.remove()\n assert ax.get_legend() is None\n\n\ndef test_reverse_legend_handles_and_labels():\n """Check that the legend handles and labels are reversed."""\n fig, ax = plt.subplots()\n x = 1\n y = 1\n labels = ["First label", "Second label", "Third label"]\n markers = ['.', ',', 'o']\n\n ax.plot(x, y, markers[0], label=labels[0])\n ax.plot(x, y, markers[1], label=labels[1])\n ax.plot(x, y, markers[2], label=labels[2])\n leg = ax.legend(reverse=True)\n actual_labels = [t.get_text() for t in leg.get_texts()]\n actual_markers = [h.get_marker() for h in leg.legend_handles]\n assert actual_labels == list(reversed(labels))\n assert actual_markers == list(reversed(markers))\n\n\n@check_figures_equal(extensions=["png"])\ndef test_reverse_legend_display(fig_test, fig_ref):\n """Check that the rendered legend entries are reversed"""\n ax = fig_test.subplots()\n ax.plot([1], 'ro', label="first")\n ax.plot([2], 'bx', label="second")\n ax.legend(reverse=True)\n\n ax = fig_ref.subplots()\n ax.plot([2], 'bx', label="second")\n ax.plot([1], 'ro', label="first")\n ax.legend()\n\n\nclass TestLegendFunction:\n # Tests the legend function on the Axes and pyplot.\n def test_legend_no_args(self):\n lines = plt.plot(range(10), label='hello world')\n with mock.patch('matplotlib.legend.Legend') as Legend:\n plt.legend()\n Legend.assert_called_with(plt.gca(), lines, ['hello world'])\n\n def test_legend_positional_handles_labels(self):\n lines = plt.plot(range(10))\n with mock.patch('matplotlib.legend.Legend') as Legend:\n plt.legend(lines, ['hello world'])\n Legend.assert_called_with(plt.gca(), lines, ['hello world'])\n\n def test_legend_positional_handles_only(self):\n lines = plt.plot(range(10))\n with pytest.raises(TypeError, match='but found an Artist'):\n # a single arg is interpreted as labels\n # it's a common error to just pass handles\n plt.legend(lines)\n\n def test_legend_positional_labels_only(self):\n lines = plt.plot(range(10), label='hello world')\n with mock.patch('matplotlib.legend.Legend') as Legend:\n plt.legend(['foobar'])\n Legend.assert_called_with(plt.gca(), lines, ['foobar'])\n\n def test_legend_three_args(self):\n lines = plt.plot(range(10), label='hello world')\n with mock.patch('matplotlib.legend.Legend') as Legend:\n plt.legend(lines, ['foobar'], loc='right')\n Legend.assert_called_with(plt.gca(), lines, ['foobar'], loc='right')\n\n def test_legend_handler_map(self):\n lines = plt.plot(range(10), label='hello world')\n with mock.patch('matplotlib.legend.'\n '_get_legend_handles_labels') as handles_labels:\n handles_labels.return_value = lines, ['hello world']\n plt.legend(handler_map={'1': 2})\n handles_labels.assert_called_with([plt.gca()], {'1': 2})\n\n def test_legend_kwargs_handles_only(self):\n fig, ax = plt.subplots()\n x = np.linspace(0, 1, 11)\n ln1, = ax.plot(x, x, label='x')\n ln2, = ax.plot(x, 2*x, label='2x')\n ln3, = ax.plot(x, 3*x, label='3x')\n with mock.patch('matplotlib.legend.Legend') as Legend:\n ax.legend(handles=[ln3, ln2]) # reversed and not ln1\n Legend.assert_called_with(ax, [ln3, ln2], ['3x', '2x'])\n\n def test_legend_kwargs_labels_only(self):\n fig, ax = plt.subplots()\n x = np.linspace(0, 1, 11)\n ln1, = ax.plot(x, x)\n ln2, = ax.plot(x, 2*x)\n with mock.patch('matplotlib.legend.Legend') as Legend:\n ax.legend(labels=['x', '2x'])\n Legend.assert_called_with(ax, [ln1, ln2], ['x', '2x'])\n\n def test_legend_kwargs_handles_labels(self):\n fig, ax = plt.subplots()\n th = np.linspace(0, 2*np.pi, 1024)\n lns, = ax.plot(th, np.sin(th), label='sin')\n lnc, = ax.plot(th, np.cos(th), label='cos')\n with mock.patch('matplotlib.legend.Legend') as Legend:\n # labels of lns, lnc are overwritten with explicit ('a', 'b')\n ax.legend(labels=('a', 'b'), handles=(lnc, lns))\n Legend.assert_called_with(ax, (lnc, lns), ('a', 'b'))\n\n def test_warn_mixed_args_and_kwargs(self):\n fig, ax = plt.subplots()\n th = np.linspace(0, 2*np.pi, 1024)\n lns, = ax.plot(th, np.sin(th), label='sin')\n lnc, = ax.plot(th, np.cos(th), label='cos')\n with pytest.warns(DeprecationWarning) as record:\n ax.legend((lnc, lns), labels=('a', 'b'))\n assert len(record) == 1\n assert str(record[0].message).startswith(\n "You have mixed positional and keyword arguments, some input may "\n "be discarded.")\n\n def test_parasite(self):\n from mpl_toolkits.axes_grid1 import host_subplot # type: ignore[import]\n\n host = host_subplot(111)\n par = host.twinx()\n\n p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")\n p2, = par.plot([0, 1, 2], [0, 3, 2], label="Temperature")\n\n with mock.patch('matplotlib.legend.Legend') as Legend:\n plt.legend()\n Legend.assert_called_with(host, [p1, p2], ['Density', 'Temperature'])\n\n\nclass TestLegendFigureFunction:\n # Tests the legend function for figure\n def test_legend_handle_label(self):\n fig, ax = plt.subplots()\n lines = ax.plot(range(10))\n with mock.patch('matplotlib.legend.Legend') as Legend:\n fig.legend(lines, ['hello world'])\n Legend.assert_called_with(fig, lines, ['hello world'],\n bbox_transform=fig.transFigure)\n\n def test_legend_no_args(self):\n fig, ax = plt.subplots()\n lines = ax.plot(range(10), label='hello world')\n with mock.patch('matplotlib.legend.Legend') as Legend:\n fig.legend()\n Legend.assert_called_with(fig, lines, ['hello world'],\n bbox_transform=fig.transFigure)\n\n def test_legend_label_arg(self):\n fig, ax = plt.subplots()\n lines = ax.plot(range(10))\n with mock.patch('matplotlib.legend.Legend') as Legend:\n fig.legend(['foobar'])\n Legend.assert_called_with(fig, lines, ['foobar'],\n bbox_transform=fig.transFigure)\n\n def test_legend_label_three_args(self):\n fig, ax = plt.subplots()\n lines = ax.plot(range(10))\n with pytest.raises(TypeError, match="0-2"):\n fig.legend(lines, ['foobar'], 'right')\n with pytest.raises(TypeError, match="0-2"):\n fig.legend(lines, ['foobar'], 'right', loc='left')\n\n def test_legend_kw_args(self):\n fig, axs = plt.subplots(1, 2)\n lines = axs[0].plot(range(10))\n lines2 = axs[1].plot(np.arange(10) * 2.)\n with mock.patch('matplotlib.legend.Legend') as Legend:\n fig.legend(loc='right', labels=('a', 'b'), handles=(lines, lines2))\n Legend.assert_called_with(\n fig, (lines, lines2), ('a', 'b'), loc='right',\n bbox_transform=fig.transFigure)\n\n def test_warn_args_kwargs(self):\n fig, axs = plt.subplots(1, 2)\n lines = axs[0].plot(range(10))\n lines2 = axs[1].plot(np.arange(10) * 2.)\n with pytest.warns(DeprecationWarning) as record:\n fig.legend((lines, lines2), labels=('a', 'b'))\n assert len(record) == 1\n assert str(record[0].message).startswith(\n "You have mixed positional and keyword arguments, some input may "\n "be discarded.")\n\n\ndef test_figure_legend_outside():\n todos = ['upper ' + pos for pos in ['left', 'center', 'right']]\n todos += ['lower ' + pos for pos in ['left', 'center', 'right']]\n todos += ['left ' + pos for pos in ['lower', 'center', 'upper']]\n todos += ['right ' + pos for pos in ['lower', 'center', 'upper']]\n\n upperext = [20.347556, 27.722556, 790.583, 545.499]\n lowerext = [20.347556, 71.056556, 790.583, 588.833]\n leftext = [151.681556, 27.722556, 790.583, 588.833]\n rightext = [20.347556, 27.722556, 659.249, 588.833]\n axbb = [upperext, upperext, upperext,\n lowerext, lowerext, lowerext,\n leftext, leftext, leftext,\n rightext, rightext, rightext]\n\n legbb = [[10., 555., 133., 590.], # upper left\n [338.5, 555., 461.5, 590.], # upper center\n [667, 555., 790., 590.], # upper right\n [10., 10., 133., 45.], # lower left\n [338.5, 10., 461.5, 45.], # lower center\n [667., 10., 790., 45.], # lower right\n [10., 10., 133., 45.], # left lower\n [10., 282.5, 133., 317.5], # left center\n [10., 555., 133., 590.], # left upper\n [667, 10., 790., 45.], # right lower\n [667., 282.5, 790., 317.5], # right center\n [667., 555., 790., 590.]] # right upper\n\n for nn, todo in enumerate(todos):\n print(todo)\n fig, axs = plt.subplots(constrained_layout=True, dpi=100)\n axs.plot(range(10), label='Boo1')\n leg = fig.legend(loc='outside ' + todo)\n fig.draw_without_rendering()\n\n assert_allclose(axs.get_window_extent().extents,\n axbb[nn])\n assert_allclose(leg.get_window_extent().extents,\n legbb[nn])\n\n\n@image_comparison(['legend_stackplot.png'],\n tol=0 if platform.machine() == 'x86_64' else 0.031)\ndef test_legend_stackplot():\n """Test legend for PolyCollection using stackplot."""\n # related to #1341, #1943, and PR #3303\n fig, ax = plt.subplots()\n x = np.linspace(0, 10, 10)\n y1 = 1.0 * x\n y2 = 2.0 * x + 1\n y3 = 3.0 * x + 2\n ax.stackplot(x, y1, y2, y3, labels=['y1', 'y2', 'y3'])\n ax.set_xlim((0, 10))\n ax.set_ylim((0, 70))\n ax.legend(loc='best')\n\n\ndef test_cross_figure_patch_legend():\n fig, ax = plt.subplots()\n fig2, ax2 = plt.subplots()\n\n brs = ax.bar(range(3), range(3))\n fig2.legend(brs, 'foo')\n\n\ndef test_nanscatter():\n fig, ax = plt.subplots()\n\n h = ax.scatter([np.nan], [np.nan], marker="o",\n facecolor="r", edgecolor="r", s=3)\n\n ax.legend([h], ["scatter"])\n\n fig, ax = plt.subplots()\n for color in ['red', 'green', 'blue']:\n n = 750\n x, y = np.random.rand(2, n)\n scale = 200.0 * np.random.rand(n)\n ax.scatter(x, y, c=color, s=scale, label=color,\n alpha=0.3, edgecolors='none')\n\n ax.legend()\n ax.grid(True)\n\n\ndef test_legend_repeatcheckok():\n fig, ax = plt.subplots()\n ax.scatter(0.0, 1.0, color='k', marker='o', label='test')\n ax.scatter(0.5, 0.0, color='r', marker='v', label='test')\n ax.legend()\n hand, lab = mlegend._get_legend_handles_labels([ax])\n assert len(lab) == 2\n fig, ax = plt.subplots()\n ax.scatter(0.0, 1.0, color='k', marker='o', label='test')\n ax.scatter(0.5, 0.0, color='k', marker='v', label='test')\n ax.legend()\n hand, lab = mlegend._get_legend_handles_labels([ax])\n assert len(lab) == 2\n\n\n@image_comparison(['not_covering_scatter.png'])\ndef test_not_covering_scatter():\n colors = ['b', 'g', 'r']\n\n for n in range(3):\n plt.scatter([n], [n], color=colors[n])\n\n plt.legend(['foo', 'foo', 'foo'], loc='best')\n plt.gca().set_xlim(-0.5, 2.2)\n plt.gca().set_ylim(-0.5, 2.2)\n\n\n@image_comparison(['not_covering_scatter_transform.png'])\ndef test_not_covering_scatter_transform():\n # Offsets point to top left, the default auto position\n offset = mtransforms.Affine2D().translate(-20, 20)\n x = np.linspace(0, 30, 1000)\n plt.plot(x, x)\n\n plt.scatter([20], [10], transform=offset + plt.gca().transData)\n\n plt.legend(['foo', 'bar'], loc='best')\n\n\ndef test_linecollection_scaled_dashes():\n lines1 = [[(0, .5), (.5, 1)], [(.3, .6), (.2, .2)]]\n lines2 = [[[0.7, .2], [.8, .4]], [[.5, .7], [.6, .1]]]\n lines3 = [[[0.6, .2], [.8, .4]], [[.5, .7], [.1, .1]]]\n lc1 = mcollections.LineCollection(lines1, linestyles="--", lw=3)\n lc2 = mcollections.LineCollection(lines2, linestyles="-.")\n lc3 = mcollections.LineCollection(lines3, linestyles=":", lw=.5)\n\n fig, ax = plt.subplots()\n ax.add_collection(lc1)\n ax.add_collection(lc2)\n ax.add_collection(lc3)\n\n leg = ax.legend([lc1, lc2, lc3], ["line1", "line2", 'line 3'])\n h1, h2, h3 = leg.legend_handles\n\n for oh, lh in zip((lc1, lc2, lc3), (h1, h2, h3)):\n assert oh.get_linestyles()[0] == lh._dash_pattern\n\n\ndef test_handler_numpoints():\n """Test legend handler with numpoints <= 1."""\n # related to #6921 and PR #8478\n fig, ax = plt.subplots()\n ax.plot(range(5), label='test')\n ax.legend(numpoints=0.5)\n\n\ndef test_text_nohandler_warning():\n """Test that Text artists with labels raise a warning"""\n fig, ax = plt.subplots()\n ax.plot([0], label="mock data")\n ax.text(x=0, y=0, s="text", label="label")\n with pytest.warns(UserWarning) as record:\n ax.legend()\n assert len(record) == 1\n\n # this should _not_ warn:\n f, ax = plt.subplots()\n ax.pcolormesh(np.random.uniform(0, 1, (10, 10)))\n with warnings.catch_warnings():\n warnings.simplefilter("error")\n ax.get_legend_handles_labels()\n\n\ndef test_empty_bar_chart_with_legend():\n """Test legend when bar chart is empty with a label."""\n # related to issue #13003. Calling plt.legend() should not\n # raise an IndexError.\n plt.bar([], [], label='test')\n plt.legend()\n\n\n@image_comparison(['shadow_argument_types.png'], remove_text=True, style='mpl20',\n tol=0 if platform.machine() == 'x86_64' else 0.028)\ndef test_shadow_argument_types():\n # Test that different arguments for shadow work as expected\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3], label='test')\n\n # Test various shadow configurations\n # as well as different ways of specifying colors\n legs = (ax.legend(loc='upper left', shadow=True), # True\n ax.legend(loc='upper right', shadow=False), # False\n ax.legend(loc='center left', # string\n shadow={'color': 'red', 'alpha': 0.1}),\n ax.legend(loc='center right', # tuple\n shadow={'color': (0.1, 0.2, 0.5), 'oy': -5}),\n ax.legend(loc='lower left', # tab\n shadow={'color': 'tab:cyan', 'ox': 10})\n )\n for l in legs:\n ax.add_artist(l)\n ax.legend(loc='lower right') # default\n\n\ndef test_shadow_invalid_argument():\n # Test if invalid argument to legend shadow\n # (i.e. not [color|bool]) raises ValueError\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3], label='test')\n with pytest.raises(ValueError, match="dict or bool"):\n ax.legend(loc="upper left", shadow="aardvark") # Bad argument\n\n\ndef test_shadow_framealpha():\n # Test if framealpha is activated when shadow is True\n # and framealpha is not explicitly passed'''\n fig, ax = plt.subplots()\n ax.plot(range(100), label="test")\n leg = ax.legend(shadow=True, facecolor='w')\n assert leg.get_frame().get_alpha() == 1\n\n\ndef test_legend_title_empty():\n # test that if we don't set the legend title, that\n # it comes back as an empty string, and that it is not\n # visible:\n fig, ax = plt.subplots()\n ax.plot(range(10), label="mock data")\n leg = ax.legend()\n assert leg.get_title().get_text() == ""\n assert not leg.get_title().get_visible()\n\n\ndef test_legend_proper_window_extent():\n # test that legend returns the expected extent under various dpi...\n fig, ax = plt.subplots(dpi=100)\n ax.plot(range(10), label='Aardvark')\n leg = ax.legend()\n x01 = leg.get_window_extent(fig.canvas.get_renderer()).x0\n\n fig, ax = plt.subplots(dpi=200)\n ax.plot(range(10), label='Aardvark')\n leg = ax.legend()\n x02 = leg.get_window_extent(fig.canvas.get_renderer()).x0\n assert pytest.approx(x01*2, 0.1) == x02\n\n\ndef test_window_extent_cached_renderer():\n fig, ax = plt.subplots(dpi=100)\n ax.plot(range(10), label='Aardvark')\n leg = ax.legend()\n leg2 = fig.legend()\n fig.canvas.draw()\n # check that get_window_extent will use the cached renderer\n leg.get_window_extent()\n leg2.get_window_extent()\n\n\ndef test_legend_title_fontprop_fontsize():\n # test the title_fontsize kwarg\n plt.plot(range(10), label="mock data")\n with pytest.raises(ValueError):\n plt.legend(title='Aardvark', title_fontsize=22,\n title_fontproperties={'family': 'serif', 'size': 22})\n\n leg = plt.legend(title='Aardvark', title_fontproperties=FontProperties(\n family='serif', size=22))\n assert leg.get_title().get_size() == 22\n\n fig, axes = plt.subplots(2, 3, figsize=(10, 6))\n axes = axes.flat\n axes[0].plot(range(10), label="mock data")\n leg0 = axes[0].legend(title='Aardvark', title_fontsize=22)\n assert leg0.get_title().get_fontsize() == 22\n axes[1].plot(range(10), label="mock data")\n leg1 = axes[1].legend(title='Aardvark',\n title_fontproperties={'family': 'serif', 'size': 22})\n assert leg1.get_title().get_fontsize() == 22\n axes[2].plot(range(10), label="mock data")\n mpl.rcParams['legend.title_fontsize'] = None\n leg2 = axes[2].legend(title='Aardvark',\n title_fontproperties={'family': 'serif'})\n assert leg2.get_title().get_fontsize() == mpl.rcParams['font.size']\n axes[3].plot(range(10), label="mock data")\n leg3 = axes[3].legend(title='Aardvark')\n assert leg3.get_title().get_fontsize() == mpl.rcParams['font.size']\n axes[4].plot(range(10), label="mock data")\n mpl.rcParams['legend.title_fontsize'] = 20\n leg4 = axes[4].legend(title='Aardvark',\n title_fontproperties={'family': 'serif'})\n assert leg4.get_title().get_fontsize() == 20\n axes[5].plot(range(10), label="mock data")\n leg5 = axes[5].legend(title='Aardvark')\n assert leg5.get_title().get_fontsize() == 20\n\n\n@pytest.mark.parametrize('alignment', ('center', 'left', 'right'))\ndef test_legend_alignment(alignment):\n fig, ax = plt.subplots()\n ax.plot(range(10), label='test')\n leg = ax.legend(title="Aardvark", alignment=alignment)\n assert leg.get_children()[0].align == alignment\n assert leg.get_alignment() == alignment\n\n\n@pytest.mark.parametrize('loc', ('center', 'best',))\ndef test_ax_legend_set_loc(loc):\n fig, ax = plt.subplots()\n ax.plot(range(10), label='test')\n leg = ax.legend()\n leg.set_loc(loc)\n assert leg._get_loc() == mlegend.Legend.codes[loc]\n\n\n@pytest.mark.parametrize('loc', ('outside right', 'right',))\ndef test_fig_legend_set_loc(loc):\n fig, ax = plt.subplots()\n ax.plot(range(10), label='test')\n leg = fig.legend()\n leg.set_loc(loc)\n\n loc = loc.split()[1] if loc.startswith("outside") else loc\n assert leg._get_loc() == mlegend.Legend.codes[loc]\n\n\n@pytest.mark.parametrize('alignment', ('center', 'left', 'right'))\ndef test_legend_set_alignment(alignment):\n fig, ax = plt.subplots()\n ax.plot(range(10), label='test')\n leg = ax.legend()\n leg.set_alignment(alignment)\n assert leg.get_children()[0].align == alignment\n assert leg.get_alignment() == alignment\n\n\n@pytest.mark.parametrize('color', ('red', 'none', (.5, .5, .5)))\ndef test_legend_labelcolor_single(color):\n # test labelcolor for a single color\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), np.arange(10)*1, label='#1')\n ax.plot(np.arange(10), np.arange(10)*2, label='#2')\n ax.plot(np.arange(10), np.arange(10)*3, label='#3')\n\n leg = ax.legend(labelcolor=color)\n for text in leg.get_texts():\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_labelcolor_list():\n # test labelcolor for a list of colors\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), np.arange(10)*1, label='#1')\n ax.plot(np.arange(10), np.arange(10)*2, label='#2')\n ax.plot(np.arange(10), np.arange(10)*3, label='#3')\n\n leg = ax.legend(labelcolor=['r', 'g', 'b'])\n for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_labelcolor_linecolor():\n # test the labelcolor for labelcolor='linecolor'\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), np.arange(10)*1, label='#1', color='r')\n ax.plot(np.arange(10), np.arange(10)*2, label='#2', color='g')\n ax.plot(np.arange(10), np.arange(10)*3, label='#3', color='b')\n\n leg = ax.legend(labelcolor='linecolor')\n for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_pathcollection_labelcolor_linecolor():\n # test the labelcolor for labelcolor='linecolor' on PathCollection\n fig, ax = plt.subplots()\n ax.scatter(np.arange(10), np.arange(10)*1, label='#1', c='r')\n ax.scatter(np.arange(10), np.arange(10)*2, label='#2', c='g')\n ax.scatter(np.arange(10), np.arange(10)*3, label='#3', c='b')\n\n leg = ax.legend(labelcolor='linecolor')\n for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_pathcollection_labelcolor_linecolor_iterable():\n # test the labelcolor for labelcolor='linecolor' on PathCollection\n # with iterable colors\n fig, ax = plt.subplots()\n colors = np.array(['r', 'g', 'b', 'c', 'm'] * 2)\n ax.scatter(np.arange(10), np.arange(10), label='#1', c=colors)\n\n leg = ax.legend(labelcolor='linecolor')\n text, = leg.get_texts()\n assert mpl.colors.same_color(text.get_color(), 'black')\n\n\ndef test_legend_pathcollection_labelcolor_linecolor_cmap():\n # test the labelcolor for labelcolor='linecolor' on PathCollection\n # with a colormap\n fig, ax = plt.subplots()\n ax.scatter(np.arange(10), np.arange(10), c=np.arange(10), label='#1')\n\n leg = ax.legend(labelcolor='linecolor')\n text, = leg.get_texts()\n assert mpl.colors.same_color(text.get_color(), 'black')\n\n\ndef test_legend_labelcolor_markeredgecolor():\n # test the labelcolor for labelcolor='markeredgecolor'\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), np.arange(10)*1, label='#1', markeredgecolor='r')\n ax.plot(np.arange(10), np.arange(10)*2, label='#2', markeredgecolor='g')\n ax.plot(np.arange(10), np.arange(10)*3, label='#3', markeredgecolor='b')\n\n leg = ax.legend(labelcolor='markeredgecolor')\n for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_pathcollection_labelcolor_markeredgecolor():\n # test the labelcolor for labelcolor='markeredgecolor' on PathCollection\n fig, ax = plt.subplots()\n ax.scatter(np.arange(10), np.arange(10)*1, label='#1', edgecolor='r')\n ax.scatter(np.arange(10), np.arange(10)*2, label='#2', edgecolor='g')\n ax.scatter(np.arange(10), np.arange(10)*3, label='#3', edgecolor='b')\n\n leg = ax.legend(labelcolor='markeredgecolor')\n for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_pathcollection_labelcolor_markeredgecolor_iterable():\n # test the labelcolor for labelcolor='markeredgecolor' on PathCollection\n # with iterable colors\n fig, ax = plt.subplots()\n colors = np.array(['r', 'g', 'b', 'c', 'm'] * 2)\n ax.scatter(np.arange(10), np.arange(10), label='#1', edgecolor=colors)\n\n leg = ax.legend(labelcolor='markeredgecolor')\n for text, color in zip(leg.get_texts(), ['k']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_pathcollection_labelcolor_markeredgecolor_cmap():\n # test the labelcolor for labelcolor='markeredgecolor' on PathCollection\n # with a colormap\n fig, ax = plt.subplots()\n edgecolors = mpl.cm.viridis(np.random.rand(10))\n ax.scatter(\n np.arange(10),\n np.arange(10),\n label='#1',\n c=np.arange(10),\n edgecolor=edgecolors,\n cmap="Reds"\n )\n\n leg = ax.legend(labelcolor='markeredgecolor')\n for text, color in zip(leg.get_texts(), ['k']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_labelcolor_markerfacecolor():\n # test the labelcolor for labelcolor='markerfacecolor'\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), np.arange(10)*1, label='#1', markerfacecolor='r')\n ax.plot(np.arange(10), np.arange(10)*2, label='#2', markerfacecolor='g')\n ax.plot(np.arange(10), np.arange(10)*3, label='#3', markerfacecolor='b')\n\n leg = ax.legend(labelcolor='markerfacecolor')\n for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_pathcollection_labelcolor_markerfacecolor():\n # test the labelcolor for labelcolor='markerfacecolor' on PathCollection\n fig, ax = plt.subplots()\n ax.scatter(np.arange(10), np.arange(10)*1, label='#1', facecolor='r')\n ax.scatter(np.arange(10), np.arange(10)*2, label='#2', facecolor='g')\n ax.scatter(np.arange(10), np.arange(10)*3, label='#3', facecolor='b')\n\n leg = ax.legend(labelcolor='markerfacecolor')\n for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_pathcollection_labelcolor_markerfacecolor_iterable():\n # test the labelcolor for labelcolor='markerfacecolor' on PathCollection\n # with iterable colors\n fig, ax = plt.subplots()\n colors = np.array(['r', 'g', 'b', 'c', 'm'] * 2)\n ax.scatter(np.arange(10), np.arange(10), label='#1', facecolor=colors)\n\n leg = ax.legend(labelcolor='markerfacecolor')\n for text, color in zip(leg.get_texts(), ['k']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_pathcollection_labelcolor_markfacecolor_cmap():\n # test the labelcolor for labelcolor='markerfacecolor' on PathCollection\n # with colormaps\n fig, ax = plt.subplots()\n colors = mpl.cm.viridis(np.random.rand(10))\n ax.scatter(\n np.arange(10),\n np.arange(10),\n label='#1',\n c=colors\n )\n\n leg = ax.legend(labelcolor='markerfacecolor')\n for text, color in zip(leg.get_texts(), ['k']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\n@pytest.mark.parametrize('color', ('red', 'none', (.5, .5, .5)))\ndef test_legend_labelcolor_rcparam_single(color):\n # test the rcParams legend.labelcolor for a single color\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), np.arange(10)*1, label='#1')\n ax.plot(np.arange(10), np.arange(10)*2, label='#2')\n ax.plot(np.arange(10), np.arange(10)*3, label='#3')\n\n mpl.rcParams['legend.labelcolor'] = color\n leg = ax.legend()\n for text in leg.get_texts():\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_labelcolor_rcparam_linecolor():\n # test the rcParams legend.labelcolor for a linecolor\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), np.arange(10)*1, label='#1', color='r')\n ax.plot(np.arange(10), np.arange(10)*2, label='#2', color='g')\n ax.plot(np.arange(10), np.arange(10)*3, label='#3', color='b')\n\n mpl.rcParams['legend.labelcolor'] = 'linecolor'\n leg = ax.legend()\n for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_labelcolor_rcparam_markeredgecolor():\n # test the labelcolor for labelcolor='markeredgecolor'\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), np.arange(10)*1, label='#1', markeredgecolor='r')\n ax.plot(np.arange(10), np.arange(10)*2, label='#2', markeredgecolor='g')\n ax.plot(np.arange(10), np.arange(10)*3, label='#3', markeredgecolor='b')\n\n mpl.rcParams['legend.labelcolor'] = 'markeredgecolor'\n leg = ax.legend()\n for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_labelcolor_rcparam_markeredgecolor_short():\n # test the labelcolor for labelcolor='markeredgecolor'\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), np.arange(10)*1, label='#1', markeredgecolor='r')\n ax.plot(np.arange(10), np.arange(10)*2, label='#2', markeredgecolor='g')\n ax.plot(np.arange(10), np.arange(10)*3, label='#3', markeredgecolor='b')\n\n mpl.rcParams['legend.labelcolor'] = 'mec'\n leg = ax.legend()\n for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_labelcolor_rcparam_markerfacecolor():\n # test the labelcolor for labelcolor='markeredgecolor'\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), np.arange(10)*1, label='#1', markerfacecolor='r')\n ax.plot(np.arange(10), np.arange(10)*2, label='#2', markerfacecolor='g')\n ax.plot(np.arange(10), np.arange(10)*3, label='#3', markerfacecolor='b')\n\n mpl.rcParams['legend.labelcolor'] = 'markerfacecolor'\n leg = ax.legend()\n for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\ndef test_legend_labelcolor_rcparam_markerfacecolor_short():\n # test the labelcolor for labelcolor='markeredgecolor'\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), np.arange(10)*1, label='#1', markerfacecolor='r')\n ax.plot(np.arange(10), np.arange(10)*2, label='#2', markerfacecolor='g')\n ax.plot(np.arange(10), np.arange(10)*3, label='#3', markerfacecolor='b')\n\n mpl.rcParams['legend.labelcolor'] = 'mfc'\n leg = ax.legend()\n for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):\n assert mpl.colors.same_color(text.get_color(), color)\n\n\n@pytest.mark.filterwarnings("ignore:No artists with labels found to put in legend")\ndef test_get_set_draggable():\n legend = plt.legend()\n assert not legend.get_draggable()\n legend.set_draggable(True)\n assert legend.get_draggable()\n legend.set_draggable(False)\n assert not legend.get_draggable()\n\n\n@pytest.mark.parametrize('draggable', (True, False))\ndef test_legend_draggable(draggable):\n fig, ax = plt.subplots()\n ax.plot(range(10), label='shabnams')\n leg = ax.legend(draggable=draggable)\n assert leg.get_draggable() is draggable\n\n\ndef test_alpha_handles():\n x, n, hh = plt.hist([1, 2, 3], alpha=0.25, label='data', color='red')\n legend = plt.legend()\n for lh in legend.legend_handles:\n lh.set_alpha(1.0)\n assert lh.get_facecolor()[:-1] == hh[1].get_facecolor()[:-1]\n assert lh.get_edgecolor()[:-1] == hh[1].get_edgecolor()[:-1]\n\n\n@needs_usetex\ndef test_usetex_no_warn(caplog):\n mpl.rcParams['font.family'] = 'serif'\n mpl.rcParams['font.serif'] = 'Computer Modern'\n mpl.rcParams['text.usetex'] = True\n\n fig, ax = plt.subplots()\n ax.plot(0, 0, label='input')\n ax.legend(title="My legend")\n\n fig.canvas.draw()\n assert "Font family ['serif'] not found." not in caplog.text\n\n\ndef test_warn_big_data_best_loc(monkeypatch):\n # Force _find_best_position to think it took a long time.\n counter = itertools.count(0, step=1.5)\n monkeypatch.setattr(time, 'perf_counter', lambda: next(counter))\n\n fig, ax = plt.subplots()\n fig.canvas.draw() # So that we can call draw_artist later.\n\n # Place line across all possible legend locations.\n x = [0.9, 0.1, 0.1, 0.9, 0.9, 0.5]\n y = [0.95, 0.95, 0.05, 0.05, 0.5, 0.5]\n ax.plot(x, y, 'o-', label='line')\n\n with rc_context({'legend.loc': 'best'}):\n legend = ax.legend()\n with pytest.warns(UserWarning,\n match='Creating legend with loc="best" can be slow with large '\n 'amounts of data.') as records:\n fig.draw_artist(legend) # Don't bother drawing the lines -- it's slow.\n # The _find_best_position method of Legend is called twice, duplicating\n # the warning message.\n assert len(records) == 2\n\n\ndef test_no_warn_big_data_when_loc_specified(monkeypatch):\n # Force _find_best_position to think it took a long time.\n counter = itertools.count(0, step=1.5)\n monkeypatch.setattr(time, 'perf_counter', lambda: next(counter))\n\n fig, ax = plt.subplots()\n fig.canvas.draw()\n\n # Place line across all possible legend locations.\n x = [0.9, 0.1, 0.1, 0.9, 0.9, 0.5]\n y = [0.95, 0.95, 0.05, 0.05, 0.5, 0.5]\n ax.plot(x, y, 'o-', label='line')\n\n legend = ax.legend('best')\n fig.draw_artist(legend) # Check that no warning is emitted.\n\n\n@pytest.mark.parametrize('label_array', [['low', 'high'],\n ('low', 'high'),\n np.array(['low', 'high'])])\ndef test_plot_multiple_input_multiple_label(label_array):\n # test ax.plot() with multidimensional input\n # and multiple labels\n x = [1, 2, 3]\n y = [[1, 2],\n [2, 5],\n [4, 9]]\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label=label_array)\n leg = ax.legend()\n legend_texts = [entry.get_text() for entry in leg.get_texts()]\n assert legend_texts == ['low', 'high']\n\n\n@pytest.mark.parametrize('label', ['one', 1, int])\ndef test_plot_multiple_input_single_label(label):\n # test ax.plot() with multidimensional input\n # and single label\n x = [1, 2, 3]\n y = [[1, 2],\n [2, 5],\n [4, 9]]\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label=label)\n leg = ax.legend()\n legend_texts = [entry.get_text() for entry in leg.get_texts()]\n assert legend_texts == [str(label)] * 2\n\n\n@pytest.mark.parametrize('label_array', [['low', 'high'],\n ('low', 'high'),\n np.array(['low', 'high'])])\ndef test_plot_single_input_multiple_label(label_array):\n # test ax.plot() with 1D array like input\n # and iterable label\n x = [1, 2, 3]\n y = [2, 5, 6]\n fig, ax = plt.subplots()\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match='Passing label as a length 2 sequence'):\n ax.plot(x, y, label=label_array)\n leg = ax.legend()\n assert len(leg.get_texts()) == 1\n assert leg.get_texts()[0].get_text() == str(label_array)\n\n\ndef test_plot_single_input_list_label():\n fig, ax = plt.subplots()\n line, = ax.plot([[0], [1]], label=['A'])\n assert line.get_label() == 'A'\n\n\ndef test_plot_multiple_label_incorrect_length_exception():\n # check that exception is raised if multiple labels\n # are given, but number of on labels != number of lines\n with pytest.raises(ValueError):\n x = [1, 2, 3]\n y = [[1, 2],\n [2, 5],\n [4, 9]]\n label = ['high', 'low', 'medium']\n fig, ax = plt.subplots()\n ax.plot(x, y, label=label)\n\n\ndef test_legend_face_edgecolor():\n # Smoke test for PolyCollection legend handler with 'face' edgecolor.\n fig, ax = plt.subplots()\n ax.fill_between([0, 1, 2], [1, 2, 3], [2, 3, 4],\n facecolor='r', edgecolor='face', label='Fill')\n ax.legend()\n\n\ndef test_legend_text_axes():\n fig, ax = plt.subplots()\n ax.plot([1, 2], [3, 4], label='line')\n leg = ax.legend()\n\n assert leg.axes is ax\n assert leg.get_texts()[0].axes is ax\n\n\ndef test_handlerline2d():\n # Test marker consistency for monolithic Line2D legend handler (#11357).\n fig, ax = plt.subplots()\n ax.scatter([0, 1], [0, 1], marker="v")\n handles = [mlines.Line2D([0], [0], marker="v")]\n leg = ax.legend(handles, ["Aardvark"], numpoints=1)\n assert handles[0].get_marker() == leg.legend_handles[0].get_marker()\n\n\ndef test_subfigure_legend():\n # Test that legend can be added to subfigure (#20723)\n subfig = plt.figure().subfigures()\n ax = subfig.subplots()\n ax.plot([0, 1], [0, 1], label="line")\n leg = subfig.legend()\n assert leg.get_figure(root=False) is subfig\n\n\ndef test_setting_alpha_keeps_polycollection_color():\n pc = plt.fill_between([0, 1], [2, 3], color='#123456', label='label')\n patch = plt.legend().get_patches()[0]\n patch.set_alpha(0.5)\n assert patch.get_facecolor()[:3] == tuple(pc.get_facecolor()[0][:3])\n assert patch.get_edgecolor()[:3] == tuple(pc.get_edgecolor()[0][:3])\n\n\ndef test_legend_markers_from_line2d():\n # Test that markers can be copied for legend lines (#17960)\n _markers = ['.', '*', 'v']\n fig, ax = plt.subplots()\n lines = [mlines.Line2D([0], [0], ls='None', marker=mark)\n for mark in _markers]\n labels = ["foo", "bar", "xyzzy"]\n markers = [line.get_marker() for line in lines]\n legend = ax.legend(lines, labels)\n\n new_markers = [line.get_marker() for line in legend.get_lines()]\n new_labels = [text.get_text() for text in legend.get_texts()]\n\n assert markers == new_markers == _markers\n assert labels == new_labels\n\n\n@check_figures_equal(extensions=['png'])\ndef test_ncol_ncols(fig_test, fig_ref):\n # Test that both ncol and ncols work\n strings = ["a", "b", "c", "d", "e", "f"]\n ncols = 3\n fig_test.legend(strings, ncol=ncols)\n fig_ref.legend(strings, ncols=ncols)\n\n\ndef test_loc_invalid_tuple_exception():\n # check that exception is raised if the loc arg\n # of legend is not a 2-tuple of numbers\n fig, ax = plt.subplots()\n with pytest.raises(ValueError, match=('loc must be string, coordinate '\n 'tuple, or an integer 0-10, not \\(1.1,\\)')):\n ax.legend(loc=(1.1, ), labels=["mock data"])\n\n with pytest.raises(ValueError, match=('loc must be string, coordinate '\n 'tuple, or an integer 0-10, not \\(0.481, 0.4227, 0.4523\\)')):\n ax.legend(loc=(0.481, 0.4227, 0.4523), labels=["mock data"])\n\n with pytest.raises(ValueError, match=('loc must be string, coordinate '\n 'tuple, or an integer 0-10, not \\(0.481, \'go blue\'\\)')):\n ax.legend(loc=(0.481, "go blue"), labels=["mock data"])\n\n\ndef test_loc_valid_tuple():\n fig, ax = plt.subplots()\n ax.legend(loc=(0.481, 0.442), labels=["mock data"])\n ax.legend(loc=(1, 2), labels=["mock data"])\n\n\ndef test_loc_valid_list():\n fig, ax = plt.subplots()\n ax.legend(loc=[0.481, 0.442], labels=["mock data"])\n ax.legend(loc=[1, 2], labels=["mock data"])\n\n\ndef test_loc_invalid_list_exception():\n fig, ax = plt.subplots()\n with pytest.raises(ValueError, match=('loc must be string, coordinate '\n 'tuple, or an integer 0-10, not \\[1.1, 2.2, 3.3\\]')):\n ax.legend(loc=[1.1, 2.2, 3.3], labels=["mock data"])\n\n\ndef test_loc_invalid_type():\n fig, ax = plt.subplots()\n with pytest.raises(ValueError, match=("loc must be string, coordinate "\n "tuple, or an integer 0-10, not {'not': True}")):\n ax.legend(loc={'not': True}, labels=["mock data"])\n\n\ndef test_loc_validation_numeric_value():\n fig, ax = plt.subplots()\n ax.legend(loc=0, labels=["mock data"])\n ax.legend(loc=1, labels=["mock data"])\n ax.legend(loc=5, labels=["mock data"])\n ax.legend(loc=10, labels=["mock data"])\n with pytest.raises(ValueError, match=('loc must be string, coordinate '\n 'tuple, or an integer 0-10, not 11')):\n ax.legend(loc=11, labels=["mock data"])\n\n with pytest.raises(ValueError, match=('loc must be string, coordinate '\n 'tuple, or an integer 0-10, not -1')):\n ax.legend(loc=-1, labels=["mock data"])\n\n\ndef test_loc_validation_string_value():\n fig, ax = plt.subplots()\n labels = ["mock data"]\n ax.legend(loc='best', labels=labels)\n ax.legend(loc='upper right', labels=labels)\n ax.legend(loc='best', labels=labels)\n ax.legend(loc='upper right', labels=labels)\n ax.legend(loc='upper left', labels=labels)\n ax.legend(loc='lower left', labels=labels)\n ax.legend(loc='lower right', labels=labels)\n ax.legend(loc='right', labels=labels)\n ax.legend(loc='center left', labels=labels)\n ax.legend(loc='center right', labels=labels)\n ax.legend(loc='lower center', labels=labels)\n ax.legend(loc='upper center', labels=labels)\n with pytest.raises(ValueError, match="'wrong' is not a valid value for"):\n ax.legend(loc='wrong', labels=labels)\n\n\ndef test_legend_handle_label_mismatch():\n pl1, = plt.plot(range(10))\n pl2, = plt.plot(range(10))\n with pytest.warns(UserWarning, match="number of handles and labels"):\n legend = plt.legend(handles=[pl1, pl2], labels=["pl1", "pl2", "pl3"])\n assert len(legend.legend_handles) == 2\n assert len(legend.get_texts()) == 2\n\n\ndef test_legend_handle_label_mismatch_no_len():\n pl1, = plt.plot(range(10))\n pl2, = plt.plot(range(10))\n legend = plt.legend(handles=iter([pl1, pl2]),\n labels=iter(["pl1", "pl2", "pl3"]))\n assert len(legend.legend_handles) == 2\n assert len(legend.get_texts()) == 2\n\n\ndef test_legend_nolabels_warning():\n plt.plot([1, 2, 3])\n with pytest.raises(UserWarning, match="No artists with labels found"):\n plt.legend()\n\n\n@pytest.mark.filterwarnings("ignore:No artists with labels found to put in legend")\ndef test_legend_nolabels_draw():\n plt.plot([1, 2, 3])\n plt.legend()\n assert plt.gca().get_legend() is not None\n\n\ndef test_legend_loc_polycollection():\n # Test that the legend is placed in the correct\n # position for 'best' for polycollection\n x = [3, 4, 5]\n y1 = [1, 1, 1]\n y2 = [5, 5, 5]\n leg_bboxes = []\n fig, axs = plt.subplots(ncols=2, figsize=(10, 5))\n for ax, loc in zip(axs.flat, ('best', 'lower left')):\n ax.fill_between(x, y1, y2, color='gray', alpha=0.5, label='Shaded Area')\n ax.set_xlim(0, 6)\n ax.set_ylim(-1, 5)\n leg = ax.legend(loc=loc)\n fig.canvas.draw()\n leg_bboxes.append(\n leg.get_window_extent().transformed(ax.transAxes.inverted()))\n assert_allclose(leg_bboxes[1].bounds, leg_bboxes[0].bounds)\n\n\ndef test_legend_text():\n # Test that legend is place in the correct\n # position for 'best' when there is text in figure\n fig, axs = plt.subplots(ncols=2, figsize=(10, 5))\n leg_bboxes = []\n for ax, loc in zip(axs.flat, ('best', 'lower left')):\n x = [1, 2]\n y = [2, 1]\n ax.plot(x, y, label='plot name')\n ax.text(1.5, 2, 'some text blahblah', verticalalignment='top')\n leg = ax.legend(loc=loc)\n fig.canvas.draw()\n leg_bboxes.append(\n leg.get_window_extent().transformed(ax.transAxes.inverted()))\n assert_allclose(leg_bboxes[1].bounds, leg_bboxes[0].bounds)\n\n\ndef test_legend_annotate():\n fig, ax = plt.subplots()\n\n ax.plot([1, 2, 3], label="Line")\n ax.annotate("a", xy=(1, 1))\n ax.legend(loc=0)\n\n with mock.patch.object(\n fig, '_get_renderer', wraps=fig._get_renderer) as mocked_get_renderer:\n fig.savefig(io.BytesIO())\n\n # Finding the legend position should not require _get_renderer to be called\n mocked_get_renderer.assert_not_called()\n\n\ndef test_boxplot_legend_labels():\n # Test that legend entries are generated when passing `label`.\n np.random.seed(19680801)\n data = np.random.random((10, 4))\n fig, axs = plt.subplots(nrows=1, ncols=4)\n legend_labels = ['box A', 'box B', 'box C', 'box D']\n\n # Testing legend labels and patch passed to legend.\n bp1 = axs[0].boxplot(data, patch_artist=True, label=legend_labels)\n assert [v.get_label() for v in bp1['boxes']] == legend_labels\n handles, labels = axs[0].get_legend_handles_labels()\n assert labels == legend_labels\n assert all(isinstance(h, mpl.patches.PathPatch) for h in handles)\n\n # Testing legend without `box`.\n bp2 = axs[1].boxplot(data, label=legend_labels, showbox=False)\n # Without a box, The legend entries should be passed from the medians.\n assert [v.get_label() for v in bp2['medians']] == legend_labels\n handles, labels = axs[1].get_legend_handles_labels()\n assert labels == legend_labels\n assert all(isinstance(h, mpl.lines.Line2D) for h in handles)\n\n # Testing legend with number of labels different from number of boxes.\n with pytest.raises(ValueError, match='values must have same the length'):\n bp3 = axs[2].boxplot(data, label=legend_labels[:-1])\n\n # Test that for a string label, only the first box gets a label.\n bp4 = axs[3].boxplot(data, label='box A')\n assert bp4['medians'][0].get_label() == 'box A'\n assert all(x.get_label().startswith("_") for x in bp4['medians'][1:])\n | .venv\Lib\site-packages\matplotlib\tests\test_legend.py | test_legend.py | Python | 54,829 | 0.75 | 0.140434 | 0.087986 | react-lib | 541 | 2024-10-12T06:30:15.791918 | BSD-3-Clause | true | 639a67f50d53727f39dcd812e75578f7 |
"""\nTests specific to the lines module.\n"""\n\nimport itertools\nimport platform\nimport timeit\nfrom types import SimpleNamespace\n\nfrom cycler import cycler\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nimport pytest\n\nimport matplotlib\nimport matplotlib as mpl\nfrom matplotlib import _path\nimport matplotlib.lines as mlines\nfrom matplotlib.markers import MarkerStyle\nfrom matplotlib.path import Path\nimport matplotlib.pyplot as plt\nimport matplotlib.transforms as mtransforms\nfrom matplotlib.testing.decorators import image_comparison, check_figures_equal\n\n\ndef test_segment_hits():\n """Test a problematic case."""\n cx, cy = 553, 902\n x, y = np.array([553., 553.]), np.array([95., 947.])\n radius = 6.94\n assert_array_equal(mlines.segment_hits(cx, cy, x, y, radius), [0])\n\n\n# Runtimes on a loaded system are inherently flaky. Not so much that a rerun\n# won't help, hopefully.\n@pytest.mark.flaky(reruns=3)\ndef test_invisible_Line_rendering():\n """\n GitHub issue #1256 identified a bug in Line.draw method\n\n Despite visibility attribute set to False, the draw method was not\n returning early enough and some pre-rendering code was executed\n though not necessary.\n\n Consequence was an excessive draw time for invisible Line instances\n holding a large number of points (Npts> 10**6)\n """\n # Creates big x and y data:\n N = 10**7\n x = np.linspace(0, 1, N)\n y = np.random.normal(size=N)\n\n # Create a plot figure:\n fig = plt.figure()\n ax = plt.subplot()\n\n # Create a "big" Line instance:\n l = mlines.Line2D(x, y)\n l.set_visible(False)\n # but don't add it to the Axis instance `ax`\n\n # [here Interactive panning and zooming is pretty responsive]\n # Time the canvas drawing:\n t_no_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3))\n # (gives about 25 ms)\n\n # Add the big invisible Line:\n ax.add_line(l)\n\n # [Now interactive panning and zooming is very slow]\n # Time the canvas drawing:\n t_invisible_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3))\n # gives about 290 ms for N = 10**7 pts\n\n slowdown_factor = t_invisible_line / t_no_line\n slowdown_threshold = 2 # trying to avoid false positive failures\n assert slowdown_factor < slowdown_threshold\n\n\ndef test_set_line_coll_dash():\n fig, ax = plt.subplots()\n np.random.seed(0)\n # Testing setting linestyles for line collections.\n # This should not produce an error.\n ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))])\n\n\ndef test_invalid_line_data():\n with pytest.raises(RuntimeError, match='xdata must be'):\n mlines.Line2D(0, [])\n with pytest.raises(RuntimeError, match='ydata must be'):\n mlines.Line2D([], 1)\n\n line = mlines.Line2D([], [])\n with pytest.raises(RuntimeError, match='x must be'):\n line.set_xdata(0)\n with pytest.raises(RuntimeError, match='y must be'):\n line.set_ydata(0)\n\n\n@image_comparison(['line_dashes'], remove_text=True, tol=0.003)\ndef test_line_dashes():\n # Tolerance introduced after reordering of floating-point operations\n # Remove when regenerating the images\n fig, ax = plt.subplots()\n\n ax.plot(range(10), linestyle=(0, (3, 3)), lw=5)\n\n\ndef test_line_colors():\n fig, ax = plt.subplots()\n ax.plot(range(10), color='none')\n ax.plot(range(10), color='r')\n ax.plot(range(10), color='.3')\n ax.plot(range(10), color=(1, 0, 0, 1))\n ax.plot(range(10), color=(1, 0, 0))\n fig.canvas.draw()\n\n\ndef test_valid_colors():\n line = mlines.Line2D([], [])\n with pytest.raises(ValueError):\n line.set_color("foobar")\n\n\ndef test_linestyle_variants():\n fig, ax = plt.subplots()\n for ls in ["-", "solid", "--", "dashed",\n "-.", "dashdot", ":", "dotted",\n (0, None), (0, ()), (0, []), # gh-22930\n ]:\n ax.plot(range(10), linestyle=ls)\n fig.canvas.draw()\n\n\ndef test_valid_linestyles():\n line = mlines.Line2D([], [])\n with pytest.raises(ValueError):\n line.set_linestyle('aardvark')\n\n\n@image_comparison(['drawstyle_variants.png'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.03)\ndef test_drawstyle_variants():\n fig, axs = plt.subplots(6)\n dss = ["default", "steps-mid", "steps-pre", "steps-post", "steps", None]\n # We want to check that drawstyles are properly handled even for very long\n # lines (for which the subslice optimization is on); however, we need\n # to zoom in so that the difference between the drawstyles is actually\n # visible.\n for ax, ds in zip(axs.flat, dss):\n ax.plot(range(2000), drawstyle=ds)\n ax.set(xlim=(0, 2), ylim=(0, 2))\n\n\n@check_figures_equal(extensions=('png',))\ndef test_no_subslice_with_transform(fig_ref, fig_test):\n ax = fig_ref.add_subplot()\n x = np.arange(2000)\n ax.plot(x + 2000, x)\n\n ax = fig_test.add_subplot()\n t = mtransforms.Affine2D().translate(2000.0, 0.0)\n ax.plot(x, x, transform=t+ax.transData)\n\n\ndef test_valid_drawstyles():\n line = mlines.Line2D([], [])\n with pytest.raises(ValueError):\n line.set_drawstyle('foobar')\n\n\ndef test_set_drawstyle():\n x = np.linspace(0, 2*np.pi, 10)\n y = np.sin(x)\n\n fig, ax = plt.subplots()\n line, = ax.plot(x, y)\n line.set_drawstyle("steps-pre")\n assert len(line.get_path().vertices) == 2*len(x)-1\n\n line.set_drawstyle("default")\n assert len(line.get_path().vertices) == len(x)\n\n\n@image_comparison(['line_collection_dashes'], remove_text=True, style='mpl20',\n tol=0 if platform.machine() == 'x86_64' else 0.65)\ndef test_set_line_coll_dash_image():\n fig, ax = plt.subplots()\n np.random.seed(0)\n ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))])\n\n\n@image_comparison(['marker_fill_styles.png'], remove_text=True)\ndef test_marker_fill_styles():\n colors = itertools.cycle([[0, 0, 1], 'g', '#ff0000', 'c', 'm', 'y',\n np.array([0, 0, 0])])\n altcolor = 'lightgreen'\n\n y = np.array([1, 1])\n x = np.array([0, 9])\n fig, ax = plt.subplots()\n\n # This hard-coded list of markers correspond to an earlier iteration of\n # MarkerStyle.filled_markers; the value of that attribute has changed but\n # we kept the old value here to not regenerate the baseline image.\n # Replace with mlines.Line2D.filled_markers when the image is regenerated.\n for j, marker in enumerate("ov^<>8sp*hHDdPX"):\n for i, fs in enumerate(mlines.Line2D.fillStyles):\n color = next(colors)\n ax.plot(j * 10 + x, y + i + .5 * (j % 2),\n marker=marker,\n markersize=20,\n markerfacecoloralt=altcolor,\n fillstyle=fs,\n label=fs,\n linewidth=5,\n color=color,\n markeredgecolor=color,\n markeredgewidth=2)\n\n ax.set_ylim([0, 7.5])\n ax.set_xlim([-5, 155])\n\n\ndef test_markerfacecolor_fillstyle():\n """Test that markerfacecolor does not override fillstyle='none'."""\n l, = plt.plot([1, 3, 2], marker=MarkerStyle('o', fillstyle='none'),\n markerfacecolor='red')\n assert l.get_fillstyle() == 'none'\n assert l.get_markerfacecolor() == 'none'\n\n\n@image_comparison(['scaled_lines'], style='default')\ndef test_lw_scaling():\n th = np.linspace(0, 32)\n fig, ax = plt.subplots()\n lins_styles = ['dashed', 'dotted', 'dashdot']\n cy = cycler(matplotlib.rcParams['axes.prop_cycle'])\n for j, (ls, sty) in enumerate(zip(lins_styles, cy)):\n for lw in np.linspace(.5, 10, 10):\n ax.plot(th, j*np.ones(50) + .1 * lw, linestyle=ls, lw=lw, **sty)\n\n\ndef test_is_sorted_and_has_non_nan():\n assert _path.is_sorted_and_has_non_nan(np.array([1, 2, 3]))\n assert _path.is_sorted_and_has_non_nan(np.array([1, np.nan, 3]))\n assert not _path.is_sorted_and_has_non_nan([3, 5] + [np.nan] * 100 + [0, 2])\n # [2, 256] byteswapped:\n assert not _path.is_sorted_and_has_non_nan(np.array([33554432, 65536], ">i4"))\n n = 2 * mlines.Line2D._subslice_optim_min_size\n plt.plot([np.nan] * n, range(n))\n\n\n@check_figures_equal(extensions=['png'])\ndef test_step_markers(fig_test, fig_ref):\n fig_test.subplots().step([0, 1], "-o")\n fig_ref.subplots().plot([0, 0, 1], [0, 1, 1], "-o", markevery=[0, 2])\n\n\n@pytest.mark.parametrize("parent", ["figure", "axes"])\n@check_figures_equal(extensions=('png',))\ndef test_markevery(fig_test, fig_ref, parent):\n np.random.seed(42)\n x = np.linspace(0, 1, 14)\n y = np.random.rand(len(x))\n\n cases_test = [None, 4, (2, 5), [1, 5, 11],\n [0, -1], slice(5, 10, 2),\n np.arange(len(x))[y > 0.5],\n 0.3, (0.3, 0.4)]\n cases_ref = ["11111111111111", "10001000100010", "00100001000010",\n "01000100000100", "10000000000001", "00000101010000",\n "01110001110110", "11011011011110", "01010011011101"]\n\n if parent == "figure":\n # float markevery ("relative to axes size") is not supported.\n cases_test = cases_test[:-2]\n cases_ref = cases_ref[:-2]\n\n def add_test(x, y, *, markevery):\n fig_test.add_artist(\n mlines.Line2D(x, y, marker="o", markevery=markevery))\n\n def add_ref(x, y, *, markevery):\n fig_ref.add_artist(\n mlines.Line2D(x, y, marker="o", markevery=markevery))\n\n elif parent == "axes":\n axs_test = iter(fig_test.subplots(3, 3).flat)\n axs_ref = iter(fig_ref.subplots(3, 3).flat)\n\n def add_test(x, y, *, markevery):\n next(axs_test).plot(x, y, "-gD", markevery=markevery)\n\n def add_ref(x, y, *, markevery):\n next(axs_ref).plot(x, y, "-gD", markevery=markevery)\n\n for case in cases_test:\n add_test(x, y, markevery=case)\n\n for case in cases_ref:\n me = np.array(list(case)).astype(int).astype(bool)\n add_ref(x, y, markevery=me)\n\n\ndef test_markevery_figure_line_unsupported_relsize():\n fig = plt.figure()\n fig.add_artist(mlines.Line2D([0, 1], [0, 1], marker="o", markevery=.5))\n with pytest.raises(ValueError):\n fig.canvas.draw()\n\n\ndef test_marker_as_markerstyle():\n fig, ax = plt.subplots()\n line, = ax.plot([2, 4, 3], marker=MarkerStyle("D"))\n fig.canvas.draw()\n assert line.get_marker() == "D"\n\n # continue with smoke tests:\n line.set_marker("s")\n fig.canvas.draw()\n line.set_marker(MarkerStyle("o"))\n fig.canvas.draw()\n # test Path roundtrip\n triangle1 = Path._create_closed([[-1, -1], [1, -1], [0, 2]])\n line2, = ax.plot([1, 3, 2], marker=MarkerStyle(triangle1), ms=22)\n line3, = ax.plot([0, 2, 1], marker=triangle1, ms=22)\n\n assert_array_equal(line2.get_marker().vertices, triangle1.vertices)\n assert_array_equal(line3.get_marker().vertices, triangle1.vertices)\n\n\n@image_comparison(['striped_line.png'], remove_text=True, style='mpl20')\ndef test_striped_lines():\n rng = np.random.default_rng(19680801)\n _, ax = plt.subplots()\n ax.plot(rng.uniform(size=12), color='orange', gapcolor='blue',\n linestyle='--', lw=5, label=' ')\n ax.plot(rng.uniform(size=12), color='red', gapcolor='black',\n linestyle=(0, (2, 5, 4, 2)), lw=5, label=' ', alpha=0.5)\n ax.legend(handlelength=5)\n\n\n@check_figures_equal(extensions=['png'])\ndef test_odd_dashes(fig_test, fig_ref):\n fig_test.add_subplot().plot([1, 2], dashes=[1, 2, 3])\n fig_ref.add_subplot().plot([1, 2], dashes=[1, 2, 3, 1, 2, 3])\n\n\ndef test_picking():\n fig, ax = plt.subplots()\n mouse_event = SimpleNamespace(x=fig.bbox.width // 2,\n y=fig.bbox.height // 2 + 15)\n\n # Default pickradius is 5, so event should not pick this line.\n l0, = ax.plot([0, 1], [0, 1], picker=True)\n found, indices = l0.contains(mouse_event)\n assert not found\n\n # But with a larger pickradius, this should be picked.\n l1, = ax.plot([0, 1], [0, 1], picker=True, pickradius=20)\n found, indices = l1.contains(mouse_event)\n assert found\n assert_array_equal(indices['ind'], [0])\n\n # And if we modify the pickradius after creation, it should work as well.\n l2, = ax.plot([0, 1], [0, 1], picker=True)\n found, indices = l2.contains(mouse_event)\n assert not found\n l2.set_pickradius(20)\n found, indices = l2.contains(mouse_event)\n assert found\n assert_array_equal(indices['ind'], [0])\n\n\n@check_figures_equal(extensions=['png'])\ndef test_input_copy(fig_test, fig_ref):\n\n t = np.arange(0, 6, 2)\n l, = fig_test.add_subplot().plot(t, t, ".-")\n t[:] = range(3)\n # Trigger cache invalidation\n l.set_drawstyle("steps")\n fig_ref.add_subplot().plot([0, 2, 4], [0, 2, 4], ".-", drawstyle="steps")\n\n\n@check_figures_equal(extensions=["png"])\ndef test_markevery_prop_cycle(fig_test, fig_ref):\n """Test that we can set markevery prop_cycle."""\n cases = [None, 8, (30, 8), [16, 24, 30], [0, -1],\n slice(100, 200, 3), 0.1, 0.3, 1.5,\n (0.0, 0.1), (0.45, 0.1)]\n\n cmap = mpl.colormaps['jet']\n colors = cmap(np.linspace(0.2, 0.8, len(cases)))\n\n x = np.linspace(-1, 1)\n y = 5 * x**2\n\n axs = fig_ref.add_subplot()\n for i, markevery in enumerate(cases):\n axs.plot(y - i, 'o-', markevery=markevery, color=colors[i])\n\n matplotlib.rcParams['axes.prop_cycle'] = cycler(markevery=cases,\n color=colors)\n\n ax = fig_test.add_subplot()\n for i, _ in enumerate(cases):\n ax.plot(y - i, 'o-')\n\n\ndef test_axline_setters():\n fig, ax = plt.subplots()\n line1 = ax.axline((.1, .1), slope=0.6)\n line2 = ax.axline((.1, .1), (.8, .4))\n # Testing xy1, xy2 and slope setters.\n # This should not produce an error.\n line1.set_xy1((.2, .3))\n line1.set_slope(2.4)\n line2.set_xy1((.3, .2))\n line2.set_xy2((.6, .8))\n # Testing xy1, xy2 and slope getters.\n # Should return the modified values.\n assert line1.get_xy1() == (.2, .3)\n assert line1.get_slope() == 2.4\n assert line2.get_xy1() == (.3, .2)\n assert line2.get_xy2() == (.6, .8)\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n line1.set_xy1(.2, .3)\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n line2.set_xy2(.6, .8)\n # Testing setting xy2 and slope together.\n # These test should raise a ValueError\n with pytest.raises(ValueError,\n match="Cannot set an 'xy2' value while 'slope' is set"):\n line1.set_xy2(.2, .3)\n\n with pytest.raises(ValueError,\n match="Cannot set a 'slope' value while 'xy2' is set"):\n line2.set_slope(3)\n\n\ndef test_axline_small_slope():\n """Test that small slopes are not coerced to zero in the transform."""\n line = plt.axline((0, 0), slope=1e-14)\n p1 = line.get_transform().transform_point((0, 0))\n p2 = line.get_transform().transform_point((1, 1))\n # y-values must be slightly different\n dy = p2[1] - p1[1]\n assert dy > 0\n assert dy < 4e-12\n | .venv\Lib\site-packages\matplotlib\tests\test_lines.py | test_lines.py | Python | 15,035 | 0.95 | 0.119469 | 0.112994 | react-lib | 768 | 2024-07-15T23:16:05.972618 | BSD-3-Clause | true | 326ae98092e056a397f94658a06dd081 |
import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import markers\nfrom matplotlib.path import Path\nfrom matplotlib.testing.decorators import check_figures_equal\nfrom matplotlib.transforms import Affine2D\n\nimport pytest\n\n\ndef test_marker_fillstyle():\n marker_style = markers.MarkerStyle(marker='o', fillstyle='none')\n assert marker_style.get_fillstyle() == 'none'\n assert not marker_style.is_filled()\n\n\n@pytest.mark.parametrize('marker', [\n 'o',\n 'x',\n '',\n 'None',\n r'$\frac{1}{2}$',\n "$\u266B$",\n 1,\n markers.TICKLEFT,\n [[-1, 0], [1, 0]],\n np.array([[-1, 0], [1, 0]]),\n Path([[0, 0], [1, 0]], [Path.MOVETO, Path.LINETO]),\n (5, 0), # a pentagon\n (7, 1), # a 7-pointed star\n (5, 2), # asterisk\n (5, 0, 10), # a pentagon, rotated by 10 degrees\n (7, 1, 10), # a 7-pointed star, rotated by 10 degrees\n (5, 2, 10), # asterisk, rotated by 10 degrees\n markers.MarkerStyle('o'),\n])\ndef test_markers_valid(marker):\n # Checking this doesn't fail.\n markers.MarkerStyle(marker)\n\n\n@pytest.mark.parametrize('marker', [\n 'square', # arbitrary string\n np.array([[-0.5, 0, 1, 2, 3]]), # 1D array\n (1,),\n (5, 3), # second parameter of tuple must be 0, 1, or 2\n (1, 2, 3, 4),\n])\ndef test_markers_invalid(marker):\n with pytest.raises(ValueError):\n markers.MarkerStyle(marker)\n\n\nclass UnsnappedMarkerStyle(markers.MarkerStyle):\n """\n A MarkerStyle where the snap threshold is force-disabled.\n\n This is used to compare to polygon/star/asterisk markers which do not have\n any snap threshold set.\n """\n def _recache(self):\n super()._recache()\n self._snap_threshold = None\n\n\n@check_figures_equal()\ndef test_poly_marker(fig_test, fig_ref):\n ax_test = fig_test.add_subplot()\n ax_ref = fig_ref.add_subplot()\n\n # Note, some reference sizes must be different because they have unit\n # *length*, while polygon markers are inscribed in a circle of unit\n # *radius*. This introduces a factor of np.sqrt(2), but since size is\n # squared, that becomes 2.\n size = 20**2\n\n # Squares\n ax_test.scatter([0], [0], marker=(4, 0, 45), s=size)\n ax_ref.scatter([0], [0], marker='s', s=size/2)\n\n # Diamonds, with and without rotation argument\n ax_test.scatter([1], [1], marker=(4, 0), s=size)\n ax_ref.scatter([1], [1], marker=UnsnappedMarkerStyle('D'), s=size/2)\n ax_test.scatter([1], [1.5], marker=(4, 0, 0), s=size)\n ax_ref.scatter([1], [1.5], marker=UnsnappedMarkerStyle('D'), s=size/2)\n\n # Pentagon, with and without rotation argument\n ax_test.scatter([2], [2], marker=(5, 0), s=size)\n ax_ref.scatter([2], [2], marker=UnsnappedMarkerStyle('p'), s=size)\n ax_test.scatter([2], [2.5], marker=(5, 0, 0), s=size)\n ax_ref.scatter([2], [2.5], marker=UnsnappedMarkerStyle('p'), s=size)\n\n # Hexagon, with and without rotation argument\n ax_test.scatter([3], [3], marker=(6, 0), s=size)\n ax_ref.scatter([3], [3], marker='h', s=size)\n ax_test.scatter([3], [3.5], marker=(6, 0, 0), s=size)\n ax_ref.scatter([3], [3.5], marker='h', s=size)\n\n # Rotated hexagon\n ax_test.scatter([4], [4], marker=(6, 0, 30), s=size)\n ax_ref.scatter([4], [4], marker='H', s=size)\n\n # Octagons\n ax_test.scatter([5], [5], marker=(8, 0, 22.5), s=size)\n ax_ref.scatter([5], [5], marker=UnsnappedMarkerStyle('8'), s=size)\n\n ax_test.set(xlim=(-0.5, 5.5), ylim=(-0.5, 5.5))\n ax_ref.set(xlim=(-0.5, 5.5), ylim=(-0.5, 5.5))\n\n\ndef test_star_marker():\n # We don't really have a strict equivalent to this marker, so we'll just do\n # a smoke test.\n size = 20**2\n\n fig, ax = plt.subplots()\n ax.scatter([0], [0], marker=(5, 1), s=size)\n ax.scatter([1], [1], marker=(5, 1, 0), s=size)\n ax.set(xlim=(-0.5, 0.5), ylim=(-0.5, 1.5))\n\n\n# The asterisk marker is really a star with 0-size inner circle, so the ends\n# are corners and get a slight bevel. The reference markers are just singular\n# lines without corners, so they have no bevel, and we need to add a slight\n# tolerance.\n@check_figures_equal(tol=1.45)\ndef test_asterisk_marker(fig_test, fig_ref, request):\n ax_test = fig_test.add_subplot()\n ax_ref = fig_ref.add_subplot()\n\n # Note, some reference sizes must be different because they have unit\n # *length*, while asterisk markers are inscribed in a circle of unit\n # *radius*. This introduces a factor of np.sqrt(2), but since size is\n # squared, that becomes 2.\n size = 20**2\n\n def draw_ref_marker(y, style, size):\n # As noted above, every line is doubled. Due to antialiasing, these\n # doubled lines make a slight difference in the .png results.\n ax_ref.scatter([y], [y], marker=UnsnappedMarkerStyle(style), s=size)\n if request.getfixturevalue('ext') == 'png':\n ax_ref.scatter([y], [y], marker=UnsnappedMarkerStyle(style),\n s=size)\n\n # Plus\n ax_test.scatter([0], [0], marker=(4, 2), s=size)\n draw_ref_marker(0, '+', size)\n ax_test.scatter([0.5], [0.5], marker=(4, 2, 0), s=size)\n draw_ref_marker(0.5, '+', size)\n\n # Cross\n ax_test.scatter([1], [1], marker=(4, 2, 45), s=size)\n draw_ref_marker(1, 'x', size/2)\n\n ax_test.set(xlim=(-0.5, 1.5), ylim=(-0.5, 1.5))\n ax_ref.set(xlim=(-0.5, 1.5), ylim=(-0.5, 1.5))\n\n\n# The bullet mathtext marker is not quite a circle, so this is not a perfect match, but\n# it is close enough to confirm that the text-based marker is centred correctly. But we\n# still need a small tolerance to work around that difference.\n@check_figures_equal(extensions=['png'], tol=1.86)\ndef test_text_marker(fig_ref, fig_test):\n ax_ref = fig_ref.add_subplot()\n ax_test = fig_test.add_subplot()\n\n ax_ref.plot(0, 0, marker=r'o', markersize=100, markeredgewidth=0)\n ax_test.plot(0, 0, marker=r'$\bullet$', markersize=100, markeredgewidth=0)\n\n\n@check_figures_equal()\ndef test_marker_clipping(fig_ref, fig_test):\n # Plotting multiple markers can trigger different optimized paths in\n # backends, so compare single markers vs multiple to ensure they are\n # clipped correctly.\n marker_count = len(markers.MarkerStyle.markers)\n marker_size = 50\n ncol = 7\n nrow = marker_count // ncol + 1\n\n width = 2 * marker_size * ncol\n height = 2 * marker_size * nrow * 2\n fig_ref.set_size_inches((width / fig_ref.dpi, height / fig_ref.dpi))\n ax_ref = fig_ref.add_axes([0, 0, 1, 1])\n fig_test.set_size_inches((width / fig_test.dpi, height / fig_ref.dpi))\n ax_test = fig_test.add_axes([0, 0, 1, 1])\n\n for i, marker in enumerate(markers.MarkerStyle.markers):\n x = i % ncol\n y = i // ncol * 2\n\n # Singular markers per call.\n ax_ref.plot([x, x], [y, y + 1], c='k', linestyle='-', lw=3)\n ax_ref.plot(x, y, c='k',\n marker=marker, markersize=marker_size, markeredgewidth=10,\n fillstyle='full', markerfacecolor='white')\n ax_ref.plot(x, y + 1, c='k',\n marker=marker, markersize=marker_size, markeredgewidth=10,\n fillstyle='full', markerfacecolor='white')\n\n # Multiple markers in a single call.\n ax_test.plot([x, x], [y, y + 1], c='k', linestyle='-', lw=3,\n marker=marker, markersize=marker_size, markeredgewidth=10,\n fillstyle='full', markerfacecolor='white')\n\n ax_ref.set(xlim=(-0.5, ncol), ylim=(-0.5, 2 * nrow))\n ax_test.set(xlim=(-0.5, ncol), ylim=(-0.5, 2 * nrow))\n ax_ref.axis('off')\n ax_test.axis('off')\n\n\ndef test_marker_init_transforms():\n """Test that initializing marker with transform is a simple addition."""\n marker = markers.MarkerStyle("o")\n t = Affine2D().translate(1, 1)\n t_marker = markers.MarkerStyle("o", transform=t)\n assert marker.get_transform() + t == t_marker.get_transform()\n\n\ndef test_marker_init_joinstyle():\n marker = markers.MarkerStyle("*")\n styled_marker = markers.MarkerStyle("*", joinstyle="round")\n assert styled_marker.get_joinstyle() == "round"\n assert marker.get_joinstyle() != "round"\n\n\ndef test_marker_init_captyle():\n marker = markers.MarkerStyle("*")\n styled_marker = markers.MarkerStyle("*", capstyle="round")\n assert styled_marker.get_capstyle() == "round"\n assert marker.get_capstyle() != "round"\n\n\n@pytest.mark.parametrize("marker,transform,expected", [\n (markers.MarkerStyle("o"), Affine2D().translate(1, 1),\n Affine2D().translate(1, 1)),\n (markers.MarkerStyle("o", transform=Affine2D().translate(1, 1)),\n Affine2D().translate(1, 1), Affine2D().translate(2, 2)),\n (markers.MarkerStyle("$|||$", transform=Affine2D().translate(1, 1)),\n Affine2D().translate(1, 1), Affine2D().translate(2, 2)),\n (markers.MarkerStyle(\n markers.TICKLEFT, transform=Affine2D().translate(1, 1)),\n Affine2D().translate(1, 1), Affine2D().translate(2, 2)),\n])\ndef test_marker_transformed(marker, transform, expected):\n new_marker = marker.transformed(transform)\n assert new_marker is not marker\n assert new_marker.get_user_transform() == expected\n assert marker._user_transform is not new_marker._user_transform\n\n\ndef test_marker_rotated_invalid():\n marker = markers.MarkerStyle("o")\n with pytest.raises(ValueError):\n new_marker = marker.rotated()\n with pytest.raises(ValueError):\n new_marker = marker.rotated(deg=10, rad=10)\n\n\n@pytest.mark.parametrize("marker,deg,rad,expected", [\n (markers.MarkerStyle("o"), 10, None, Affine2D().rotate_deg(10)),\n (markers.MarkerStyle("o"), None, 0.01, Affine2D().rotate(0.01)),\n (markers.MarkerStyle("o", transform=Affine2D().translate(1, 1)),\n 10, None, Affine2D().translate(1, 1).rotate_deg(10)),\n (markers.MarkerStyle("o", transform=Affine2D().translate(1, 1)),\n None, 0.01, Affine2D().translate(1, 1).rotate(0.01)),\n (markers.MarkerStyle("$|||$", transform=Affine2D().translate(1, 1)),\n 10, None, Affine2D().translate(1, 1).rotate_deg(10)),\n (markers.MarkerStyle(\n markers.TICKLEFT, transform=Affine2D().translate(1, 1)),\n 10, None, Affine2D().translate(1, 1).rotate_deg(10)),\n])\ndef test_marker_rotated(marker, deg, rad, expected):\n new_marker = marker.rotated(deg=deg, rad=rad)\n assert new_marker is not marker\n assert new_marker.get_user_transform() == expected\n assert marker._user_transform is not new_marker._user_transform\n\n\ndef test_marker_scaled():\n marker = markers.MarkerStyle("1")\n new_marker = marker.scaled(2)\n assert new_marker is not marker\n assert new_marker.get_user_transform() == Affine2D().scale(2)\n assert marker._user_transform is not new_marker._user_transform\n\n new_marker = marker.scaled(2, 3)\n assert new_marker is not marker\n assert new_marker.get_user_transform() == Affine2D().scale(2, 3)\n assert marker._user_transform is not new_marker._user_transform\n\n marker = markers.MarkerStyle("1", transform=Affine2D().translate(1, 1))\n new_marker = marker.scaled(2)\n assert new_marker is not marker\n expected = Affine2D().translate(1, 1).scale(2)\n assert new_marker.get_user_transform() == expected\n assert marker._user_transform is not new_marker._user_transform\n\n\ndef test_alt_transform():\n m1 = markers.MarkerStyle("o", "left")\n m2 = markers.MarkerStyle("o", "left", Affine2D().rotate_deg(90))\n assert m1.get_alt_transform().rotate_deg(90) == m2.get_alt_transform()\n | .venv\Lib\site-packages\matplotlib\tests\test_marker.py | test_marker.py | Python | 11,410 | 0.95 | 0.075908 | 0.134694 | vue-tools | 518 | 2024-06-09T21:30:35.660336 | MIT | true | 1f84ef36625a41756bc31ab4db5e194e |
from __future__ import annotations\n\nimport io\nfrom pathlib import Path\nimport platform\nimport re\nfrom xml.etree import ElementTree as ET\nfrom typing import Any\n\nimport numpy as np\nfrom packaging.version import parse as parse_version\nimport pyparsing\nimport pytest\n\n\nimport matplotlib as mpl\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\nimport matplotlib.pyplot as plt\nfrom matplotlib import mathtext, _mathtext\n\npyparsing_version = parse_version(pyparsing.__version__)\n\n\n# If test is removed, use None as placeholder\nmath_tests = [\n r'$a+b+\dot s+\dot{s}+\ldots$',\n r'$x\hspace{-0.2}\doteq\hspace{-0.2}y$',\n r'\$100.00 $\alpha \_$',\n r'$\frac{\$100.00}{y}$',\n r'$x y$',\n r'$x+y\ x=y\ x<y\ x:y\ x,y\ x@y$',\n r'$100\%y\ x*y\ x/y x\$y$',\n r'$x\leftarrow y\ x\forall y\ x-y$',\n r'$x \sf x \bf x {\cal X} \rm x$',\n r'$x\ x\,x\;x\quad x\qquad x\!x\hspace{ 0.5 }y$',\n r'$\{ \rm braces \}$',\n r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} y\right)\right]$',\n r'$\left(x\right)$',\n r'$\sin(x)$',\n r'$x_2$',\n r'$x^2$',\n r'$x^2_y$',\n r'$x_y^2$',\n (r'$\sum _{\genfrac{}{}{0}{}{0\leq i\leq m}{0<j<n}}f\left(i,j\right)'\n r'\mathcal{R}\prod_{i=\alpha_{i+1}}^\infty a_i \sin(2 \pi f x_i)'\n r"\sqrt[2]{\prod^\frac{x}{2\pi^2}_\infty}$"),\n r'$x = \frac{x+\frac{5}{2}}{\frac{y+3}{8}}$',\n r'$dz/dt = \gamma x^2 + {\rm sin}(2\pi y+\phi)$',\n r'Foo: $\alpha_{i+1}^j = {\rm sin}(2\pi f_j t_i) e^{-5 t_i/\tau}$',\n None,\n r'Variable $i$ is good',\n r'$\Delta_i^j$',\n r'$\Delta^j_{i+1}$',\n r'$\ddot{o}\acute{e}\grave{e}\hat{O}\breve{\imath}\tilde{n}\vec{q}$',\n r"$\arccos((x^i))$",\n r"$\gamma = \frac{x=\frac{6}{8}}{y} \delta$",\n r'$\limsup_{x\to\infty}$',\n None,\n r"$f'\quad f'''(x)\quad ''/\mathrm{yr}$",\n r'$\frac{x_2888}{y}$',\n r"$\sqrt[3]{\frac{X_2}{Y}}=5$",\n None,\n r"$\sqrt[3]{x}=5$",\n r'$\frac{X}{\frac{X}{Y}}$',\n r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$",\n r'$\mathcal{H} = \int d \tau \left(\epsilon E^2 + \mu H^2\right)$',\n r'$\widehat{abc}\widetilde{def}$',\n '$\\Gamma \\Delta \\Theta \\Lambda \\Xi \\Pi \\Sigma \\Upsilon \\Phi \\Psi \\Omega$',\n '$\\alpha \\beta \\gamma \\delta \\epsilon \\zeta \\eta \\theta \\iota \\lambda \\mu \\nu \\xi \\pi \\kappa \\rho \\sigma \\tau \\upsilon \\phi \\chi \\psi$',\n\n # The following examples are from the MathML torture test here:\n # https://www-archive.mozilla.org/projects/mathml/demo/texvsmml.xhtml\n r'${x}^{2}{y}^{2}$',\n r'${}_{2}F_{3}$',\n r'$\frac{x+{y}^{2}}{k+1}$',\n r'$x+{y}^{\frac{2}{k+1}}$',\n r'$\frac{a}{b/2}$',\n r'${a}_{0}+\frac{1}{{a}_{1}+\frac{1}{{a}_{2}+\frac{1}{{a}_{3}+\frac{1}{{a}_{4}}}}}$',\n r'${a}_{0}+\frac{1}{{a}_{1}+\frac{1}{{a}_{2}+\frac{1}{{a}_{3}+\frac{1}{{a}_{4}}}}}$',\n r'$\binom{n}{k/2}$',\n r'$\binom{p}{2}{x}^{2}{y}^{p-2}-\frac{1}{1-x}\frac{1}{1-{x}^{2}}$',\n r'${x}^{2y}$',\n r'$\sum _{i=1}^{p}\sum _{j=1}^{q}\sum _{k=1}^{r}{a}_{ij}{b}_{jk}{c}_{ki}$',\n r'$\sqrt{1+\sqrt{1+\sqrt{1+\sqrt{1+\sqrt{1+\sqrt{1+\sqrt{1+x}}}}}}}$',\n r'$\left(\frac{{\partial }^{2}}{\partial {x}^{2}}+\frac{{\partial }^{2}}{\partial {y}^{2}}\right){|\varphi \left(x+iy\right)|}^{2}=0$',\n r'${2}^{{2}^{{2}^{x}}}$',\n r'${\int }_{1}^{x}\frac{\mathrm{dt}}{t}$',\n r'$\int {\int }_{D}\mathrm{dx} \mathrm{dy}$',\n # mathtex doesn't support array\n # 'mmltt18' : r'$f\left(x\right)=\left\{\begin{array}{cc}\hfill 1/3\hfill & \text{if_}0\le x\le 1;\hfill \\ \hfill 2/3\hfill & \hfill \text{if_}3\le x\le 4;\hfill \\ \hfill 0\hfill & \text{elsewhere.}\hfill \end{array}$',\n # mathtex doesn't support stackrel\n # 'mmltt19' : r'$\stackrel{\stackrel{k\text{times}}{\ufe37}}{x+...+x}$',\n r'${y}_{{x}^{2}}$',\n # mathtex doesn't support the "\text" command\n # 'mmltt21' : r'$\sum _{p\text{\prime}}f\left(p\right)={\int }_{t>1}f\left(t\right) d\pi \left(t\right)$',\n # mathtex doesn't support array\n # 'mmltt23' : r'$\left(\begin{array}{cc}\hfill \left(\begin{array}{cc}\hfill a\hfill & \hfill b\hfill \\ \hfill c\hfill & \hfill d\hfill \end{array}\right)\hfill & \hfill \left(\begin{array}{cc}\hfill e\hfill & \hfill f\hfill \\ \hfill g\hfill & \hfill h\hfill \end{array}\right)\hfill \\ \hfill 0\hfill & \hfill \left(\begin{array}{cc}\hfill i\hfill & \hfill j\hfill \\ \hfill k\hfill & \hfill l\hfill \end{array}\right)\hfill \end{array}\right)$',\n # mathtex doesn't support array\n # 'mmltt24' : r'$det|\begin{array}{ccccc}\hfill {c}_{0}\hfill & \hfill {c}_{1}\hfill & \hfill {c}_{2}\hfill & \hfill \dots \hfill & \hfill {c}_{n}\hfill \\ \hfill {c}_{1}\hfill & \hfill {c}_{2}\hfill & \hfill {c}_{3}\hfill & \hfill \dots \hfill & \hfill {c}_{n+1}\hfill \\ \hfill {c}_{2}\hfill & \hfill {c}_{3}\hfill & \hfill {c}_{4}\hfill & \hfill \dots \hfill & \hfill {c}_{n+2}\hfill \\ \hfill \u22ee\hfill & \hfill \u22ee\hfill & \hfill \u22ee\hfill & \hfill \hfill & \hfill \u22ee\hfill \\ \hfill {c}_{n}\hfill & \hfill {c}_{n+1}\hfill & \hfill {c}_{n+2}\hfill & \hfill \dots \hfill & \hfill {c}_{2n}\hfill \end{array}|>0$',\n r'${y}_{{x}_{2}}$',\n r'${x}_{92}^{31415}+\pi $',\n r'${x}_{{y}_{b}^{a}}^{{z}_{c}^{d}}$',\n r'${y}_{3}^{\prime \prime \prime }$',\n # End of the MathML torture tests.\n\n r"$\left( \xi \left( 1 - \xi \right) \right)$", # Bug 2969451\n r"$\left(2 \, a=b\right)$", # Sage bug #8125\n r"$? ! &$", # github issue #466\n None,\n None,\n r"$\left\Vert \frac{a}{b} \right\Vert \left\vert \frac{a}{b} \right\vert \left\| \frac{a}{b}\right\| \left| \frac{a}{b} \right| \Vert a \Vert \vert b \vert \| a \| | b |$",\n r'$\mathring{A} \AA$',\n r'$M \, M \thinspace M \/ M \> M \: M \; M \ M \enspace M \quad M \qquad M \! M$',\n r'$\Cap$ $\Cup$ $\leftharpoonup$ $\barwedge$ $\rightharpoonup$',\n r'$\hspace{-0.2}\dotplus\hspace{-0.2}$ $\hspace{-0.2}\doteq\hspace{-0.2}$ $\hspace{-0.2}\doteqdot\hspace{-0.2}$ $\ddots$',\n r'$xyz^kx_kx^py^{p-2} d_i^jb_jc_kd x^j_i E^0 E^0_u$', # github issue #4873\n r'${xyz}^k{x}_{k}{x}^{p}{y}^{p-2} {d}_{i}^{j}{b}_{j}{c}_{k}{d} {x}^{j}_{i}{E}^{0}{E}^0_u$',\n r'${\int}_x^x x\oint_x^x x\int_{X}^{X}x\int_x x \int^x x \int_{x} x\int^{x}{\int}_{x} x{\int}^{x}_{x}x$',\n r'testing$^{123}$',\n None,\n r'$6-2$; $-2$; $ -2$; ${-2}$; ${ -2}$; $20^{+3}_{-2}$',\n r'$\overline{\omega}^x \frac{1}{2}_0^x$', # github issue #5444\n r'$,$ $.$ $1{,}234{, }567{ , }890$ and $1,234,567,890$', # github issue 5799\n r'$\left(X\right)_{a}^{b}$', # github issue 7615\n r'$\dfrac{\$100.00}{y}$', # github issue #1888\n r'$a=-b-c$' # github issue #28180\n]\n# 'svgastext' tests switch svg output to embed text as text (rather than as\n# paths).\nsvgastext_math_tests = [\n r'$-$-',\n]\n# 'lightweight' tests test only a single fontset (dejavusans, which is the\n# default) and only png outputs, in order to minimize the size of baseline\n# images.\nlightweight_math_tests = [\n r'$\sqrt[ab]{123}$', # github issue #8665\n r'$x \overset{f}{\rightarrow} \overset{f}{x} \underset{xx}{ff} \overset{xx}{ff} \underset{f}{x} \underset{f}{\leftarrow} x$', # github issue #18241\n r'$\sum x\quad\sum^nx\quad\sum_nx\quad\sum_n^nx\quad\prod x\quad\prod^nx\quad\prod_nx\quad\prod_n^nx$', # GitHub issue 18085\n r'$1.$ $2.$ $19680801.$ $a.$ $b.$ $mpl.$',\n r'$\text{text}_{\text{sub}}^{\text{sup}} + \text{\$foo\$} + \frac{\text{num}}{\mathbf{\text{den}}}\text{with space, curly brackets \{\}, and dash -}$',\n r'$\boldsymbol{abcde} \boldsymbol{+} \boldsymbol{\Gamma + \Omega} \boldsymbol{01234} \boldsymbol{\alpha * \beta}$',\n r'$\left\lbrace\frac{\left\lbrack A^b_c\right\rbrace}{\left\leftbrace D^e_f \right\rbrack}\right\rightbrace\ \left\leftparen\max_{x} \left\lgroup \frac{A}{B}\right\rgroup \right\rightparen$',\n r'$\left( a\middle. b \right)$ $\left( \frac{a}{b} \middle\vert x_i \in P^S \right)$ $\left[ 1 - \middle| a\middle| + \left( x - \left\lfloor \dfrac{a}{b}\right\rfloor \right) \right]$',\n r'$\sum_{\substack{k = 1\\ k \neq \lfloor n/2\rfloor}}^{n}P(i,j) \sum_{\substack{i \neq 0\\ -1 \leq i \leq 3\\ 1 \leq j \leq 5}} F^i(x,y) \sum_{\substack{\left \lfloor \frac{n}{2} \right\rfloor}} F(n)$',\n]\n\ndigits = "0123456789"\nuppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\nlowercase = "abcdefghijklmnopqrstuvwxyz"\nuppergreek = ("\\Gamma \\Delta \\Theta \\Lambda \\Xi \\Pi \\Sigma \\Upsilon \\Phi \\Psi "\n "\\Omega")\nlowergreek = ("\\alpha \\beta \\gamma \\delta \\epsilon \\zeta \\eta \\theta \\iota "\n "\\lambda \\mu \\nu \\xi \\pi \\kappa \\rho \\sigma \\tau \\upsilon "\n "\\phi \\chi \\psi")\nall = [digits, uppercase, lowercase, uppergreek, lowergreek]\n\n# Use stubs to reserve space if tests are removed\n# stub should be of the form (None, N) where N is the number of strings that\n# used to be tested\n# Add new tests at the end.\nfont_test_specs: list[tuple[None | list[str], Any]] = [\n ([], all),\n (['mathrm'], all),\n (['mathbf'], all),\n (['mathit'], all),\n (['mathtt'], [digits, uppercase, lowercase]),\n (None, 3),\n (None, 3),\n (None, 3),\n (['mathbb'], [digits, uppercase, lowercase,\n r'\Gamma \Pi \Sigma \gamma \pi']),\n (['mathrm', 'mathbb'], [digits, uppercase, lowercase,\n r'\Gamma \Pi \Sigma \gamma \pi']),\n (['mathbf', 'mathbb'], [digits, uppercase, lowercase,\n r'\Gamma \Pi \Sigma \gamma \pi']),\n (['mathcal'], [uppercase]),\n (['mathfrak'], [uppercase, lowercase]),\n (['mathbf', 'mathfrak'], [uppercase, lowercase]),\n (['mathscr'], [uppercase, lowercase]),\n (['mathsf'], [digits, uppercase, lowercase]),\n (['mathrm', 'mathsf'], [digits, uppercase, lowercase]),\n (['mathbf', 'mathsf'], [digits, uppercase, lowercase]),\n (['mathbfit'], all),\n ]\n\nfont_tests: list[None | str] = []\nfor fonts, chars in font_test_specs:\n if fonts is None:\n font_tests.extend([None] * chars)\n else:\n wrapper = ''.join([\n ' '.join(fonts),\n ' $',\n *(r'\%s{' % font for font in fonts),\n '%s',\n *('}' for font in fonts),\n '$',\n ])\n for font_set in chars:\n font_tests.append(wrapper % font_set)\n\n\n@pytest.fixture\ndef baseline_images(request, fontset, index, text):\n if text is None:\n pytest.skip("test has been removed")\n return ['%s_%s_%02d' % (request.param, fontset, index)]\n\n\n@pytest.mark.parametrize(\n 'index, text', enumerate(math_tests), ids=range(len(math_tests)))\n@pytest.mark.parametrize(\n 'fontset', ['cm', 'stix', 'stixsans', 'dejavusans', 'dejavuserif'])\n@pytest.mark.parametrize('baseline_images', ['mathtext'], indirect=True)\n@image_comparison(baseline_images=None,\n tol=0.011 if platform.machine() in ('ppc64le', 's390x') else 0)\ndef test_mathtext_rendering(baseline_images, fontset, index, text):\n mpl.rcParams['mathtext.fontset'] = fontset\n fig = plt.figure(figsize=(5.25, 0.75))\n fig.text(0.5, 0.5, text,\n horizontalalignment='center', verticalalignment='center')\n\n\n@pytest.mark.parametrize('index, text', enumerate(svgastext_math_tests),\n ids=range(len(svgastext_math_tests)))\n@pytest.mark.parametrize('fontset', ['cm', 'dejavusans'])\n@pytest.mark.parametrize('baseline_images', ['mathtext0'], indirect=True)\n@image_comparison(\n baseline_images=None, extensions=['svg'],\n savefig_kwarg={'metadata': { # Minimize image size.\n 'Creator': None, 'Date': None, 'Format': None, 'Type': None}})\ndef test_mathtext_rendering_svgastext(baseline_images, fontset, index, text):\n mpl.rcParams['mathtext.fontset'] = fontset\n mpl.rcParams['svg.fonttype'] = 'none' # Minimize image size.\n fig = plt.figure(figsize=(5.25, 0.75))\n fig.patch.set(visible=False) # Minimize image size.\n fig.text(0.5, 0.5, text,\n horizontalalignment='center', verticalalignment='center')\n\n\n@pytest.mark.parametrize('index, text', enumerate(lightweight_math_tests),\n ids=range(len(lightweight_math_tests)))\n@pytest.mark.parametrize('fontset', ['dejavusans'])\n@pytest.mark.parametrize('baseline_images', ['mathtext1'], indirect=True)\n@image_comparison(baseline_images=None, extensions=['png'])\ndef test_mathtext_rendering_lightweight(baseline_images, fontset, index, text):\n fig = plt.figure(figsize=(5.25, 0.75))\n fig.text(0.5, 0.5, text, math_fontfamily=fontset,\n horizontalalignment='center', verticalalignment='center')\n\n\n@pytest.mark.parametrize(\n 'index, text', enumerate(font_tests), ids=range(len(font_tests)))\n@pytest.mark.parametrize(\n 'fontset', ['cm', 'stix', 'stixsans', 'dejavusans', 'dejavuserif'])\n@pytest.mark.parametrize('baseline_images', ['mathfont'], indirect=True)\n@image_comparison(baseline_images=None, extensions=['png'],\n tol=0.011 if platform.machine() in ('ppc64le', 's390x') else 0)\ndef test_mathfont_rendering(baseline_images, fontset, index, text):\n mpl.rcParams['mathtext.fontset'] = fontset\n fig = plt.figure(figsize=(5.25, 0.75))\n fig.text(0.5, 0.5, text,\n horizontalalignment='center', verticalalignment='center')\n\n\n@check_figures_equal(extensions=["png"])\ndef test_short_long_accents(fig_test, fig_ref):\n acc_map = _mathtext.Parser._accent_map\n short_accs = [s for s in acc_map if len(s) == 1]\n corresponding_long_accs = []\n for s in short_accs:\n l, = (l for l in acc_map if len(l) > 1 and acc_map[l] == acc_map[s])\n corresponding_long_accs.append(l)\n fig_test.text(0, .5, "$" + "".join(rf"\{s}a" for s in short_accs) + "$")\n fig_ref.text(\n 0, .5, "$" + "".join(fr"\{l} a" for l in corresponding_long_accs) + "$")\n\n\ndef test_fontinfo():\n fontpath = mpl.font_manager.findfont("DejaVu Sans")\n font = mpl.ft2font.FT2Font(fontpath)\n table = font.get_sfnt_table("head")\n assert table is not None\n assert table['version'] == (1, 0)\n\n\n# See gh-26152 for more context on this xfail\n@pytest.mark.xfail(pyparsing_version.release == (3, 1, 0),\n reason="Error messages are incorrect for this version")\n@pytest.mark.parametrize(\n 'math, msg',\n [\n (r'$\hspace{}$', r'Expected \hspace{space}'),\n (r'$\hspace{foo}$', r'Expected \hspace{space}'),\n (r'$\sinx$', r'Unknown symbol: \sinx'),\n (r'$\dotx$', r'Unknown symbol: \dotx'),\n (r'$\frac$', r'Expected \frac{num}{den}'),\n (r'$\frac{}{}$', r'Expected \frac{num}{den}'),\n (r'$\binom$', r'Expected \binom{num}{den}'),\n (r'$\binom{}{}$', r'Expected \binom{num}{den}'),\n (r'$\genfrac$',\n r'Expected \genfrac{ldelim}{rdelim}{rulesize}{style}{num}{den}'),\n (r'$\genfrac{}{}{}{}{}{}$',\n r'Expected \genfrac{ldelim}{rdelim}{rulesize}{style}{num}{den}'),\n (r'$\sqrt$', r'Expected \sqrt{value}'),\n (r'$\sqrt f$', r'Expected \sqrt{value}'),\n (r'$\overline$', r'Expected \overline{body}'),\n (r'$\overline{}$', r'Expected \overline{body}'),\n (r'$\leftF$', r'Expected a delimiter'),\n (r'$\rightF$', r'Unknown symbol: \rightF'),\n (r'$\left(\right$', r'Expected a delimiter'),\n # PyParsing 2 uses double quotes, PyParsing 3 uses single quotes and an\n # extra backslash.\n (r'$\left($', re.compile(r'Expected ("|\'\\)\\right["\']')),\n (r'$\dfrac$', r'Expected \dfrac{num}{den}'),\n (r'$\dfrac{}{}$', r'Expected \dfrac{num}{den}'),\n (r'$\overset$', r'Expected \overset{annotation}{body}'),\n (r'$\underset$', r'Expected \underset{annotation}{body}'),\n (r'$\foo$', r'Unknown symbol: \foo'),\n (r'$a^2^2$', r'Double superscript'),\n (r'$a_2_2$', r'Double subscript'),\n (r'$a^2_a^2$', r'Double superscript'),\n (r'$a = {b$', r"Expected '}'"),\n ],\n ids=[\n 'hspace without value',\n 'hspace with invalid value',\n 'function without space',\n 'accent without space',\n 'frac without parameters',\n 'frac with empty parameters',\n 'binom without parameters',\n 'binom with empty parameters',\n 'genfrac without parameters',\n 'genfrac with empty parameters',\n 'sqrt without parameters',\n 'sqrt with invalid value',\n 'overline without parameters',\n 'overline with empty parameter',\n 'left with invalid delimiter',\n 'right with invalid delimiter',\n 'unclosed parentheses with sizing',\n 'unclosed parentheses without sizing',\n 'dfrac without parameters',\n 'dfrac with empty parameters',\n 'overset without parameters',\n 'underset without parameters',\n 'unknown symbol',\n 'double superscript',\n 'double subscript',\n 'super on sub without braces',\n 'unclosed group',\n ]\n)\ndef test_mathtext_exceptions(math, msg):\n parser = mathtext.MathTextParser('agg')\n match = re.escape(msg) if isinstance(msg, str) else msg\n with pytest.raises(ValueError, match=match):\n parser.parse(math)\n\n\ndef test_get_unicode_index_exception():\n with pytest.raises(ValueError):\n _mathtext.get_unicode_index(r'\foo')\n\n\ndef test_single_minus_sign():\n fig = plt.figure()\n fig.text(0.5, 0.5, '$-$')\n fig.canvas.draw()\n t = np.asarray(fig.canvas.renderer.buffer_rgba())\n assert (t != 0xff).any() # assert that canvas is not all white.\n\n\n@check_figures_equal(extensions=["png"])\ndef test_spaces(fig_test, fig_ref):\n fig_test.text(.5, .5, r"$1\,2\>3\ 4$")\n fig_ref.text(.5, .5, r"$1\/2\:3~4$")\n\n\n@check_figures_equal(extensions=["png"])\ndef test_operator_space(fig_test, fig_ref):\n fig_test.text(0.1, 0.1, r"$\log 6$")\n fig_test.text(0.1, 0.2, r"$\log(6)$")\n fig_test.text(0.1, 0.3, r"$\arcsin 6$")\n fig_test.text(0.1, 0.4, r"$\arcsin|6|$")\n fig_test.text(0.1, 0.5, r"$\operatorname{op} 6$") # GitHub issue #553\n fig_test.text(0.1, 0.6, r"$\operatorname{op}[6]$")\n fig_test.text(0.1, 0.7, r"$\cos^2$")\n fig_test.text(0.1, 0.8, r"$\log_2$")\n fig_test.text(0.1, 0.9, r"$\sin^2 \cos$") # GitHub issue #17852\n\n fig_ref.text(0.1, 0.1, r"$\mathrm{log\,}6$")\n fig_ref.text(0.1, 0.2, r"$\mathrm{log}(6)$")\n fig_ref.text(0.1, 0.3, r"$\mathrm{arcsin\,}6$")\n fig_ref.text(0.1, 0.4, r"$\mathrm{arcsin}|6|$")\n fig_ref.text(0.1, 0.5, r"$\mathrm{op\,}6$")\n fig_ref.text(0.1, 0.6, r"$\mathrm{op}[6]$")\n fig_ref.text(0.1, 0.7, r"$\mathrm{cos}^2$")\n fig_ref.text(0.1, 0.8, r"$\mathrm{log}_2$")\n fig_ref.text(0.1, 0.9, r"$\mathrm{sin}^2 \mathrm{\,cos}$")\n\n\n@check_figures_equal(extensions=["png"])\ndef test_inverted_delimiters(fig_test, fig_ref):\n fig_test.text(.5, .5, r"$\left)\right($", math_fontfamily="dejavusans")\n fig_ref.text(.5, .5, r"$)($", math_fontfamily="dejavusans")\n\n\n@check_figures_equal(extensions=["png"])\ndef test_genfrac_displaystyle(fig_test, fig_ref):\n fig_test.text(0.1, 0.1, r"$\dfrac{2x}{3y}$")\n\n thickness = _mathtext.TruetypeFonts.get_underline_thickness(\n None, None, fontsize=mpl.rcParams["font.size"],\n dpi=mpl.rcParams["savefig.dpi"])\n fig_ref.text(0.1, 0.1, r"$\genfrac{}{}{%f}{0}{2x}{3y}$" % thickness)\n\n\ndef test_mathtext_fallback_valid():\n for fallback in ['cm', 'stix', 'stixsans', 'None']:\n mpl.rcParams['mathtext.fallback'] = fallback\n\n\ndef test_mathtext_fallback_invalid():\n for fallback in ['abc', '']:\n with pytest.raises(ValueError, match="not a valid fallback font name"):\n mpl.rcParams['mathtext.fallback'] = fallback\n\n\n@pytest.mark.parametrize(\n "fallback,fontlist",\n [("cm", ['DejaVu Sans', 'mpltest', 'STIXGeneral', 'cmr10', 'STIXGeneral']),\n ("stix", ['DejaVu Sans', 'mpltest', 'STIXGeneral', 'STIXGeneral', 'STIXGeneral'])])\ndef test_mathtext_fallback(fallback, fontlist):\n mpl.font_manager.fontManager.addfont(\n str(Path(__file__).resolve().parent / 'mpltest.ttf'))\n mpl.rcParams["svg.fonttype"] = 'none'\n mpl.rcParams['mathtext.fontset'] = 'custom'\n mpl.rcParams['mathtext.rm'] = 'mpltest'\n mpl.rcParams['mathtext.it'] = 'mpltest:italic'\n mpl.rcParams['mathtext.bf'] = 'mpltest:bold'\n mpl.rcParams['mathtext.bfit'] = 'mpltest:italic:bold'\n mpl.rcParams['mathtext.fallback'] = fallback\n\n test_str = r'a$A\AA\breve\gimel$'\n\n buff = io.BytesIO()\n fig, ax = plt.subplots()\n fig.text(.5, .5, test_str, fontsize=40, ha='center')\n fig.savefig(buff, format="svg")\n tspans = (ET.fromstring(buff.getvalue())\n .findall(".//{http://www.w3.org/2000/svg}tspan[@style]"))\n char_fonts = [\n re.search(r"font-family: '([\w ]+)'", tspan.attrib["style"]).group(1)\n for tspan in tspans]\n assert char_fonts == fontlist, f'Expected {fontlist}, got {char_fonts}'\n mpl.font_manager.fontManager.ttflist.pop()\n\n\ndef test_math_to_image(tmp_path):\n mathtext.math_to_image('$x^2$', tmp_path / 'example.png')\n mathtext.math_to_image('$x^2$', io.BytesIO())\n mathtext.math_to_image('$x^2$', io.BytesIO(), color='Maroon')\n\n\n@image_comparison(baseline_images=['math_fontfamily_image.png'],\n savefig_kwarg={'dpi': 40})\ndef test_math_fontfamily():\n fig = plt.figure(figsize=(10, 3))\n fig.text(0.2, 0.7, r"$This\ text\ should\ have\ one\ font$",\n size=24, math_fontfamily='dejavusans')\n fig.text(0.2, 0.3, r"$This\ text\ should\ have\ another$",\n size=24, math_fontfamily='stix')\n\n\ndef test_default_math_fontfamily():\n mpl.rcParams['mathtext.fontset'] = 'cm'\n test_str = r'abc$abc\alpha$'\n fig, ax = plt.subplots()\n\n text1 = fig.text(0.1, 0.1, test_str, font='Arial')\n prop1 = text1.get_fontproperties()\n assert prop1.get_math_fontfamily() == 'cm'\n text2 = fig.text(0.2, 0.2, test_str, fontproperties='Arial')\n prop2 = text2.get_fontproperties()\n assert prop2.get_math_fontfamily() == 'cm'\n\n fig.draw_without_rendering()\n\n\ndef test_argument_order():\n mpl.rcParams['mathtext.fontset'] = 'cm'\n test_str = r'abc$abc\alpha$'\n fig, ax = plt.subplots()\n\n text1 = fig.text(0.1, 0.1, test_str,\n math_fontfamily='dejavusans', font='Arial')\n prop1 = text1.get_fontproperties()\n assert prop1.get_math_fontfamily() == 'dejavusans'\n text2 = fig.text(0.2, 0.2, test_str,\n math_fontfamily='dejavusans', fontproperties='Arial')\n prop2 = text2.get_fontproperties()\n assert prop2.get_math_fontfamily() == 'dejavusans'\n text3 = fig.text(0.3, 0.3, test_str,\n font='Arial', math_fontfamily='dejavusans')\n prop3 = text3.get_fontproperties()\n assert prop3.get_math_fontfamily() == 'dejavusans'\n text4 = fig.text(0.4, 0.4, test_str,\n fontproperties='Arial', math_fontfamily='dejavusans')\n prop4 = text4.get_fontproperties()\n assert prop4.get_math_fontfamily() == 'dejavusans'\n\n fig.draw_without_rendering()\n\n\ndef test_mathtext_cmr10_minus_sign():\n # cmr10 does not contain a minus sign and used to issue a warning\n # RuntimeWarning: Glyph 8722 missing from current font.\n mpl.rcParams['font.family'] = 'cmr10'\n mpl.rcParams['axes.formatter.use_mathtext'] = True\n fig, ax = plt.subplots()\n ax.plot(range(-1, 1), range(-1, 1))\n # draw to make sure we have no warnings\n fig.canvas.draw()\n\n\ndef test_mathtext_operators():\n test_str = r'''\n \increment \smallin \notsmallowns\n \smallowns \QED \rightangle\n \smallintclockwise \smallvarointclockwise\n \smallointctrcclockwise\n \ratio \minuscolon \dotsminusdots\n \sinewave \simneqq \nlesssim\n \ngtrsim \nlessgtr \ngtrless\n \cupleftarrow \oequal \rightassert\n \rightModels \hermitmatrix \barvee\n \measuredrightangle \varlrtriangle\n \equalparallel \npreccurlyeq \nsucccurlyeq\n \nsqsubseteq \nsqsupseteq \sqsubsetneq\n \sqsupsetneq \disin \varisins\n \isins \isindot \varisinobar\n \isinobar \isinvb \isinE\n \nisd \varnis \nis\n \varniobar \niobar \bagmember\n \triangle'''.split()\n\n fig = plt.figure()\n for x, i in enumerate(test_str):\n fig.text(0.5, (x + 0.5)/len(test_str), r'${%s}$' % i)\n\n fig.draw_without_rendering()\n\n\n@check_figures_equal(extensions=["png"])\ndef test_boldsymbol(fig_test, fig_ref):\n fig_test.text(0.1, 0.2, r"$\boldsymbol{\mathrm{abc0123\alpha}}$")\n fig_ref.text(0.1, 0.2, r"$\mathrm{abc0123\alpha}$")\n | .venv\Lib\site-packages\matplotlib\tests\test_mathtext.py | test_mathtext.py | Python | 24,549 | 0.95 | 0.089286 | 0.063265 | node-utils | 700 | 2023-10-18T03:29:46.220394 | MIT | true | 26de6bdb395814223b4c57353c9b8c48 |
import os\nimport subprocess\nimport sys\n\nimport pytest\n\nimport matplotlib\nfrom matplotlib.testing import subprocess_run_for_testing\n\n\n@pytest.mark.parametrize('version_str, version_tuple', [\n ('3.5.0', (3, 5, 0, 'final', 0)),\n ('3.5.0rc2', (3, 5, 0, 'candidate', 2)),\n ('3.5.0.dev820+g6768ef8c4c', (3, 5, 0, 'alpha', 820)),\n ('3.5.0.post820+g6768ef8c4c', (3, 5, 1, 'alpha', 820)),\n])\ndef test_parse_to_version_info(version_str, version_tuple):\n assert matplotlib._parse_to_version_info(version_str) == version_tuple\n\n\n@pytest.mark.skipif(sys.platform == "win32",\n reason="chmod() doesn't work as is on Windows")\n@pytest.mark.skipif(sys.platform != "win32" and os.geteuid() == 0,\n reason="chmod() doesn't work as root")\ndef test_tmpconfigdir_warning(tmp_path):\n """Test that a warning is emitted if a temporary configdir must be used."""\n mode = os.stat(tmp_path).st_mode\n try:\n os.chmod(tmp_path, 0)\n proc = subprocess_run_for_testing(\n [sys.executable, "-c", "import matplotlib"],\n env={**os.environ, "MPLCONFIGDIR": str(tmp_path)},\n stderr=subprocess.PIPE, text=True, check=True)\n assert "set the MPLCONFIGDIR" in proc.stderr\n finally:\n os.chmod(tmp_path, mode)\n\n\ndef test_importable_with_no_home(tmp_path):\n subprocess_run_for_testing(\n [sys.executable, "-c",\n "import pathlib; pathlib.Path.home = lambda *args: 1/0; "\n "import matplotlib.pyplot"],\n env={**os.environ, "MPLCONFIGDIR": str(tmp_path)}, check=True)\n\n\ndef test_use_doc_standard_backends():\n """\n Test that the standard backends mentioned in the docstring of\n matplotlib.use() are the same as in matplotlib.rcsetup.\n """\n def parse(key):\n backends = []\n for line in matplotlib.use.__doc__.split(key)[1].split('\n'):\n if not line.strip():\n break\n backends += [e.strip().lower() for e in line.split(',') if e]\n return backends\n\n from matplotlib.backends import BackendFilter, backend_registry\n\n assert (set(parse('- interactive backends:\n')) ==\n set(backend_registry.list_builtin(BackendFilter.INTERACTIVE)))\n assert (set(parse('- non-interactive backends:\n')) ==\n set(backend_registry.list_builtin(BackendFilter.NON_INTERACTIVE)))\n\n\ndef test_importable_with__OO():\n """\n When using -OO or export PYTHONOPTIMIZE=2, docstrings are discarded,\n this simple test may prevent something like issue #17970.\n """\n program = (\n "import matplotlib as mpl; "\n "import matplotlib.pyplot as plt; "\n "import matplotlib.cbook as cbook; "\n "import matplotlib.patches as mpatches"\n )\n subprocess_run_for_testing(\n [sys.executable, "-OO", "-c", program],\n env={**os.environ, "MPLBACKEND": ""}, check=True\n )\n | .venv\Lib\site-packages\matplotlib\tests\test_matplotlib.py | test_matplotlib.py | Python | 2,887 | 0.95 | 0.146341 | 0 | react-lib | 945 | 2023-08-20T18:05:19.979353 | GPL-3.0 | true | 9f41795ede005a7b4010f7ec4caa4387 |
from numpy.testing import (assert_allclose, assert_almost_equal,\n assert_array_equal, assert_array_almost_equal_nulp)\nimport numpy as np\nimport pytest\n\nfrom matplotlib import mlab\n\n\ndef test_window():\n np.random.seed(0)\n n = 1000\n rand = np.random.standard_normal(n) + 100\n ones = np.ones(n)\n assert_array_equal(mlab.window_none(ones), ones)\n assert_array_equal(mlab.window_none(rand), rand)\n assert_array_equal(np.hanning(len(rand)) * rand, mlab.window_hanning(rand))\n assert_array_equal(np.hanning(len(ones)), mlab.window_hanning(ones))\n\n\nclass TestDetrend:\n def setup_method(self):\n np.random.seed(0)\n n = 1000\n x = np.linspace(0., 100, n)\n\n self.sig_zeros = np.zeros(n)\n\n self.sig_off = self.sig_zeros + 100.\n self.sig_slope = np.linspace(-10., 90., n)\n self.sig_slope_mean = x - x.mean()\n\n self.sig_base = (\n np.random.standard_normal(n) + np.sin(x*2*np.pi/(n/100)))\n self.sig_base -= self.sig_base.mean()\n\n def allclose(self, *args):\n assert_allclose(*args, atol=1e-8)\n\n def test_detrend_none(self):\n assert mlab.detrend_none(0.) == 0.\n assert mlab.detrend_none(0., axis=1) == 0.\n assert mlab.detrend(0., key="none") == 0.\n assert mlab.detrend(0., key=mlab.detrend_none) == 0.\n for sig in [\n 5.5, self.sig_off, self.sig_slope, self.sig_base,\n (self.sig_base + self.sig_slope + self.sig_off).tolist(),\n np.vstack([self.sig_base, # 2D case.\n self.sig_base + self.sig_off,\n self.sig_base + self.sig_slope,\n self.sig_base + self.sig_off + self.sig_slope]),\n np.vstack([self.sig_base, # 2D transposed case.\n self.sig_base + self.sig_off,\n self.sig_base + self.sig_slope,\n self.sig_base + self.sig_off + self.sig_slope]).T,\n ]:\n if isinstance(sig, np.ndarray):\n assert_array_equal(mlab.detrend_none(sig), sig)\n else:\n assert mlab.detrend_none(sig) == sig\n\n def test_detrend_mean(self):\n for sig in [0., 5.5]: # 0D.\n assert mlab.detrend_mean(sig) == 0.\n assert mlab.detrend(sig, key="mean") == 0.\n assert mlab.detrend(sig, key=mlab.detrend_mean) == 0.\n # 1D.\n self.allclose(mlab.detrend_mean(self.sig_zeros), self.sig_zeros)\n self.allclose(mlab.detrend_mean(self.sig_base), self.sig_base)\n self.allclose(mlab.detrend_mean(self.sig_base + self.sig_off),\n self.sig_base)\n self.allclose(mlab.detrend_mean(self.sig_base + self.sig_slope),\n self.sig_base + self.sig_slope_mean)\n self.allclose(\n mlab.detrend_mean(self.sig_base + self.sig_slope + self.sig_off),\n self.sig_base + self.sig_slope_mean)\n\n def test_detrend_mean_1d_base_slope_off_list_andor_axis0(self):\n input = self.sig_base + self.sig_slope + self.sig_off\n target = self.sig_base + self.sig_slope_mean\n self.allclose(mlab.detrend_mean(input, axis=0), target)\n self.allclose(mlab.detrend_mean(input.tolist()), target)\n self.allclose(mlab.detrend_mean(input.tolist(), axis=0), target)\n\n def test_detrend_mean_2d(self):\n input = np.vstack([self.sig_off,\n self.sig_base + self.sig_off])\n target = np.vstack([self.sig_zeros,\n self.sig_base])\n self.allclose(mlab.detrend_mean(input), target)\n self.allclose(mlab.detrend_mean(input, axis=None), target)\n self.allclose(mlab.detrend_mean(input.T, axis=None).T, target)\n self.allclose(mlab.detrend(input), target)\n self.allclose(mlab.detrend(input, axis=None), target)\n self.allclose(\n mlab.detrend(input.T, key="constant", axis=None), target.T)\n\n input = np.vstack([self.sig_base,\n self.sig_base + self.sig_off,\n self.sig_base + self.sig_slope,\n self.sig_base + self.sig_off + self.sig_slope])\n target = np.vstack([self.sig_base,\n self.sig_base,\n self.sig_base + self.sig_slope_mean,\n self.sig_base + self.sig_slope_mean])\n self.allclose(mlab.detrend_mean(input.T, axis=0), target.T)\n self.allclose(mlab.detrend_mean(input, axis=1), target)\n self.allclose(mlab.detrend_mean(input, axis=-1), target)\n self.allclose(mlab.detrend(input, key="default", axis=1), target)\n self.allclose(mlab.detrend(input.T, key="mean", axis=0), target.T)\n self.allclose(\n mlab.detrend(input.T, key=mlab.detrend_mean, axis=0), target.T)\n\n def test_detrend_ValueError(self):\n for signal, kwargs in [\n (self.sig_slope[np.newaxis], {"key": "spam"}),\n (self.sig_slope[np.newaxis], {"key": 5}),\n (5.5, {"axis": 0}),\n (self.sig_slope, {"axis": 1}),\n (self.sig_slope[np.newaxis], {"axis": 2}),\n ]:\n with pytest.raises(ValueError):\n mlab.detrend(signal, **kwargs)\n\n def test_detrend_mean_ValueError(self):\n for signal, kwargs in [\n (5.5, {"axis": 0}),\n (self.sig_slope, {"axis": 1}),\n (self.sig_slope[np.newaxis], {"axis": 2}),\n ]:\n with pytest.raises(ValueError):\n mlab.detrend_mean(signal, **kwargs)\n\n def test_detrend_linear(self):\n # 0D.\n assert mlab.detrend_linear(0.) == 0.\n assert mlab.detrend_linear(5.5) == 0.\n assert mlab.detrend(5.5, key="linear") == 0.\n assert mlab.detrend(5.5, key=mlab.detrend_linear) == 0.\n for sig in [ # 1D.\n self.sig_off,\n self.sig_slope,\n self.sig_slope + self.sig_off,\n ]:\n self.allclose(mlab.detrend_linear(sig), self.sig_zeros)\n\n def test_detrend_str_linear_1d(self):\n input = self.sig_slope + self.sig_off\n target = self.sig_zeros\n self.allclose(mlab.detrend(input, key="linear"), target)\n self.allclose(mlab.detrend(input, key=mlab.detrend_linear), target)\n self.allclose(mlab.detrend_linear(input.tolist()), target)\n\n def test_detrend_linear_2d(self):\n input = np.vstack([self.sig_off,\n self.sig_slope,\n self.sig_slope + self.sig_off])\n target = np.vstack([self.sig_zeros,\n self.sig_zeros,\n self.sig_zeros])\n self.allclose(\n mlab.detrend(input.T, key="linear", axis=0), target.T)\n self.allclose(\n mlab.detrend(input.T, key=mlab.detrend_linear, axis=0), target.T)\n self.allclose(\n mlab.detrend(input, key="linear", axis=1), target)\n self.allclose(\n mlab.detrend(input, key=mlab.detrend_linear, axis=1), target)\n\n with pytest.raises(ValueError):\n mlab.detrend_linear(self.sig_slope[np.newaxis])\n\n\n@pytest.mark.parametrize('iscomplex', [False, True],\n ids=['real', 'complex'], scope='class')\n@pytest.mark.parametrize('sides', ['onesided', 'twosided', 'default'],\n scope='class')\n@pytest.mark.parametrize(\n 'fstims,len_x,NFFT_density,nover_density,pad_to_density,pad_to_spectrum',\n [\n ([], None, -1, -1, -1, -1),\n ([4], None, -1, -1, -1, -1),\n ([4, 5, 10], None, -1, -1, -1, -1),\n ([], None, None, -1, -1, None),\n ([], None, -1, -1, None, None),\n ([], None, None, -1, None, None),\n ([], 1024, 512, -1, -1, 128),\n ([], 256, -1, -1, 33, 257),\n ([], 255, 33, -1, -1, None),\n ([], 256, 128, -1, 256, 256),\n ([], None, -1, 32, -1, -1),\n ],\n ids=[\n 'nosig',\n 'Fs4',\n 'FsAll',\n 'nosig_noNFFT',\n 'nosig_nopad_to',\n 'nosig_noNFFT_no_pad_to',\n 'nosig_trim',\n 'nosig_odd',\n 'nosig_oddlen',\n 'nosig_stretch',\n 'nosig_overlap',\n ],\n scope='class')\nclass TestSpectral:\n @pytest.fixture(scope='class', autouse=True)\n def stim(self, request, fstims, iscomplex, sides, len_x, NFFT_density,\n nover_density, pad_to_density, pad_to_spectrum):\n Fs = 100.\n\n x = np.arange(0, 10, 1 / Fs)\n if len_x is not None:\n x = x[:len_x]\n\n # get the stimulus frequencies, defaulting to None\n fstims = [Fs / fstim for fstim in fstims]\n\n # get the constants, default to calculated values\n if NFFT_density is None:\n NFFT_density_real = 256\n elif NFFT_density < 0:\n NFFT_density_real = NFFT_density = 100\n else:\n NFFT_density_real = NFFT_density\n\n if nover_density is None:\n nover_density_real = 0\n elif nover_density < 0:\n nover_density_real = nover_density = NFFT_density_real // 2\n else:\n nover_density_real = nover_density\n\n if pad_to_density is None:\n pad_to_density_real = NFFT_density_real\n elif pad_to_density < 0:\n pad_to_density = int(2**np.ceil(np.log2(NFFT_density_real)))\n pad_to_density_real = pad_to_density\n else:\n pad_to_density_real = pad_to_density\n\n if pad_to_spectrum is None:\n pad_to_spectrum_real = len(x)\n elif pad_to_spectrum < 0:\n pad_to_spectrum_real = pad_to_spectrum = len(x)\n else:\n pad_to_spectrum_real = pad_to_spectrum\n\n if pad_to_spectrum is None:\n NFFT_spectrum_real = NFFT_spectrum = pad_to_spectrum_real\n else:\n NFFT_spectrum_real = NFFT_spectrum = len(x)\n nover_spectrum = 0\n\n NFFT_specgram = NFFT_density\n nover_specgram = nover_density\n pad_to_specgram = pad_to_density\n NFFT_specgram_real = NFFT_density_real\n nover_specgram_real = nover_density_real\n\n if sides == 'onesided' or (sides == 'default' and not iscomplex):\n # frequencies for specgram, psd, and csd\n # need to handle even and odd differently\n if pad_to_density_real % 2:\n freqs_density = np.linspace(0, Fs / 2,\n num=pad_to_density_real,\n endpoint=False)[::2]\n else:\n freqs_density = np.linspace(0, Fs / 2,\n num=pad_to_density_real // 2 + 1)\n\n # frequencies for complex, magnitude, angle, and phase spectrums\n # need to handle even and odd differently\n if pad_to_spectrum_real % 2:\n freqs_spectrum = np.linspace(0, Fs / 2,\n num=pad_to_spectrum_real,\n endpoint=False)[::2]\n else:\n freqs_spectrum = np.linspace(0, Fs / 2,\n num=pad_to_spectrum_real // 2 + 1)\n else:\n # frequencies for specgram, psd, and csd\n # need to handle even and odd differently\n if pad_to_density_real % 2:\n freqs_density = np.linspace(-Fs / 2, Fs / 2,\n num=2 * pad_to_density_real,\n endpoint=False)[1::2]\n else:\n freqs_density = np.linspace(-Fs / 2, Fs / 2,\n num=pad_to_density_real,\n endpoint=False)\n\n # frequencies for complex, magnitude, angle, and phase spectrums\n # need to handle even and odd differently\n if pad_to_spectrum_real % 2:\n freqs_spectrum = np.linspace(-Fs / 2, Fs / 2,\n num=2 * pad_to_spectrum_real,\n endpoint=False)[1::2]\n else:\n freqs_spectrum = np.linspace(-Fs / 2, Fs / 2,\n num=pad_to_spectrum_real,\n endpoint=False)\n\n freqs_specgram = freqs_density\n # time points for specgram\n t_start = NFFT_specgram_real // 2\n t_stop = len(x) - NFFT_specgram_real // 2 + 1\n t_step = NFFT_specgram_real - nover_specgram_real\n t_specgram = x[t_start:t_stop:t_step]\n if NFFT_specgram_real % 2:\n t_specgram += 1 / Fs / 2\n if len(t_specgram) == 0:\n t_specgram = np.array([NFFT_specgram_real / (2 * Fs)])\n t_spectrum = np.array([NFFT_spectrum_real / (2 * Fs)])\n t_density = t_specgram\n\n y = np.zeros_like(x)\n for i, fstim in enumerate(fstims):\n y += np.sin(fstim * x * np.pi * 2) * 10**i\n\n if iscomplex:\n y = y.astype('complex')\n\n # Interestingly, the instance on which this fixture is called is not\n # the same as the one on which a test is run. So we need to modify the\n # class itself when using a class-scoped fixture.\n cls = request.cls\n\n cls.Fs = Fs\n cls.sides = sides\n cls.fstims = fstims\n\n cls.NFFT_density = NFFT_density\n cls.nover_density = nover_density\n cls.pad_to_density = pad_to_density\n\n cls.NFFT_spectrum = NFFT_spectrum\n cls.nover_spectrum = nover_spectrum\n cls.pad_to_spectrum = pad_to_spectrum\n\n cls.NFFT_specgram = NFFT_specgram\n cls.nover_specgram = nover_specgram\n cls.pad_to_specgram = pad_to_specgram\n\n cls.t_specgram = t_specgram\n cls.t_density = t_density\n cls.t_spectrum = t_spectrum\n cls.y = y\n\n cls.freqs_density = freqs_density\n cls.freqs_spectrum = freqs_spectrum\n cls.freqs_specgram = freqs_specgram\n\n cls.NFFT_density_real = NFFT_density_real\n\n def check_freqs(self, vals, targfreqs, resfreqs, fstims):\n assert resfreqs.argmin() == 0\n assert resfreqs.argmax() == len(resfreqs)-1\n assert_allclose(resfreqs, targfreqs, atol=1e-06)\n for fstim in fstims:\n i = np.abs(resfreqs - fstim).argmin()\n assert vals[i] > vals[i+2]\n assert vals[i] > vals[i-2]\n\n def check_maxfreq(self, spec, fsp, fstims):\n # skip the test if there are no frequencies\n if len(fstims) == 0:\n return\n\n # if twosided, do the test for each side\n if fsp.min() < 0:\n fspa = np.abs(fsp)\n zeroind = fspa.argmin()\n self.check_maxfreq(spec[:zeroind], fspa[:zeroind], fstims)\n self.check_maxfreq(spec[zeroind:], fspa[zeroind:], fstims)\n return\n\n fstimst = fstims[:]\n spect = spec.copy()\n\n # go through each peak and make sure it is correctly the maximum peak\n while fstimst:\n maxind = spect.argmax()\n maxfreq = fsp[maxind]\n assert_almost_equal(maxfreq, fstimst[-1])\n del fstimst[-1]\n spect[maxind-5:maxind+5] = 0\n\n def test_spectral_helper_raises(self):\n # We don't use parametrize here to handle ``y = self.y``.\n for kwargs in [ # Various error conditions:\n {"y": self.y+1, "mode": "complex"}, # Modes requiring ``x is y``.\n {"y": self.y+1, "mode": "magnitude"},\n {"y": self.y+1, "mode": "angle"},\n {"y": self.y+1, "mode": "phase"},\n {"mode": "spam"}, # Bad mode.\n {"y": self.y, "sides": "eggs"}, # Bad sides.\n {"y": self.y, "NFFT": 10, "noverlap": 20}, # noverlap > NFFT.\n {"NFFT": 10, "noverlap": 10}, # noverlap == NFFT.\n {"y": self.y, "NFFT": 10,\n "window": np.ones(9)}, # len(win) != NFFT.\n ]:\n with pytest.raises(ValueError):\n mlab._spectral_helper(x=self.y, **kwargs)\n\n @pytest.mark.parametrize('mode', ['default', 'psd'])\n def test_single_spectrum_helper_unsupported_modes(self, mode):\n with pytest.raises(ValueError):\n mlab._single_spectrum_helper(x=self.y, mode=mode)\n\n @pytest.mark.parametrize("mode, case", [\n ("psd", "density"),\n ("magnitude", "specgram"),\n ("magnitude", "spectrum"),\n ])\n def test_spectral_helper_psd(self, mode, case):\n freqs = getattr(self, f"freqs_{case}")\n spec, fsp, t = mlab._spectral_helper(\n x=self.y, y=self.y,\n NFFT=getattr(self, f"NFFT_{case}"),\n Fs=self.Fs,\n noverlap=getattr(self, f"nover_{case}"),\n pad_to=getattr(self, f"pad_to_{case}"),\n sides=self.sides,\n mode=mode)\n\n assert_allclose(fsp, freqs, atol=1e-06)\n assert_allclose(t, getattr(self, f"t_{case}"), atol=1e-06)\n assert spec.shape[0] == freqs.shape[0]\n assert spec.shape[1] == getattr(self, f"t_{case}").shape[0]\n\n def test_csd(self):\n freqs = self.freqs_density\n spec, fsp = mlab.csd(x=self.y, y=self.y+1,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=self.nover_density,\n pad_to=self.pad_to_density,\n sides=self.sides)\n assert_allclose(fsp, freqs, atol=1e-06)\n assert spec.shape == freqs.shape\n\n def test_csd_padding(self):\n """Test zero padding of csd()."""\n if self.NFFT_density is None: # for derived classes\n return\n sargs = dict(x=self.y, y=self.y+1, Fs=self.Fs, window=mlab.window_none,\n sides=self.sides)\n\n spec0, _ = mlab.csd(NFFT=self.NFFT_density, **sargs)\n spec1, _ = mlab.csd(NFFT=self.NFFT_density*2, **sargs)\n assert_almost_equal(np.sum(np.conjugate(spec0)*spec0).real,\n np.sum(np.conjugate(spec1/2)*spec1/2).real)\n\n def test_psd(self):\n freqs = self.freqs_density\n spec, fsp = mlab.psd(x=self.y,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=self.nover_density,\n pad_to=self.pad_to_density,\n sides=self.sides)\n assert spec.shape == freqs.shape\n self.check_freqs(spec, freqs, fsp, self.fstims)\n\n @pytest.mark.parametrize(\n 'make_data, detrend',\n [(np.zeros, mlab.detrend_mean), (np.zeros, 'mean'),\n (np.arange, mlab.detrend_linear), (np.arange, 'linear')])\n def test_psd_detrend(self, make_data, detrend):\n if self.NFFT_density is None:\n return\n ydata = make_data(self.NFFT_density)\n ydata1 = ydata+5\n ydata2 = ydata+3.3\n ydata = np.vstack([ydata1, ydata2])\n ydata = np.tile(ydata, (20, 1))\n ydatab = ydata.T.flatten()\n ydata = ydata.flatten()\n ycontrol = np.zeros_like(ydata)\n spec_g, fsp_g = mlab.psd(x=ydata,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=0,\n sides=self.sides,\n detrend=detrend)\n spec_b, fsp_b = mlab.psd(x=ydatab,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=0,\n sides=self.sides,\n detrend=detrend)\n spec_c, fsp_c = mlab.psd(x=ycontrol,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=0,\n sides=self.sides)\n assert_array_equal(fsp_g, fsp_c)\n assert_array_equal(fsp_b, fsp_c)\n assert_allclose(spec_g, spec_c, atol=1e-08)\n # these should not be almost equal\n with pytest.raises(AssertionError):\n assert_allclose(spec_b, spec_c, atol=1e-08)\n\n def test_psd_window_hanning(self):\n if self.NFFT_density is None:\n return\n ydata = np.arange(self.NFFT_density)\n ydata1 = ydata+5\n ydata2 = ydata+3.3\n windowVals = mlab.window_hanning(np.ones_like(ydata1))\n ycontrol1 = ydata1 * windowVals\n ycontrol2 = mlab.window_hanning(ydata2)\n ydata = np.vstack([ydata1, ydata2])\n ycontrol = np.vstack([ycontrol1, ycontrol2])\n ydata = np.tile(ydata, (20, 1))\n ycontrol = np.tile(ycontrol, (20, 1))\n ydatab = ydata.T.flatten()\n ydataf = ydata.flatten()\n ycontrol = ycontrol.flatten()\n spec_g, fsp_g = mlab.psd(x=ydataf,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=0,\n sides=self.sides,\n window=mlab.window_hanning)\n spec_b, fsp_b = mlab.psd(x=ydatab,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=0,\n sides=self.sides,\n window=mlab.window_hanning)\n spec_c, fsp_c = mlab.psd(x=ycontrol,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=0,\n sides=self.sides,\n window=mlab.window_none)\n spec_c *= len(ycontrol1)/(windowVals**2).sum()\n assert_array_equal(fsp_g, fsp_c)\n assert_array_equal(fsp_b, fsp_c)\n assert_allclose(spec_g, spec_c, atol=1e-08)\n # these should not be almost equal\n with pytest.raises(AssertionError):\n assert_allclose(spec_b, spec_c, atol=1e-08)\n\n def test_psd_window_hanning_detrend_linear(self):\n if self.NFFT_density is None:\n return\n ydata = np.arange(self.NFFT_density)\n ycontrol = np.zeros(self.NFFT_density)\n ydata1 = ydata+5\n ydata2 = ydata+3.3\n ycontrol1 = ycontrol\n ycontrol2 = ycontrol\n windowVals = mlab.window_hanning(np.ones_like(ycontrol1))\n ycontrol1 = ycontrol1 * windowVals\n ycontrol2 = mlab.window_hanning(ycontrol2)\n ydata = np.vstack([ydata1, ydata2])\n ycontrol = np.vstack([ycontrol1, ycontrol2])\n ydata = np.tile(ydata, (20, 1))\n ycontrol = np.tile(ycontrol, (20, 1))\n ydatab = ydata.T.flatten()\n ydataf = ydata.flatten()\n ycontrol = ycontrol.flatten()\n spec_g, fsp_g = mlab.psd(x=ydataf,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=0,\n sides=self.sides,\n detrend=mlab.detrend_linear,\n window=mlab.window_hanning)\n spec_b, fsp_b = mlab.psd(x=ydatab,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=0,\n sides=self.sides,\n detrend=mlab.detrend_linear,\n window=mlab.window_hanning)\n spec_c, fsp_c = mlab.psd(x=ycontrol,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=0,\n sides=self.sides,\n window=mlab.window_none)\n spec_c *= len(ycontrol1)/(windowVals**2).sum()\n assert_array_equal(fsp_g, fsp_c)\n assert_array_equal(fsp_b, fsp_c)\n assert_allclose(spec_g, spec_c, atol=1e-08)\n # these should not be almost equal\n with pytest.raises(AssertionError):\n assert_allclose(spec_b, spec_c, atol=1e-08)\n\n def test_psd_window_flattop(self):\n # flattop window\n # adaption from https://github.com/scipy/scipy/blob\\n # /v1.10.0/scipy/signal/windows/_windows.py#L562-L622\n a = [0.21557895, 0.41663158, 0.277263158, 0.083578947, 0.006947368]\n fac = np.linspace(-np.pi, np.pi, self.NFFT_density_real)\n win = np.zeros(self.NFFT_density_real)\n for k in range(len(a)):\n win += a[k] * np.cos(k * fac)\n\n spec, fsp = mlab.psd(x=self.y,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=0,\n sides=self.sides,\n window=win,\n scale_by_freq=False)\n spec_a, fsp_a = mlab.psd(x=self.y,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=0,\n sides=self.sides,\n window=win)\n assert_allclose(spec*win.sum()**2,\n spec_a*self.Fs*(win**2).sum(),\n atol=1e-08)\n\n def test_psd_windowarray(self):\n freqs = self.freqs_density\n spec, fsp = mlab.psd(x=self.y,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=self.nover_density,\n pad_to=self.pad_to_density,\n sides=self.sides,\n window=np.ones(self.NFFT_density_real))\n assert_allclose(fsp, freqs, atol=1e-06)\n assert spec.shape == freqs.shape\n\n def test_psd_windowarray_scale_by_freq(self):\n win = mlab.window_hanning(np.ones(self.NFFT_density_real))\n\n spec, fsp = mlab.psd(x=self.y,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=self.nover_density,\n pad_to=self.pad_to_density,\n sides=self.sides,\n window=mlab.window_hanning)\n spec_s, fsp_s = mlab.psd(x=self.y,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=self.nover_density,\n pad_to=self.pad_to_density,\n sides=self.sides,\n window=mlab.window_hanning,\n scale_by_freq=True)\n spec_n, fsp_n = mlab.psd(x=self.y,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=self.nover_density,\n pad_to=self.pad_to_density,\n sides=self.sides,\n window=mlab.window_hanning,\n scale_by_freq=False)\n assert_array_equal(fsp, fsp_s)\n assert_array_equal(fsp, fsp_n)\n assert_array_equal(spec, spec_s)\n assert_allclose(spec_s*(win**2).sum(),\n spec_n/self.Fs*win.sum()**2,\n atol=1e-08)\n\n @pytest.mark.parametrize(\n "kind", ["complex", "magnitude", "angle", "phase"])\n def test_spectrum(self, kind):\n freqs = self.freqs_spectrum\n spec, fsp = getattr(mlab, f"{kind}_spectrum")(\n x=self.y,\n Fs=self.Fs, sides=self.sides, pad_to=self.pad_to_spectrum)\n assert_allclose(fsp, freqs, atol=1e-06)\n assert spec.shape == freqs.shape\n if kind == "magnitude":\n self.check_maxfreq(spec, fsp, self.fstims)\n self.check_freqs(spec, freqs, fsp, self.fstims)\n\n @pytest.mark.parametrize(\n 'kwargs',\n [{}, {'mode': 'default'}, {'mode': 'psd'}, {'mode': 'magnitude'},\n {'mode': 'complex'}, {'mode': 'angle'}, {'mode': 'phase'}])\n def test_specgram(self, kwargs):\n freqs = self.freqs_specgram\n spec, fsp, t = mlab.specgram(x=self.y,\n NFFT=self.NFFT_specgram,\n Fs=self.Fs,\n noverlap=self.nover_specgram,\n pad_to=self.pad_to_specgram,\n sides=self.sides,\n **kwargs)\n if kwargs.get('mode') == 'complex':\n spec = np.abs(spec)\n specm = np.mean(spec, axis=1)\n\n assert_allclose(fsp, freqs, atol=1e-06)\n assert_allclose(t, self.t_specgram, atol=1e-06)\n\n assert spec.shape[0] == freqs.shape[0]\n assert spec.shape[1] == self.t_specgram.shape[0]\n\n if kwargs.get('mode') not in ['complex', 'angle', 'phase']:\n # using a single freq, so all time slices should be about the same\n if np.abs(spec.max()) != 0:\n assert_allclose(\n np.diff(spec, axis=1).max() / np.abs(spec.max()), 0,\n atol=1e-02)\n if kwargs.get('mode') not in ['angle', 'phase']:\n self.check_freqs(specm, freqs, fsp, self.fstims)\n\n def test_specgram_warn_only1seg(self):\n """Warning should be raised if len(x) <= NFFT."""\n with pytest.warns(UserWarning, match="Only one segment is calculated"):\n mlab.specgram(x=self.y, NFFT=len(self.y), Fs=self.Fs)\n\n def test_psd_csd_equal(self):\n Pxx, freqsxx = mlab.psd(x=self.y,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=self.nover_density,\n pad_to=self.pad_to_density,\n sides=self.sides)\n Pxy, freqsxy = mlab.csd(x=self.y, y=self.y,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=self.nover_density,\n pad_to=self.pad_to_density,\n sides=self.sides)\n assert_array_almost_equal_nulp(Pxx, Pxy)\n assert_array_equal(freqsxx, freqsxy)\n\n @pytest.mark.parametrize("mode", ["default", "psd"])\n def test_specgram_auto_default_psd_equal(self, mode):\n """\n Test that mlab.specgram without mode and with mode 'default' and 'psd'\n are all the same.\n """\n speca, freqspeca, ta = mlab.specgram(x=self.y,\n NFFT=self.NFFT_specgram,\n Fs=self.Fs,\n noverlap=self.nover_specgram,\n pad_to=self.pad_to_specgram,\n sides=self.sides)\n specb, freqspecb, tb = mlab.specgram(x=self.y,\n NFFT=self.NFFT_specgram,\n Fs=self.Fs,\n noverlap=self.nover_specgram,\n pad_to=self.pad_to_specgram,\n sides=self.sides,\n mode=mode)\n assert_array_equal(speca, specb)\n assert_array_equal(freqspeca, freqspecb)\n assert_array_equal(ta, tb)\n\n @pytest.mark.parametrize(\n "mode, conv", [\n ("magnitude", np.abs),\n ("angle", np.angle),\n ("phase", lambda x: np.unwrap(np.angle(x), axis=0))\n ])\n def test_specgram_complex_equivalent(self, mode, conv):\n specc, freqspecc, tc = mlab.specgram(x=self.y,\n NFFT=self.NFFT_specgram,\n Fs=self.Fs,\n noverlap=self.nover_specgram,\n pad_to=self.pad_to_specgram,\n sides=self.sides,\n mode='complex')\n specm, freqspecm, tm = mlab.specgram(x=self.y,\n NFFT=self.NFFT_specgram,\n Fs=self.Fs,\n noverlap=self.nover_specgram,\n pad_to=self.pad_to_specgram,\n sides=self.sides,\n mode=mode)\n\n assert_array_equal(freqspecc, freqspecm)\n assert_array_equal(tc, tm)\n assert_allclose(conv(specc), specm, atol=1e-06)\n\n def test_psd_windowarray_equal(self):\n win = mlab.window_hanning(np.ones(self.NFFT_density_real))\n speca, fspa = mlab.psd(x=self.y,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=self.nover_density,\n pad_to=self.pad_to_density,\n sides=self.sides,\n window=win)\n specb, fspb = mlab.psd(x=self.y,\n NFFT=self.NFFT_density,\n Fs=self.Fs,\n noverlap=self.nover_density,\n pad_to=self.pad_to_density,\n sides=self.sides)\n assert_array_equal(fspa, fspb)\n assert_allclose(speca, specb, atol=1e-08)\n\n\n# extra test for cohere...\ndef test_cohere():\n N = 1024\n np.random.seed(19680801)\n x = np.random.randn(N)\n # phase offset\n y = np.roll(x, 20)\n # high-freq roll-off\n y = np.convolve(y, np.ones(20) / 20., mode='same')\n cohsq, f = mlab.cohere(x, y, NFFT=256, Fs=2, noverlap=128)\n assert_allclose(np.mean(cohsq), 0.837, atol=1.e-3)\n assert np.isreal(np.mean(cohsq))\n\n\n# *****************************************************************\n# These Tests were taken from SCIPY with some minor modifications\n# this can be retrieved from:\n# https://github.com/scipy/scipy/blob/master/scipy/stats/tests/test_kdeoth.py\n# *****************************************************************\n\nclass TestGaussianKDE:\n\n def test_kde_integer_input(self):\n """Regression test for #1181."""\n x1 = np.arange(5)\n kde = mlab.GaussianKDE(x1)\n y_expected = [0.13480721, 0.18222869, 0.19514935, 0.18222869,\n 0.13480721]\n np.testing.assert_array_almost_equal(kde(x1), y_expected, decimal=6)\n\n def test_gaussian_kde_covariance_caching(self):\n x1 = np.array([-7, -5, 1, 4, 5], dtype=float)\n xs = np.linspace(-10, 10, num=5)\n # These expected values are from scipy 0.10, before some changes to\n # gaussian_kde. They were not compared with any external reference.\n y_expected = [0.02463386, 0.04689208, 0.05395444, 0.05337754,\n 0.01664475]\n\n # set it to the default bandwidth.\n kde2 = mlab.GaussianKDE(x1, 'scott')\n y2 = kde2(xs)\n\n np.testing.assert_array_almost_equal(y_expected, y2, decimal=7)\n\n def test_kde_bandwidth_method(self):\n\n np.random.seed(8765678)\n n_basesample = 50\n xn = np.random.randn(n_basesample)\n\n # Default\n gkde = mlab.GaussianKDE(xn)\n # Supply a callable\n gkde2 = mlab.GaussianKDE(xn, 'scott')\n # Supply a scalar\n gkde3 = mlab.GaussianKDE(xn, bw_method=gkde.factor)\n\n xs = np.linspace(-7, 7, 51)\n kdepdf = gkde.evaluate(xs)\n kdepdf2 = gkde2.evaluate(xs)\n assert kdepdf.all() == kdepdf2.all()\n kdepdf3 = gkde3.evaluate(xs)\n assert kdepdf.all() == kdepdf3.all()\n\n\nclass TestGaussianKDECustom:\n def test_no_data(self):\n """Pass no data into the GaussianKDE class."""\n with pytest.raises(ValueError):\n mlab.GaussianKDE([])\n\n def test_single_dataset_element(self):\n """Pass a single dataset element into the GaussianKDE class."""\n with pytest.raises(ValueError):\n mlab.GaussianKDE([42])\n\n def test_silverman_multidim_dataset(self):\n """Test silverman's for a multi-dimensional array."""\n x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n with pytest.raises(np.linalg.LinAlgError):\n mlab.GaussianKDE(x1, "silverman")\n\n def test_silverman_singledim_dataset(self):\n """Test silverman's output for a single dimension list."""\n x1 = np.array([-7, -5, 1, 4, 5])\n mygauss = mlab.GaussianKDE(x1, "silverman")\n y_expected = 0.76770389927475502\n assert_almost_equal(mygauss.covariance_factor(), y_expected, 7)\n\n def test_scott_multidim_dataset(self):\n """Test scott's output for a multi-dimensional array."""\n x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n with pytest.raises(np.linalg.LinAlgError):\n mlab.GaussianKDE(x1, "scott")\n\n def test_scott_singledim_dataset(self):\n """Test scott's output a single-dimensional array."""\n x1 = np.array([-7, -5, 1, 4, 5])\n mygauss = mlab.GaussianKDE(x1, "scott")\n y_expected = 0.72477966367769553\n assert_almost_equal(mygauss.covariance_factor(), y_expected, 7)\n\n def test_scalar_empty_dataset(self):\n """Test the scalar's cov factor for an empty array."""\n with pytest.raises(ValueError):\n mlab.GaussianKDE([], bw_method=5)\n\n def test_scalar_covariance_dataset(self):\n """Test a scalar's cov factor."""\n np.random.seed(8765678)\n n_basesample = 50\n multidim_data = [np.random.randn(n_basesample) for i in range(5)]\n\n kde = mlab.GaussianKDE(multidim_data, bw_method=0.5)\n assert kde.covariance_factor() == 0.5\n\n def test_callable_covariance_dataset(self):\n """Test the callable's cov factor for a multi-dimensional array."""\n np.random.seed(8765678)\n n_basesample = 50\n multidim_data = [np.random.randn(n_basesample) for i in range(5)]\n\n def callable_fun(x):\n return 0.55\n kde = mlab.GaussianKDE(multidim_data, bw_method=callable_fun)\n assert kde.covariance_factor() == 0.55\n\n def test_callable_singledim_dataset(self):\n """Test the callable's cov factor for a single-dimensional array."""\n np.random.seed(8765678)\n n_basesample = 50\n multidim_data = np.random.randn(n_basesample)\n\n kde = mlab.GaussianKDE(multidim_data, bw_method='silverman')\n y_expected = 0.48438841363348911\n assert_almost_equal(kde.covariance_factor(), y_expected, 7)\n\n def test_wrong_bw_method(self):\n """Test the error message that should be called when bw is invalid."""\n np.random.seed(8765678)\n n_basesample = 50\n data = np.random.randn(n_basesample)\n with pytest.raises(ValueError):\n mlab.GaussianKDE(data, bw_method="invalid")\n\n\nclass TestGaussianKDEEvaluate:\n\n def test_evaluate_diff_dim(self):\n """\n Test the evaluate method when the dim's of dataset and points have\n different dimensions.\n """\n x1 = np.arange(3, 10, 2)\n kde = mlab.GaussianKDE(x1)\n x2 = np.arange(3, 12, 2)\n y_expected = [\n 0.08797252, 0.11774109, 0.11774109, 0.08797252, 0.0370153\n ]\n y = kde.evaluate(x2)\n np.testing.assert_array_almost_equal(y, y_expected, 7)\n\n def test_evaluate_inv_dim(self):\n """\n Invert the dimensions; i.e., for a dataset of dimension 1 [3, 2, 4],\n the points should have a dimension of 3 [[3], [2], [4]].\n """\n np.random.seed(8765678)\n n_basesample = 50\n multidim_data = np.random.randn(n_basesample)\n kde = mlab.GaussianKDE(multidim_data)\n x2 = [[1], [2], [3]]\n with pytest.raises(ValueError):\n kde.evaluate(x2)\n\n def test_evaluate_dim_and_num(self):\n """Tests if evaluated against a one by one array"""\n x1 = np.arange(3, 10, 2)\n x2 = np.array([3])\n kde = mlab.GaussianKDE(x1)\n y_expected = [0.08797252]\n y = kde.evaluate(x2)\n np.testing.assert_array_almost_equal(y, y_expected, 7)\n\n def test_evaluate_point_dim_not_one(self):\n x1 = np.arange(3, 10, 2)\n x2 = [np.arange(3, 10, 2), np.arange(3, 10, 2)]\n kde = mlab.GaussianKDE(x1)\n with pytest.raises(ValueError):\n kde.evaluate(x2)\n\n def test_evaluate_equal_dim_and_num_lt(self):\n x1 = np.arange(3, 10, 2)\n x2 = np.arange(3, 8, 2)\n kde = mlab.GaussianKDE(x1)\n y_expected = [0.08797252, 0.11774109, 0.11774109]\n y = kde.evaluate(x2)\n np.testing.assert_array_almost_equal(y, y_expected, 7)\n\n\ndef test_psd_onesided_norm():\n u = np.array([0, 1, 2, 3, 1, 2, 1])\n dt = 1.0\n Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size)\n P, f = mlab.psd(u, NFFT=u.size, Fs=1/dt, window=mlab.window_none,\n detrend=mlab.detrend_none, noverlap=0, pad_to=None,\n scale_by_freq=None,\n sides='onesided')\n Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1])\n assert_allclose(P, Su_1side, atol=1e-06)\n\n\ndef test_psd_oversampling():\n """Test the case len(x) < NFFT for psd()."""\n u = np.array([0, 1, 2, 3, 1, 2, 1])\n dt = 1.0\n Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size)\n P, f = mlab.psd(u, NFFT=u.size*2, Fs=1/dt, window=mlab.window_none,\n detrend=mlab.detrend_none, noverlap=0, pad_to=None,\n scale_by_freq=None,\n sides='onesided')\n Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1])\n assert_almost_equal(np.sum(P), np.sum(Su_1side)) # same energy\n | .venv\Lib\site-packages\matplotlib\tests\test_mlab.py | test_mlab.py | Python | 42,269 | 0.95 | 0.127202 | 0.046307 | react-lib | 832 | 2025-05-16T04:28:32.738833 | BSD-3-Clause | true | 294d0752d703f5d91d3ab0b3bdd9d096 |
import numpy as np\nfrom numpy.testing import assert_array_equal, assert_allclose\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing.decorators import (image_comparison,\n remove_ticks_and_titles)\nimport matplotlib as mpl\nimport pytest\nfrom pathlib import Path\nfrom io import BytesIO\nfrom PIL import Image\nimport base64\n\n\n@image_comparison(["bivariate_cmap_shapes.png"])\ndef test_bivariate_cmap_shapes():\n x_0 = np.repeat(np.linspace(-0.1, 1.1, 10, dtype='float32')[None, :], 10, axis=0)\n x_1 = x_0.T\n\n fig, axes = plt.subplots(1, 4, figsize=(10, 2))\n\n # shape = 'square'\n cmap = mpl.bivar_colormaps['BiPeak']\n axes[0].imshow(cmap((x_0, x_1)), interpolation='nearest')\n\n # shape = 'circle'\n cmap = mpl.bivar_colormaps['BiCone']\n axes[1].imshow(cmap((x_0, x_1)), interpolation='nearest')\n\n # shape = 'ignore'\n cmap = mpl.bivar_colormaps['BiPeak']\n cmap = cmap.with_extremes(shape='ignore')\n axes[2].imshow(cmap((x_0, x_1)), interpolation='nearest')\n\n # shape = circleignore\n cmap = mpl.bivar_colormaps['BiCone']\n cmap = cmap.with_extremes(shape='circleignore')\n axes[3].imshow(cmap((x_0, x_1)), interpolation='nearest')\n remove_ticks_and_titles(fig)\n\n\ndef test_multivar_creation():\n # test creation of a custom multivariate colorbar\n blues = mpl.colormaps['Blues']\n cmap = mpl.colors.MultivarColormap((blues, 'Oranges'), 'sRGB_sub')\n y, x = np.mgrid[0:3, 0:3]/2\n im = cmap((y, x))\n res = np.array([[[0.96862745, 0.94509804, 0.92156863, 1],\n [0.96004614, 0.53504037, 0.23277201, 1],\n [0.46666667, 0.1372549, 0.01568627, 1]],\n [[0.41708574, 0.64141484, 0.75980008, 1],\n [0.40850442, 0.23135717, 0.07100346, 1],\n [0, 0, 0, 1]],\n [[0.03137255, 0.14901961, 0.34117647, 1],\n [0.02279123, 0, 0, 1],\n [0, 0, 0, 1]]])\n assert_allclose(im, res, atol=0.01)\n\n with pytest.raises(ValueError, match="colormaps must be a list of"):\n cmap = mpl.colors.MultivarColormap((blues, [blues]), 'sRGB_sub')\n with pytest.raises(ValueError, match="A MultivarColormap must"):\n cmap = mpl.colors.MultivarColormap('blues', 'sRGB_sub')\n with pytest.raises(ValueError, match="A MultivarColormap must"):\n cmap = mpl.colors.MultivarColormap((blues), 'sRGB_sub')\n\n\n@image_comparison(["multivar_alpha_mixing.png"])\ndef test_multivar_alpha_mixing():\n # test creation of a custom colormap using 'rainbow'\n # and a colormap that goes from alpha = 1 to alpha = 0\n rainbow = mpl.colormaps['rainbow']\n alpha = np.zeros((256, 4))\n alpha[:, 3] = np.linspace(1, 0, 256)\n alpha_cmap = mpl.colors.LinearSegmentedColormap.from_list('from_list', alpha)\n\n cmap = mpl.colors.MultivarColormap((rainbow, alpha_cmap), 'sRGB_add')\n y, x = np.mgrid[0:10, 0:10]/9\n im = cmap((y, x))\n\n fig, ax = plt.subplots()\n ax.imshow(im, interpolation='nearest')\n remove_ticks_and_titles(fig)\n\n\ndef test_multivar_cmap_call():\n cmap = mpl.multivar_colormaps['2VarAddA']\n assert_array_equal(cmap((0.0, 0.0)), (0, 0, 0, 1))\n assert_array_equal(cmap((1.0, 1.0)), (1, 1, 1, 1))\n assert_allclose(cmap((0.0, 0.0), alpha=0.1), (0, 0, 0, 0.1), atol=0.1)\n\n cmap = mpl.multivar_colormaps['2VarSubA']\n assert_array_equal(cmap((0.0, 0.0)), (1, 1, 1, 1))\n assert_allclose(cmap((1.0, 1.0)), (0, 0, 0, 1), atol=0.1)\n\n # check outside and bad\n cs = cmap([(0., 0., 0., 1.2, np.nan), (0., 1.2, np.nan, 0., 0., )])\n assert_allclose(cs, [[1., 1., 1., 1.],\n [0.801, 0.426, 0.119, 1.],\n [0., 0., 0., 0.],\n [0.199, 0.574, 0.881, 1.],\n [0., 0., 0., 0.]])\n\n assert_array_equal(cmap((0.0, 0.0), bytes=True), (255, 255, 255, 255))\n\n with pytest.raises(ValueError, match="alpha is array-like but its shape"):\n cs = cmap([(0, 5, 9), (0, 0, 0)], alpha=(0.5, 0.3))\n\n with pytest.raises(ValueError, match="For the selected colormap the data"):\n cs = cmap([(0, 5, 9), (0, 0, 0), (0, 0, 0)])\n\n with pytest.raises(ValueError, match="clip cannot be false"):\n cs = cmap([(0, 5, 9), (0, 0, 0)], bytes=True, clip=False)\n # Tests calling a multivariate colormap with integer values\n cmap = mpl.multivar_colormaps['2VarSubA']\n\n # call only integers\n cs = cmap([(0, 50, 100, 0, 0, 300), (0, 0, 0, 50, 100, 300)])\n res = np.array([[1, 1, 1, 1],\n [0.85176471, 0.91029412, 0.96023529, 1],\n [0.70452941, 0.82764706, 0.93358824, 1],\n [0.94358824, 0.88505882, 0.83511765, 1],\n [0.89729412, 0.77417647, 0.66823529, 1],\n [0, 0, 0, 1]])\n assert_allclose(cs, res, atol=0.01)\n\n # call only integers, wrong byte order\n swapped_dt = np.dtype(int).newbyteorder()\n cs = cmap([np.array([0, 50, 100, 0, 0, 300], dtype=swapped_dt),\n np.array([0, 0, 0, 50, 100, 300], dtype=swapped_dt)])\n assert_allclose(cs, res, atol=0.01)\n\n # call mix floats integers\n # check calling with bytes = True\n cs = cmap([(0, 50, 100, 0, 0, 300), (0, 0, 0, 50, 100, 300)], bytes=True)\n res = np.array([[255, 255, 255, 255],\n [217, 232, 244, 255],\n [179, 211, 238, 255],\n [240, 225, 212, 255],\n [228, 197, 170, 255],\n [0, 0, 0, 255]])\n assert_allclose(cs, res, atol=0.01)\n\n cs = cmap([(0, 50, 100, 0, 0, 300), (0, 0, 0, 50, 100, 300)], alpha=0.5)\n res = np.array([[1, 1, 1, 0.5],\n [0.85176471, 0.91029412, 0.96023529, 0.5],\n [0.70452941, 0.82764706, 0.93358824, 0.5],\n [0.94358824, 0.88505882, 0.83511765, 0.5],\n [0.89729412, 0.77417647, 0.66823529, 0.5],\n [0, 0, 0, 0.5]])\n assert_allclose(cs, res, atol=0.01)\n # call with tuple\n assert_allclose(cmap((100, 120), bytes=True, alpha=0.5),\n [149, 142, 136, 127], atol=0.01)\n\n # alpha and bytes\n cs = cmap([(0, 5, 9, 0, 0, 10), (0, 0, 0, 5, 11, 12)], bytes=True, alpha=0.5)\n res = np.array([[0, 0, 255, 127],\n [141, 0, 255, 127],\n [255, 0, 255, 127],\n [0, 115, 255, 127],\n [0, 255, 255, 127],\n [255, 255, 255, 127]])\n\n # bad alpha shape\n with pytest.raises(ValueError, match="alpha is array-like but its shape"):\n cs = cmap([(0, 5, 9), (0, 0, 0)], bytes=True, alpha=(0.5, 0.3))\n\n cmap = cmap.with_extremes(bad=(1, 1, 1, 1))\n cs = cmap([(0., 1.1, np.nan), (0., 1.2, 1.)])\n res = np.array([[1., 1., 1., 1.],\n [0., 0., 0., 1.],\n [1., 1., 1., 1.]])\n assert_allclose(cs, res, atol=0.01)\n\n # call outside with tuple\n assert_allclose(cmap((300, 300), bytes=True, alpha=0.5),\n [0, 0, 0, 127], atol=0.01)\n with pytest.raises(ValueError,\n match="For the selected colormap the data must have"):\n cs = cmap((0, 5, 9))\n\n # test over/under\n cmap = mpl.multivar_colormaps['2VarAddA']\n with pytest.raises(ValueError, match='i.e. be of length 2'):\n cmap.with_extremes(over=0)\n with pytest.raises(ValueError, match='i.e. be of length 2'):\n cmap.with_extremes(under=0)\n\n cmap = cmap.with_extremes(under=[(0, 0, 0, 0)]*2)\n assert_allclose((0, 0, 0, 0), cmap((-1., 0)), atol=1e-2)\n cmap = cmap.with_extremes(over=[(0, 0, 0, 0)]*2)\n assert_allclose((0, 0, 0, 0), cmap((2., 0)), atol=1e-2)\n\n\ndef test_multivar_bad_mode():\n cmap = mpl.multivar_colormaps['2VarSubA']\n with pytest.raises(ValueError, match="is not a valid value for"):\n cmap = mpl.colors.MultivarColormap(cmap[:], 'bad')\n\n\ndef test_multivar_resample():\n cmap = mpl.multivar_colormaps['3VarAddA']\n cmap_resampled = cmap.resampled((None, 10, 3))\n\n assert_allclose(cmap_resampled[1](0.25), (0.093, 0.116, 0.059, 1.0))\n assert_allclose(cmap_resampled((0, 0.25, 0)), (0.093, 0.116, 0.059, 1.0))\n assert_allclose(cmap_resampled((1, 0.25, 1)), (0.417271, 0.264624, 0.274976, 1.),\n atol=0.01)\n\n with pytest.raises(ValueError, match="lutshape must be of length"):\n cmap = cmap.resampled(4)\n\n\ndef test_bivar_cmap_call_tuple():\n cmap = mpl.bivar_colormaps['BiOrangeBlue']\n assert_allclose(cmap((1.0, 1.0)), (1, 1, 1, 1), atol=0.01)\n assert_allclose(cmap((0.0, 0.0)), (0, 0, 0, 1), atol=0.1)\n assert_allclose(cmap((0.0, 0.0), alpha=0.1), (0, 0, 0, 0.1), atol=0.1)\n\n\ndef test_bivar_cmap_call():\n """\n Tests calling a bivariate colormap with integer values\n """\n im = np.ones((10, 12, 4))\n im[:, :, 0] = np.linspace(0, 1, 10)[:, np.newaxis]\n im[:, :, 1] = np.linspace(0, 1, 12)[np.newaxis, :]\n cmap = mpl.colors.BivarColormapFromImage(im)\n\n # call only integers\n cs = cmap([(0, 5, 9, 0, 0, 10), (0, 0, 0, 5, 11, 12)])\n res = np.array([[0, 0, 1, 1],\n [0.556, 0, 1, 1],\n [1, 0, 1, 1],\n [0, 0.454, 1, 1],\n [0, 1, 1, 1],\n [1, 1, 1, 1]])\n assert_allclose(cs, res, atol=0.01)\n # call only integers, wrong byte order\n swapped_dt = np.dtype(int).newbyteorder()\n cs = cmap([np.array([0, 5, 9, 0, 0, 10], dtype=swapped_dt),\n np.array([0, 0, 0, 5, 11, 12], dtype=swapped_dt)])\n assert_allclose(cs, res, atol=0.01)\n\n # call mix floats integers\n cmap = cmap.with_extremes(outside=(1, 0, 0, 0))\n cs = cmap([(0.5, 0), (0, 3)])\n res = np.array([[0.555, 0, 1, 1],\n [0, 0.2727, 1, 1]])\n assert_allclose(cs, res, atol=0.01)\n\n # check calling with bytes = True\n cs = cmap([(0, 5, 9, 0, 0, 10), (0, 0, 0, 5, 11, 12)], bytes=True)\n res = np.array([[0, 0, 255, 255],\n [141, 0, 255, 255],\n [255, 0, 255, 255],\n [0, 115, 255, 255],\n [0, 255, 255, 255],\n [255, 255, 255, 255]])\n assert_allclose(cs, res, atol=0.01)\n\n # test alpha\n cs = cmap([(0, 5, 9, 0, 0, 10), (0, 0, 0, 5, 11, 12)], alpha=0.5)\n res = np.array([[0, 0, 1, 0.5],\n [0.556, 0, 1, 0.5],\n [1, 0, 1, 0.5],\n [0, 0.454, 1, 0.5],\n [0, 1, 1, 0.5],\n [1, 1, 1, 0.5]])\n assert_allclose(cs, res, atol=0.01)\n # call with tuple\n assert_allclose(cmap((10, 12), bytes=True, alpha=0.5),\n [255, 255, 255, 127], atol=0.01)\n\n # alpha and bytes\n cs = cmap([(0, 5, 9, 0, 0, 10), (0, 0, 0, 5, 11, 12)], bytes=True, alpha=0.5)\n res = np.array([[0, 0, 255, 127],\n [141, 0, 255, 127],\n [255, 0, 255, 127],\n [0, 115, 255, 127],\n [0, 255, 255, 127],\n [255, 255, 255, 127]])\n\n # bad alpha shape\n with pytest.raises(ValueError, match="alpha is array-like but its shape"):\n cs = cmap([(0, 5, 9), (0, 0, 0)], bytes=True, alpha=(0.5, 0.3))\n\n # set shape to 'ignore'.\n # final point is outside colormap and should then receive\n # the 'outside' (in this case [1,0,0,0])\n # also test 'bad' (in this case [1,1,1,0])\n cmap = cmap.with_extremes(outside=(1, 0, 0, 0), bad=(1, 1, 1, 0), shape='ignore')\n cs = cmap([(0., 1.1, np.nan), (0., 1.2, 1.)])\n res = np.array([[0, 0, 1, 1],\n [1, 0, 0, 0],\n [1, 1, 1, 0]])\n assert_allclose(cs, res, atol=0.01)\n # call outside with tuple\n assert_allclose(cmap((10, 12), bytes=True, alpha=0.5),\n [255, 0, 0, 127], atol=0.01)\n # with integers\n cs = cmap([(0, 10), (0, 12)])\n res = np.array([[0, 0, 1, 1],\n [1, 0, 0, 0]])\n assert_allclose(cs, res, atol=0.01)\n\n with pytest.raises(ValueError,\n match="For a `BivarColormap` the data must have"):\n cs = cmap((0, 5, 9))\n\n cmap = cmap.with_extremes(shape='circle')\n with pytest.raises(NotImplementedError,\n match="only implemented for use with with floats"):\n cs = cmap([(0, 5, 9, 0, 0, 9), (0, 0, 0, 5, 11, 11)])\n\n # test origin\n cmap = mpl.bivar_colormaps['BiOrangeBlue'].with_extremes(origin=(0.5, 0.5))\n assert_allclose(cmap[0](0.5),\n (0.50244140625, 0.5024222412109375, 0.50244140625, 1))\n assert_allclose(cmap[1](0.5),\n (0.50244140625, 0.5024222412109375, 0.50244140625, 1))\n cmap = mpl.bivar_colormaps['BiOrangeBlue'].with_extremes(origin=(1, 1))\n assert_allclose(cmap[0](1.),\n (0.99853515625, 0.9985467529296875, 0.99853515625, 1.0))\n assert_allclose(cmap[1](1.),\n (0.99853515625, 0.9985467529296875, 0.99853515625, 1.0))\n with pytest.raises(KeyError,\n match="only 0 or 1 are valid keys"):\n cs = cmap[2]\n\n\ndef test_bivar_getitem():\n """Test __getitem__ on BivarColormap"""\n xA = ([.0, .25, .5, .75, 1., -1, 2], [.5]*7)\n xB = ([.5]*7, [.0, .25, .5, .75, 1., -1, 2])\n\n cmaps = mpl.bivar_colormaps['BiPeak']\n assert_array_equal(cmaps(xA), cmaps[0](xA[0]))\n assert_array_equal(cmaps(xB), cmaps[1](xB[1]))\n\n cmaps = cmaps.with_extremes(shape='ignore')\n assert_array_equal(cmaps(xA), cmaps[0](xA[0]))\n assert_array_equal(cmaps(xB), cmaps[1](xB[1]))\n\n xA = ([.0, .25, .5, .75, 1., -1, 2], [.0]*7)\n xB = ([.0]*7, [.0, .25, .5, .75, 1., -1, 2])\n cmaps = mpl.bivar_colormaps['BiOrangeBlue']\n assert_array_equal(cmaps(xA), cmaps[0](xA[0]))\n assert_array_equal(cmaps(xB), cmaps[1](xB[1]))\n\n cmaps = cmaps.with_extremes(shape='ignore')\n assert_array_equal(cmaps(xA), cmaps[0](xA[0]))\n assert_array_equal(cmaps(xB), cmaps[1](xB[1]))\n\n\ndef test_bivar_cmap_bad_shape():\n """\n Tests calling a bivariate colormap with integer values\n """\n cmap = mpl.bivar_colormaps['BiCone']\n _ = cmap.lut\n with pytest.raises(ValueError,\n match="is not a valid value for shape"):\n cmap.with_extremes(shape='bad_shape')\n\n with pytest.raises(ValueError,\n match="is not a valid value for shape"):\n mpl.colors.BivarColormapFromImage(np.ones((3, 3, 4)),\n shape='bad_shape')\n\n\ndef test_bivar_cmap_bad_lut():\n """\n Tests calling a bivariate colormap with integer values\n """\n with pytest.raises(ValueError,\n match="The lut must be an array of shape"):\n cmap = mpl.colors.BivarColormapFromImage(np.ones((3, 3, 5)))\n\n\ndef test_bivar_cmap_from_image():\n """\n This tests the creation and use of a bivariate colormap\n generated from an image\n """\n\n data_0 = np.arange(6).reshape((2, 3))/5\n data_1 = np.arange(6).reshape((3, 2)).T/5\n\n # bivariate colormap from array\n cim = np.ones((10, 12, 3))\n cim[:, :, 0] = np.arange(10)[:, np.newaxis]/10\n cim[:, :, 1] = np.arange(12)[np.newaxis, :]/12\n\n cmap = mpl.colors.BivarColormapFromImage(cim)\n im = cmap((data_0, data_1))\n res = np.array([[[0, 0, 1, 1],\n [0.2, 0.33333333, 1, 1],\n [0.4, 0.75, 1, 1]],\n [[0.6, 0.16666667, 1, 1],\n [0.8, 0.58333333, 1, 1],\n [0.9, 0.91666667, 1, 1]]])\n assert_allclose(im, res, atol=0.01)\n\n # input as unit8\n cim = np.ones((10, 12, 3))*255\n cim[:, :, 0] = np.arange(10)[:, np.newaxis]/10*255\n cim[:, :, 1] = np.arange(12)[np.newaxis, :]/12*255\n\n cmap = mpl.colors.BivarColormapFromImage(cim.astype(np.uint8))\n im = cmap((data_0, data_1))\n res = np.array([[[0, 0, 1, 1],\n [0.2, 0.33333333, 1, 1],\n [0.4, 0.75, 1, 1]],\n [[0.6, 0.16666667, 1, 1],\n [0.8, 0.58333333, 1, 1],\n [0.9, 0.91666667, 1, 1]]])\n assert_allclose(im, res, atol=0.01)\n\n # bivariate colormap from array\n png_path = Path(__file__).parent / "baseline_images/pngsuite/basn2c16.png"\n cim = Image.open(png_path)\n cim = np.asarray(cim.convert('RGBA'))\n\n cmap = mpl.colors.BivarColormapFromImage(cim)\n im = cmap((data_0, data_1), bytes=True)\n res = np.array([[[255, 255, 0, 255],\n [156, 206, 0, 255],\n [49, 156, 49, 255]],\n [[206, 99, 0, 255],\n [99, 49, 107, 255],\n [0, 0, 255, 255]]])\n assert_allclose(im, res, atol=0.01)\n\n\ndef test_bivar_resample():\n cmap = mpl.bivar_colormaps['BiOrangeBlue'].resampled((2, 2))\n assert_allclose(cmap((0.25, 0.25)), (0, 0, 0, 1), atol=1e-2)\n\n cmap = mpl.bivar_colormaps['BiOrangeBlue'].resampled((-2, 2))\n assert_allclose(cmap((0.25, 0.25)), (1., 0.5, 0., 1.), atol=1e-2)\n\n cmap = mpl.bivar_colormaps['BiOrangeBlue'].resampled((2, -2))\n assert_allclose(cmap((0.25, 0.25)), (0., 0.5, 1., 1.), atol=1e-2)\n\n cmap = mpl.bivar_colormaps['BiOrangeBlue'].resampled((-2, -2))\n assert_allclose(cmap((0.25, 0.25)), (1, 1, 1, 1), atol=1e-2)\n\n cmap = mpl.bivar_colormaps['BiOrangeBlue'].reversed()\n assert_allclose(cmap((0.25, 0.25)), (0.748535, 0.748547, 0.748535, 1.), atol=1e-2)\n cmap = mpl.bivar_colormaps['BiOrangeBlue'].transposed()\n assert_allclose(cmap((0.25, 0.25)), (0.252441, 0.252422, 0.252441, 1.), atol=1e-2)\n\n with pytest.raises(ValueError, match="lutshape must be of length"):\n cmap = cmap.resampled(4)\n\n\ndef test_bivariate_repr_png():\n cmap = mpl.bivar_colormaps['BiCone']\n png = cmap._repr_png_()\n assert len(png) > 0\n img = Image.open(BytesIO(png))\n assert img.width > 0\n assert img.height > 0\n assert 'Title' in img.text\n assert 'Description' in img.text\n assert 'Author' in img.text\n assert 'Software' in img.text\n\n\ndef test_bivariate_repr_html():\n cmap = mpl.bivar_colormaps['BiCone']\n html = cmap._repr_html_()\n assert len(html) > 0\n png = cmap._repr_png_()\n assert base64.b64encode(png).decode('ascii') in html\n assert cmap.name in html\n assert html.startswith('<div')\n assert html.endswith('</div>')\n\n\ndef test_multivariate_repr_png():\n cmap = mpl.multivar_colormaps['3VarAddA']\n png = cmap._repr_png_()\n assert len(png) > 0\n img = Image.open(BytesIO(png))\n assert img.width > 0\n assert img.height > 0\n assert 'Title' in img.text\n assert 'Description' in img.text\n assert 'Author' in img.text\n assert 'Software' in img.text\n\n\ndef test_multivariate_repr_html():\n cmap = mpl.multivar_colormaps['3VarAddA']\n html = cmap._repr_html_()\n assert len(html) > 0\n for c in cmap:\n png = c._repr_png_()\n assert base64.b64encode(png).decode('ascii') in html\n assert cmap.name in html\n assert html.startswith('<div')\n assert html.endswith('</div>')\n\n\ndef test_bivar_eq():\n """\n Tests equality between multivariate colormaps\n """\n cmap_0 = mpl.bivar_colormaps['BiPeak']\n\n cmap_1 = mpl.bivar_colormaps['BiPeak']\n assert (cmap_0 == cmap_1) is True\n\n cmap_1 = mpl.multivar_colormaps['2VarAddA']\n assert (cmap_0 == cmap_1) is False\n\n cmap_1 = mpl.bivar_colormaps['BiCone']\n assert (cmap_0 == cmap_1) is False\n\n cmap_1 = mpl.bivar_colormaps['BiPeak']\n cmap_1 = cmap_1.with_extremes(bad='k')\n assert (cmap_0 == cmap_1) is False\n\n cmap_1 = mpl.bivar_colormaps['BiPeak']\n cmap_1 = cmap_1.with_extremes(outside='k')\n assert (cmap_0 == cmap_1) is False\n\n cmap_1 = mpl.bivar_colormaps['BiPeak']\n cmap_1._init()\n cmap_1._lut *= 0.5\n assert (cmap_0 == cmap_1) is False\n\n cmap_1 = mpl.bivar_colormaps['BiPeak']\n cmap_1 = cmap_1.with_extremes(shape='ignore')\n assert (cmap_0 == cmap_1) is False\n\n\ndef test_multivar_eq():\n """\n Tests equality between multivariate colormaps\n """\n cmap_0 = mpl.multivar_colormaps['2VarAddA']\n\n cmap_1 = mpl.multivar_colormaps['2VarAddA']\n assert (cmap_0 == cmap_1) is True\n\n cmap_1 = mpl.bivar_colormaps['BiPeak']\n assert (cmap_0 == cmap_1) is False\n\n cmap_1 = mpl.colors.MultivarColormap([cmap_0[0]]*2,\n 'sRGB_add')\n assert (cmap_0 == cmap_1) is False\n\n cmap_1 = mpl.multivar_colormaps['3VarAddA']\n assert (cmap_0 == cmap_1) is False\n\n cmap_1 = mpl.multivar_colormaps['2VarAddA']\n cmap_1 = cmap_1.with_extremes(bad='k')\n assert (cmap_0 == cmap_1) is False\n\n cmap_1 = mpl.multivar_colormaps['2VarAddA']\n cmap_1 = mpl.colors.MultivarColormap(cmap_1[:], 'sRGB_sub')\n assert (cmap_0 == cmap_1) is False\n | .venv\Lib\site-packages\matplotlib\tests\test_multivariate_colormaps.py | test_multivariate_colormaps.py | Python | 20,785 | 0.95 | 0.042553 | 0.078261 | vue-tools | 828 | 2025-03-19T20:35:11.682649 | BSD-3-Clause | true | 09dce441b0c3dd9f891b4ab5d8168d05 |
from collections import namedtuple\nimport io\n\nimport numpy as np\nfrom numpy.testing import assert_allclose\nimport pytest\n\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport matplotlib.lines as mlines\nfrom matplotlib.backend_bases import MouseButton, MouseEvent\n\nfrom matplotlib.offsetbox import (\n AnchoredOffsetbox, AnnotationBbox, AnchoredText, DrawingArea, HPacker,\n OffsetBox, OffsetImage, PaddedBox, TextArea, VPacker, _get_packed_offsets)\n\n\n@image_comparison(['offsetbox_clipping'], remove_text=True)\ndef test_offsetbox_clipping():\n # - create a plot\n # - put an AnchoredOffsetbox with a child DrawingArea\n # at the center of the axes\n # - give the DrawingArea a gray background\n # - put a black line across the bounds of the DrawingArea\n # - see that the black line is clipped to the edges of\n # the DrawingArea.\n fig, ax = plt.subplots()\n size = 100\n da = DrawingArea(size, size, clip=True)\n assert da.clip_children\n bg = mpatches.Rectangle((0, 0), size, size,\n facecolor='#CCCCCC',\n edgecolor='None',\n linewidth=0)\n line = mlines.Line2D([-size*.5, size*1.5], [size/2, size/2],\n color='black',\n linewidth=10)\n anchored_box = AnchoredOffsetbox(\n loc='center',\n child=da,\n pad=0.,\n frameon=False,\n bbox_to_anchor=(.5, .5),\n bbox_transform=ax.transAxes,\n borderpad=0.)\n\n da.add_artist(bg)\n da.add_artist(line)\n ax.add_artist(anchored_box)\n ax.set_xlim((0, 1))\n ax.set_ylim((0, 1))\n\n\ndef test_offsetbox_clip_children():\n # - create a plot\n # - put an AnchoredOffsetbox with a child DrawingArea\n # at the center of the axes\n # - give the DrawingArea a gray background\n # - put a black line across the bounds of the DrawingArea\n # - see that the black line is clipped to the edges of\n # the DrawingArea.\n fig, ax = plt.subplots()\n size = 100\n da = DrawingArea(size, size, clip=True)\n bg = mpatches.Rectangle((0, 0), size, size,\n facecolor='#CCCCCC',\n edgecolor='None',\n linewidth=0)\n line = mlines.Line2D([-size*.5, size*1.5], [size/2, size/2],\n color='black',\n linewidth=10)\n anchored_box = AnchoredOffsetbox(\n loc='center',\n child=da,\n pad=0.,\n frameon=False,\n bbox_to_anchor=(.5, .5),\n bbox_transform=ax.transAxes,\n borderpad=0.)\n\n da.add_artist(bg)\n da.add_artist(line)\n ax.add_artist(anchored_box)\n\n fig.canvas.draw()\n assert not fig.stale\n da.clip_children = True\n assert fig.stale\n\n\ndef test_offsetbox_loc_codes():\n # Check that valid string location codes all work with an AnchoredOffsetbox\n codes = {'upper right': 1,\n 'upper left': 2,\n 'lower left': 3,\n 'lower right': 4,\n 'right': 5,\n 'center left': 6,\n 'center right': 7,\n 'lower center': 8,\n 'upper center': 9,\n 'center': 10,\n }\n fig, ax = plt.subplots()\n da = DrawingArea(100, 100)\n for code in codes:\n anchored_box = AnchoredOffsetbox(loc=code, child=da)\n ax.add_artist(anchored_box)\n fig.canvas.draw()\n\n\ndef test_expand_with_tight_layout():\n # Check issue reported in #10476, and updated due to #10784\n fig, ax = plt.subplots()\n\n d1 = [1, 2]\n d2 = [2, 1]\n ax.plot(d1, label='series 1')\n ax.plot(d2, label='series 2')\n ax.legend(ncols=2, mode='expand')\n\n fig.tight_layout() # where the crash used to happen\n\n\n@pytest.mark.parametrize('widths',\n ([150], [150, 150, 150], [0.1], [0.1, 0.1]))\n@pytest.mark.parametrize('total', (250, 100, 0, -1, None))\n@pytest.mark.parametrize('sep', (250, 1, 0, -1))\n@pytest.mark.parametrize('mode', ("expand", "fixed", "equal"))\ndef test_get_packed_offsets(widths, total, sep, mode):\n # Check a (rather arbitrary) set of parameters due to successive similar\n # issue tickets (at least #10476 and #10784) related to corner cases\n # triggered inside this function when calling higher-level functions\n # (e.g. `Axes.legend`).\n # These are just some additional smoke tests. The output is untested.\n _get_packed_offsets(widths, total, sep, mode=mode)\n\n\n_Params = namedtuple('_Params', 'wd_list, total, sep, expected')\n\n\n@pytest.mark.parametrize('widths, total, sep, expected', [\n _Params( # total=None\n [3, 1, 2], total=None, sep=1, expected=(8, [0, 4, 6])),\n _Params( # total larger than required\n [3, 1, 2], total=10, sep=1, expected=(10, [0, 4, 6])),\n _Params( # total smaller than required\n [3, 1, 2], total=5, sep=1, expected=(5, [0, 4, 6])),\n])\ndef test_get_packed_offsets_fixed(widths, total, sep, expected):\n result = _get_packed_offsets(widths, total, sep, mode='fixed')\n assert result[0] == expected[0]\n assert_allclose(result[1], expected[1])\n\n\n@pytest.mark.parametrize('widths, total, sep, expected', [\n _Params( # total=None (implicit 1)\n [.1, .1, .1], total=None, sep=None, expected=(1, [0, .45, .9])),\n _Params( # total larger than sum of widths\n [3, 1, 2], total=10, sep=1, expected=(10, [0, 5, 8])),\n _Params( # total smaller sum of widths: overlapping boxes\n [3, 1, 2], total=5, sep=1, expected=(5, [0, 2.5, 3])),\n])\ndef test_get_packed_offsets_expand(widths, total, sep, expected):\n result = _get_packed_offsets(widths, total, sep, mode='expand')\n assert result[0] == expected[0]\n assert_allclose(result[1], expected[1])\n\n\n@pytest.mark.parametrize('widths, total, sep, expected', [\n _Params( # total larger than required\n [3, 2, 1], total=6, sep=None, expected=(6, [0, 2, 4])),\n _Params( # total smaller sum of widths: overlapping boxes\n [3, 2, 1, .5], total=2, sep=None, expected=(2, [0, 0.5, 1, 1.5])),\n _Params( # total larger than required\n [.5, 1, .2], total=None, sep=1, expected=(6, [0, 2, 4])),\n # the case total=None, sep=None is tested separately below\n])\ndef test_get_packed_offsets_equal(widths, total, sep, expected):\n result = _get_packed_offsets(widths, total, sep, mode='equal')\n assert result[0] == expected[0]\n assert_allclose(result[1], expected[1])\n\n\ndef test_get_packed_offsets_equal_total_none_sep_none():\n with pytest.raises(ValueError):\n _get_packed_offsets([1, 1, 1], total=None, sep=None, mode='equal')\n\n\n@pytest.mark.parametrize('child_type', ['draw', 'image', 'text'])\n@pytest.mark.parametrize('boxcoords',\n ['axes fraction', 'axes pixels', 'axes points',\n 'data'])\ndef test_picking(child_type, boxcoords):\n # These all take up approximately the same area.\n if child_type == 'draw':\n picking_child = DrawingArea(5, 5)\n picking_child.add_artist(mpatches.Rectangle((0, 0), 5, 5, linewidth=0))\n elif child_type == 'image':\n im = np.ones((5, 5))\n im[2, 2] = 0\n picking_child = OffsetImage(im)\n elif child_type == 'text':\n picking_child = TextArea('\N{Black Square}', textprops={'fontsize': 5})\n else:\n assert False, f'Unknown picking child type {child_type}'\n\n fig, ax = plt.subplots()\n ab = AnnotationBbox(picking_child, (0.5, 0.5), boxcoords=boxcoords)\n ab.set_picker(True)\n ax.add_artist(ab)\n\n calls = []\n fig.canvas.mpl_connect('pick_event', lambda event: calls.append(event))\n\n # Annotation should be picked by an event occurring at its center.\n if boxcoords == 'axes points':\n x, y = ax.transAxes.transform_point((0, 0))\n x += 0.5 * fig.dpi / 72\n y += 0.5 * fig.dpi / 72\n elif boxcoords == 'axes pixels':\n x, y = ax.transAxes.transform_point((0, 0))\n x += 0.5\n y += 0.5\n else:\n x, y = ax.transAxes.transform_point((0.5, 0.5))\n fig.canvas.draw()\n calls.clear()\n MouseEvent(\n "button_press_event", fig.canvas, x, y, MouseButton.LEFT)._process()\n assert len(calls) == 1 and calls[0].artist == ab\n\n # Annotation should *not* be picked by an event at its original center\n # point when the limits have changed enough to hide the *xy* point.\n ax.set_xlim(-1, 0)\n ax.set_ylim(-1, 0)\n fig.canvas.draw()\n calls.clear()\n MouseEvent(\n "button_press_event", fig.canvas, x, y, MouseButton.LEFT)._process()\n assert len(calls) == 0\n\n\n@image_comparison(['anchoredtext_align.png'], remove_text=True, style='mpl20')\ndef test_anchoredtext_horizontal_alignment():\n fig, ax = plt.subplots()\n\n text0 = AnchoredText("test\ntest long text", loc="center left",\n pad=0.2, prop={"ha": "left"})\n ax.add_artist(text0)\n text1 = AnchoredText("test\ntest long text", loc="center",\n pad=0.2, prop={"ha": "center"})\n ax.add_artist(text1)\n text2 = AnchoredText("test\ntest long text", loc="center right",\n pad=0.2, prop={"ha": "right"})\n ax.add_artist(text2)\n\n\n@pytest.mark.parametrize("extent_kind", ["window_extent", "tightbbox"])\ndef test_annotationbbox_extents(extent_kind):\n plt.rcParams.update(plt.rcParamsDefault)\n fig, ax = plt.subplots(figsize=(4, 3), dpi=100)\n\n ax.axis([0, 1, 0, 1])\n\n an1 = ax.annotate("Annotation", xy=(.9, .9), xytext=(1.1, 1.1),\n arrowprops=dict(arrowstyle="->"), clip_on=False,\n va="baseline", ha="left")\n\n da = DrawingArea(20, 20, 0, 0, clip=True)\n p = mpatches.Circle((-10, 30), 32)\n da.add_artist(p)\n\n ab3 = AnnotationBbox(da, [.5, .5], xybox=(-0.2, 0.5), xycoords='data',\n boxcoords="axes fraction", box_alignment=(0., .5),\n arrowprops=dict(arrowstyle="->"))\n ax.add_artist(ab3)\n\n im = OffsetImage(np.random.rand(10, 10), zoom=3)\n im.image.axes = ax\n ab6 = AnnotationBbox(im, (0.5, -.3), xybox=(0, 75),\n xycoords='axes fraction',\n boxcoords="offset points", pad=0.3,\n arrowprops=dict(arrowstyle="->"))\n ax.add_artist(ab6)\n\n # Test Annotation\n bb1 = getattr(an1, f"get_{extent_kind}")()\n\n target1 = [332.9, 242.8, 467.0, 298.9]\n assert_allclose(bb1.extents, target1, atol=2)\n\n # Test AnnotationBbox\n bb3 = getattr(ab3, f"get_{extent_kind}")()\n\n target3 = [-17.6, 129.0, 200.7, 167.9]\n assert_allclose(bb3.extents, target3, atol=2)\n\n bb6 = getattr(ab6, f"get_{extent_kind}")()\n\n target6 = [180.0, -32.0, 230.0, 92.9]\n assert_allclose(bb6.extents, target6, atol=2)\n\n # Test bbox_inches='tight'\n buf = io.BytesIO()\n fig.savefig(buf, bbox_inches='tight')\n buf.seek(0)\n shape = plt.imread(buf).shape\n targetshape = (350, 504, 4)\n assert_allclose(shape, targetshape, atol=2)\n\n # Simple smoke test for tight_layout, to make sure it does not error out.\n fig.canvas.draw()\n fig.tight_layout()\n fig.canvas.draw()\n\n\ndef test_zorder():\n assert OffsetBox(zorder=42).zorder == 42\n\n\ndef test_arrowprops_copied():\n da = DrawingArea(20, 20, 0, 0, clip=True)\n arrowprops = {"arrowstyle": "->", "relpos": (.3, .7)}\n ab = AnnotationBbox(da, [.5, .5], xybox=(-0.2, 0.5), xycoords='data',\n boxcoords="axes fraction", box_alignment=(0., .5),\n arrowprops=arrowprops)\n assert ab.arrowprops is not ab\n assert arrowprops["relpos"] == (.3, .7)\n\n\n@pytest.mark.parametrize("align", ["baseline", "bottom", "top",\n "left", "right", "center"])\ndef test_packers(align):\n # set the DPI to match points to make the math easier below\n fig = plt.figure(dpi=72)\n renderer = fig.canvas.get_renderer()\n\n x1, y1 = 10, 30\n x2, y2 = 20, 60\n r1 = DrawingArea(x1, y1)\n r2 = DrawingArea(x2, y2)\n\n # HPacker\n hpacker = HPacker(children=[r1, r2], align=align)\n hpacker.draw(renderer)\n bbox = hpacker.get_bbox(renderer)\n px, py = hpacker.get_offset(bbox, renderer)\n # width, height, xdescent, ydescent\n assert_allclose(bbox.bounds, (0, 0, x1 + x2, max(y1, y2)))\n # internal element placement\n if align in ("baseline", "left", "bottom"):\n y_height = 0\n elif align in ("right", "top"):\n y_height = y2 - y1\n elif align == "center":\n y_height = (y2 - y1) / 2\n # x-offsets, y-offsets\n assert_allclose([child.get_offset() for child in hpacker.get_children()],\n [(px, py + y_height), (px + x1, py)])\n\n # VPacker\n vpacker = VPacker(children=[r1, r2], align=align)\n vpacker.draw(renderer)\n bbox = vpacker.get_bbox(renderer)\n px, py = vpacker.get_offset(bbox, renderer)\n # width, height, xdescent, ydescent\n assert_allclose(bbox.bounds, (0, -max(y1, y2), max(x1, x2), y1 + y2))\n # internal element placement\n if align in ("baseline", "left", "bottom"):\n x_height = 0\n elif align in ("right", "top"):\n x_height = x2 - x1\n elif align == "center":\n x_height = (x2 - x1) / 2\n # x-offsets, y-offsets\n assert_allclose([child.get_offset() for child in vpacker.get_children()],\n [(px + x_height, py), (px, py - y2)])\n\n\ndef test_paddedbox_default_values():\n # smoke test paddedbox for correct default value\n fig, ax = plt.subplots()\n at = AnchoredText("foo", 'upper left')\n pb = PaddedBox(at, patch_attrs={'facecolor': 'r'}, draw_frame=True)\n ax.add_artist(pb)\n fig.draw_without_rendering()\n\n\ndef test_annotationbbox_properties():\n ab = AnnotationBbox(DrawingArea(20, 20, 0, 0, clip=True), (0.5, 0.5),\n xycoords='data')\n assert ab.xyann == (0.5, 0.5) # xy if xybox not given\n assert ab.anncoords == 'data' # xycoords if boxcoords not given\n\n ab = AnnotationBbox(DrawingArea(20, 20, 0, 0, clip=True), (0.5, 0.5),\n xybox=(-0.2, 0.4), xycoords='data',\n boxcoords='axes fraction')\n assert ab.xyann == (-0.2, 0.4) # xybox if given\n assert ab.anncoords == 'axes fraction' # boxcoords if given\n\n\ndef test_textarea_properties():\n ta = TextArea('Foo')\n assert ta.get_text() == 'Foo'\n assert not ta.get_multilinebaseline()\n\n ta.set_text('Bar')\n ta.set_multilinebaseline(True)\n assert ta.get_text() == 'Bar'\n assert ta.get_multilinebaseline()\n\n\n@check_figures_equal(extensions=['png'])\ndef test_textarea_set_text(fig_test, fig_ref):\n ax_ref = fig_ref.add_subplot()\n text0 = AnchoredText("Foo", "upper left")\n ax_ref.add_artist(text0)\n\n ax_test = fig_test.add_subplot()\n text1 = AnchoredText("Bar", "upper left")\n ax_test.add_artist(text1)\n text1.txt.set_text("Foo")\n\n\n@image_comparison(['paddedbox.png'], remove_text=True, style='mpl20')\ndef test_paddedbox():\n fig, ax = plt.subplots()\n\n ta = TextArea("foo")\n pb = PaddedBox(ta, pad=5, patch_attrs={'facecolor': 'r'}, draw_frame=True)\n ab = AnchoredOffsetbox('upper left', child=pb)\n ax.add_artist(ab)\n\n ta = TextArea("bar")\n pb = PaddedBox(ta, pad=10, patch_attrs={'facecolor': 'b'})\n ab = AnchoredOffsetbox('upper right', child=pb)\n ax.add_artist(ab)\n\n ta = TextArea("foobar")\n pb = PaddedBox(ta, pad=15, draw_frame=True)\n ab = AnchoredOffsetbox('lower right', child=pb)\n ax.add_artist(ab)\n\n\ndef test_remove_draggable():\n fig, ax = plt.subplots()\n an = ax.annotate("foo", (.5, .5))\n an.draggable(True)\n an.remove()\n MouseEvent("button_release_event", fig.canvas, 1, 1)._process()\n\n\ndef test_draggable_in_subfigure():\n fig = plt.figure()\n # Put annotation at lower left corner to make it easily pickable below.\n ann = fig.subfigures().add_axes([0, 0, 1, 1]).annotate("foo", (0, 0))\n ann.draggable(True)\n fig.canvas.draw() # Texts are non-pickable until the first draw.\n MouseEvent("button_press_event", fig.canvas, 1, 1)._process()\n assert ann._draggable.got_artist\n | .venv\Lib\site-packages\matplotlib\tests\test_offsetbox.py | test_offsetbox.py | Python | 16,137 | 0.95 | 0.077922 | 0.107612 | vue-tools | 136 | 2024-05-01T14:02:19.518911 | Apache-2.0 | true | f66f27753800445262961dbcd0e8ec15 |
"""\nTests specific to the patches module.\n"""\nimport platform\n\nimport numpy as np\nfrom numpy.testing import assert_almost_equal, assert_array_equal\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib.patches import (Annulus, Ellipse, Patch, Polygon, Rectangle,\n FancyArrowPatch, FancyArrow, BoxStyle, Arc)\nfrom matplotlib.testing.decorators import image_comparison, check_figures_equal\nfrom matplotlib.transforms import Bbox\nimport matplotlib.pyplot as plt\nfrom matplotlib import (\n collections as mcollections, colors as mcolors, patches as mpatches,\n path as mpath, transforms as mtransforms, rcParams)\n\n\ndef test_Polygon_close():\n #: GitHub issue #1018 identified a bug in the Polygon handling\n #: of the closed attribute; the path was not getting closed\n #: when set_xy was used to set the vertices.\n\n # open set of vertices:\n xy = [[0, 0], [0, 1], [1, 1]]\n # closed set:\n xyclosed = xy + [[0, 0]]\n\n # start with open path and close it:\n p = Polygon(xy, closed=True)\n assert p.get_closed()\n assert_array_equal(p.get_xy(), xyclosed)\n p.set_xy(xy)\n assert_array_equal(p.get_xy(), xyclosed)\n\n # start with closed path and open it:\n p = Polygon(xyclosed, closed=False)\n assert_array_equal(p.get_xy(), xy)\n p.set_xy(xyclosed)\n assert_array_equal(p.get_xy(), xy)\n\n # start with open path and leave it open:\n p = Polygon(xy, closed=False)\n assert not p.get_closed()\n assert_array_equal(p.get_xy(), xy)\n p.set_xy(xy)\n assert_array_equal(p.get_xy(), xy)\n\n # start with closed path and leave it closed:\n p = Polygon(xyclosed, closed=True)\n assert_array_equal(p.get_xy(), xyclosed)\n p.set_xy(xyclosed)\n assert_array_equal(p.get_xy(), xyclosed)\n\n\ndef test_corner_center():\n loc = [10, 20]\n width = 1\n height = 2\n\n # Rectangle\n # No rotation\n corners = ((10, 20), (11, 20), (11, 22), (10, 22))\n rect = Rectangle(loc, width, height)\n assert_array_equal(rect.get_corners(), corners)\n assert_array_equal(rect.get_center(), (10.5, 21))\n\n # 90 deg rotation\n corners_rot = ((10, 20), (10, 21), (8, 21), (8, 20))\n rect.set_angle(90)\n assert_array_equal(rect.get_corners(), corners_rot)\n assert_array_equal(rect.get_center(), (9, 20.5))\n\n # Rotation not a multiple of 90 deg\n theta = 33\n t = mtransforms.Affine2D().rotate_around(*loc, np.deg2rad(theta))\n corners_rot = t.transform(corners)\n rect.set_angle(theta)\n assert_almost_equal(rect.get_corners(), corners_rot)\n\n # Ellipse\n loc = [loc[0] + width / 2,\n loc[1] + height / 2]\n ellipse = Ellipse(loc, width, height)\n\n # No rotation\n assert_array_equal(ellipse.get_corners(), corners)\n\n # 90 deg rotation\n corners_rot = ((11.5, 20.5), (11.5, 21.5), (9.5, 21.5), (9.5, 20.5))\n ellipse.set_angle(90)\n assert_array_equal(ellipse.get_corners(), corners_rot)\n # Rotation shouldn't change ellipse center\n assert_array_equal(ellipse.get_center(), loc)\n\n # Rotation not a multiple of 90 deg\n theta = 33\n t = mtransforms.Affine2D().rotate_around(*loc, np.deg2rad(theta))\n corners_rot = t.transform(corners)\n ellipse.set_angle(theta)\n assert_almost_equal(ellipse.get_corners(), corners_rot)\n\n\ndef test_ellipse_vertices():\n # expect 0 for 0 ellipse width, height\n ellipse = Ellipse(xy=(0, 0), width=0, height=0, angle=0)\n assert_almost_equal(\n ellipse.get_vertices(),\n [(0.0, 0.0), (0.0, 0.0)],\n )\n assert_almost_equal(\n ellipse.get_co_vertices(),\n [(0.0, 0.0), (0.0, 0.0)],\n )\n\n ellipse = Ellipse(xy=(0, 0), width=2, height=1, angle=30)\n assert_almost_equal(\n ellipse.get_vertices(),\n [\n (\n ellipse.center[0] + ellipse.width / 4 * np.sqrt(3),\n ellipse.center[1] + ellipse.width / 4,\n ),\n (\n ellipse.center[0] - ellipse.width / 4 * np.sqrt(3),\n ellipse.center[1] - ellipse.width / 4,\n ),\n ],\n )\n assert_almost_equal(\n ellipse.get_co_vertices(),\n [\n (\n ellipse.center[0] - ellipse.height / 4,\n ellipse.center[1] + ellipse.height / 4 * np.sqrt(3),\n ),\n (\n ellipse.center[0] + ellipse.height / 4,\n ellipse.center[1] - ellipse.height / 4 * np.sqrt(3),\n ),\n ],\n )\n v1, v2 = np.array(ellipse.get_vertices())\n np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center)\n v1, v2 = np.array(ellipse.get_co_vertices())\n np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center)\n\n ellipse = Ellipse(xy=(2.252, -10.859), width=2.265, height=1.98, angle=68.78)\n v1, v2 = np.array(ellipse.get_vertices())\n np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center)\n v1, v2 = np.array(ellipse.get_co_vertices())\n np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center)\n\n\ndef test_rotate_rect():\n loc = np.asarray([1.0, 2.0])\n width = 2\n height = 3\n angle = 30.0\n\n # A rotated rectangle\n rect1 = Rectangle(loc, width, height, angle=angle)\n\n # A non-rotated rectangle\n rect2 = Rectangle(loc, width, height)\n\n # Set up an explicit rotation matrix (in radians)\n angle_rad = np.pi * angle / 180.0\n rotation_matrix = np.array([[np.cos(angle_rad), -np.sin(angle_rad)],\n [np.sin(angle_rad), np.cos(angle_rad)]])\n\n # Translate to origin, rotate each vertex, and then translate back\n new_verts = np.inner(rotation_matrix, rect2.get_verts() - loc).T + loc\n\n # They should be the same\n assert_almost_equal(rect1.get_verts(), new_verts)\n\n\n@check_figures_equal(extensions=['png'])\ndef test_rotate_rect_draw(fig_test, fig_ref):\n ax_test = fig_test.add_subplot()\n ax_ref = fig_ref.add_subplot()\n\n loc = (0, 0)\n width, height = (1, 1)\n angle = 30\n rect_ref = Rectangle(loc, width, height, angle=angle)\n ax_ref.add_patch(rect_ref)\n assert rect_ref.get_angle() == angle\n\n # Check that when the angle is updated after adding to an Axes, that the\n # patch is marked stale and redrawn in the correct location\n rect_test = Rectangle(loc, width, height)\n assert rect_test.get_angle() == 0\n ax_test.add_patch(rect_test)\n rect_test.set_angle(angle)\n assert rect_test.get_angle() == angle\n\n\n@check_figures_equal(extensions=['png'])\ndef test_dash_offset_patch_draw(fig_test, fig_ref):\n ax_test = fig_test.add_subplot()\n ax_ref = fig_ref.add_subplot()\n\n loc = (0.1, 0.1)\n width, height = (0.8, 0.8)\n rect_ref = Rectangle(loc, width, height, linewidth=3, edgecolor='b',\n linestyle=(0, [6, 6]))\n # fill the line gaps using a linestyle (0, [0, 6, 6, 0]), which is\n # equivalent to (6, [6, 6]) but has 0 dash offset\n rect_ref2 = Rectangle(loc, width, height, linewidth=3, edgecolor='r',\n linestyle=(0, [0, 6, 6, 0]))\n assert rect_ref.get_linestyle() == (0, [6, 6])\n assert rect_ref2.get_linestyle() == (0, [0, 6, 6, 0])\n\n ax_ref.add_patch(rect_ref)\n ax_ref.add_patch(rect_ref2)\n\n # Check that the dash offset of the rect is the same if we pass it in the\n # init method and if we create two rects with appropriate onoff sequence\n # of linestyle.\n\n rect_test = Rectangle(loc, width, height, linewidth=3, edgecolor='b',\n linestyle=(0, [6, 6]))\n rect_test2 = Rectangle(loc, width, height, linewidth=3, edgecolor='r',\n linestyle=(6, [6, 6]))\n assert rect_test.get_linestyle() == (0, [6, 6])\n assert rect_test2.get_linestyle() == (6, [6, 6])\n\n ax_test.add_patch(rect_test)\n ax_test.add_patch(rect_test2)\n\n\ndef test_negative_rect():\n # These two rectangles have the same vertices, but starting from a\n # different point. (We also drop the last vertex, which is a duplicate.)\n pos_vertices = Rectangle((-3, -2), 3, 2).get_verts()[:-1]\n neg_vertices = Rectangle((0, 0), -3, -2).get_verts()[:-1]\n assert_array_equal(np.roll(neg_vertices, 2, 0), pos_vertices)\n\n\n@image_comparison(['clip_to_bbox.png'])\ndef test_clip_to_bbox():\n fig, ax = plt.subplots()\n ax.set_xlim([-18, 20])\n ax.set_ylim([-150, 100])\n\n path = mpath.Path.unit_regular_star(8).deepcopy()\n path.vertices *= [10, 100]\n path.vertices -= [5, 25]\n\n path2 = mpath.Path.unit_circle().deepcopy()\n path2.vertices *= [10, 100]\n path2.vertices += [10, -25]\n\n combined = mpath.Path.make_compound_path(path, path2)\n\n patch = mpatches.PathPatch(\n combined, alpha=0.5, facecolor='coral', edgecolor='none')\n ax.add_patch(patch)\n\n bbox = mtransforms.Bbox([[-12, -77.5], [50, -110]])\n result_path = combined.clip_to_bbox(bbox)\n result_patch = mpatches.PathPatch(\n result_path, alpha=0.5, facecolor='green', lw=4, edgecolor='black')\n\n ax.add_patch(result_patch)\n\n\n@image_comparison(['patch_alpha_coloring'], remove_text=True)\ndef test_patch_alpha_coloring():\n """\n Test checks that the patch and collection are rendered with the specified\n alpha values in their facecolor and edgecolor.\n """\n star = mpath.Path.unit_regular_star(6)\n circle = mpath.Path.unit_circle()\n # concatenate the star with an internal cutout of the circle\n verts = np.concatenate([circle.vertices, star.vertices[::-1]])\n codes = np.concatenate([circle.codes, star.codes])\n cut_star1 = mpath.Path(verts, codes)\n cut_star2 = mpath.Path(verts + 1, codes)\n\n ax = plt.axes()\n col = mcollections.PathCollection([cut_star2],\n linewidth=5, linestyles='dashdot',\n facecolor=(1, 0, 0, 0.5),\n edgecolor=(0, 0, 1, 0.75))\n ax.add_collection(col)\n\n patch = mpatches.PathPatch(cut_star1,\n linewidth=5, linestyle='dashdot',\n facecolor=(1, 0, 0, 0.5),\n edgecolor=(0, 0, 1, 0.75))\n ax.add_patch(patch)\n\n ax.set_xlim(-1, 2)\n ax.set_ylim(-1, 2)\n\n\n@image_comparison(['patch_alpha_override'], remove_text=True)\ndef test_patch_alpha_override():\n #: Test checks that specifying an alpha attribute for a patch or\n #: collection will override any alpha component of the facecolor\n #: or edgecolor.\n star = mpath.Path.unit_regular_star(6)\n circle = mpath.Path.unit_circle()\n # concatenate the star with an internal cutout of the circle\n verts = np.concatenate([circle.vertices, star.vertices[::-1]])\n codes = np.concatenate([circle.codes, star.codes])\n cut_star1 = mpath.Path(verts, codes)\n cut_star2 = mpath.Path(verts + 1, codes)\n\n ax = plt.axes()\n col = mcollections.PathCollection([cut_star2],\n linewidth=5, linestyles='dashdot',\n alpha=0.25,\n facecolor=(1, 0, 0, 0.5),\n edgecolor=(0, 0, 1, 0.75))\n ax.add_collection(col)\n\n patch = mpatches.PathPatch(cut_star1,\n linewidth=5, linestyle='dashdot',\n alpha=0.25,\n facecolor=(1, 0, 0, 0.5),\n edgecolor=(0, 0, 1, 0.75))\n ax.add_patch(patch)\n\n ax.set_xlim(-1, 2)\n ax.set_ylim(-1, 2)\n\n\n@mpl.style.context('default')\ndef test_patch_color_none():\n # Make sure the alpha kwarg does not override 'none' facecolor.\n # Addresses issue #7478.\n c = plt.Circle((0, 0), 1, facecolor='none', alpha=1)\n assert c.get_facecolor()[0] == 0\n\n\n@image_comparison(['patch_custom_linestyle'], remove_text=True)\ndef test_patch_custom_linestyle():\n #: A test to check that patches and collections accept custom dash\n #: patterns as linestyle and that they display correctly.\n star = mpath.Path.unit_regular_star(6)\n circle = mpath.Path.unit_circle()\n # concatenate the star with an internal cutout of the circle\n verts = np.concatenate([circle.vertices, star.vertices[::-1]])\n codes = np.concatenate([circle.codes, star.codes])\n cut_star1 = mpath.Path(verts, codes)\n cut_star2 = mpath.Path(verts + 1, codes)\n\n ax = plt.axes()\n col = mcollections.PathCollection(\n [cut_star2],\n linewidth=5, linestyles=[(0, (5, 7, 10, 7))],\n facecolor=(1, 0, 0), edgecolor=(0, 0, 1))\n ax.add_collection(col)\n\n patch = mpatches.PathPatch(\n cut_star1,\n linewidth=5, linestyle=(0, (5, 7, 10, 7)),\n facecolor=(1, 0, 0), edgecolor=(0, 0, 1))\n ax.add_patch(patch)\n\n ax.set_xlim(-1, 2)\n ax.set_ylim(-1, 2)\n\n\ndef test_patch_linestyle_accents():\n #: Test if linestyle can also be specified with short mnemonics like "--"\n #: c.f. GitHub issue #2136\n star = mpath.Path.unit_regular_star(6)\n circle = mpath.Path.unit_circle()\n # concatenate the star with an internal cutout of the circle\n verts = np.concatenate([circle.vertices, star.vertices[::-1]])\n codes = np.concatenate([circle.codes, star.codes])\n\n linestyles = ["-", "--", "-.", ":",\n "solid", "dashed", "dashdot", "dotted"]\n\n fig, ax = plt.subplots()\n for i, ls in enumerate(linestyles):\n star = mpath.Path(verts + i, codes)\n patch = mpatches.PathPatch(star,\n linewidth=3, linestyle=ls,\n facecolor=(1, 0, 0),\n edgecolor=(0, 0, 1))\n ax.add_patch(patch)\n\n ax.set_xlim([-1, i + 1])\n ax.set_ylim([-1, i + 1])\n fig.canvas.draw()\n\n\n@check_figures_equal(extensions=['png'])\ndef test_patch_linestyle_none(fig_test, fig_ref):\n circle = mpath.Path.unit_circle()\n\n ax_test = fig_test.add_subplot()\n ax_ref = fig_ref.add_subplot()\n for i, ls in enumerate(['none', 'None', ' ', '']):\n path = mpath.Path(circle.vertices + i, circle.codes)\n patch = mpatches.PathPatch(path,\n linewidth=3, linestyle=ls,\n facecolor=(1, 0, 0),\n edgecolor=(0, 0, 1))\n ax_test.add_patch(patch)\n\n patch = mpatches.PathPatch(path,\n linewidth=3, linestyle='-',\n facecolor=(1, 0, 0),\n edgecolor='none')\n ax_ref.add_patch(patch)\n\n ax_test.set_xlim([-1, i + 1])\n ax_test.set_ylim([-1, i + 1])\n ax_ref.set_xlim([-1, i + 1])\n ax_ref.set_ylim([-1, i + 1])\n\n\ndef test_wedge_movement():\n param_dict = {'center': ((0, 0), (1, 1), 'set_center'),\n 'r': (5, 8, 'set_radius'),\n 'width': (2, 3, 'set_width'),\n 'theta1': (0, 30, 'set_theta1'),\n 'theta2': (45, 50, 'set_theta2')}\n\n init_args = {k: v[0] for k, v in param_dict.items()}\n\n w = mpatches.Wedge(**init_args)\n for attr, (old_v, new_v, func) in param_dict.items():\n assert getattr(w, attr) == old_v\n getattr(w, func)(new_v)\n assert getattr(w, attr) == new_v\n\n\n@image_comparison(['wedge_range'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.009)\ndef test_wedge_range():\n ax = plt.axes()\n\n t1 = 2.313869244286224\n\n args = [[52.31386924, 232.31386924],\n [52.313869244286224, 232.31386924428622],\n [t1, t1 + 180.0],\n [0, 360],\n [90, 90 + 360],\n [-180, 180],\n [0, 380],\n [45, 46],\n [46, 45]]\n\n for i, (theta1, theta2) in enumerate(args):\n x = i % 3\n y = i // 3\n\n wedge = mpatches.Wedge((x * 3, y * 3), 1, theta1, theta2,\n facecolor='none', edgecolor='k', lw=3)\n\n ax.add_artist(wedge)\n\n ax.set_xlim(-2, 8)\n ax.set_ylim(-2, 9)\n\n\ndef test_patch_str():\n """\n Check that patches have nice and working `str` representation.\n\n Note that the logic is that `__str__` is defined such that:\n str(eval(str(p))) == str(p)\n """\n p = mpatches.Circle(xy=(1, 2), radius=3)\n assert str(p) == 'Circle(xy=(1, 2), radius=3)'\n\n p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5)\n assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)'\n\n p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5)\n assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)'\n\n p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)\n assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)'\n\n p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)\n expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)'\n assert str(p) == expected\n\n p = mpatches.Annulus(xy=(1, 2), r=(3, 4), width=1, angle=2)\n expected = "Annulus(xy=(1, 2), r=(3, 4), width=1, angle=2)"\n assert str(p) == expected\n\n p = mpatches.RegularPolygon((1, 2), 20, radius=5)\n assert str(p) == "RegularPolygon((1, 2), 20, radius=5, orientation=0)"\n\n p = mpatches.CirclePolygon(xy=(1, 2), radius=5, resolution=20)\n assert str(p) == "CirclePolygon((1, 2), radius=5, resolution=20)"\n\n p = mpatches.FancyBboxPatch((1, 2), width=3, height=4)\n assert str(p) == "FancyBboxPatch((1, 2), width=3, height=4)"\n\n # Further nice __str__ which cannot be `eval`uated:\n path = mpath.Path([(1, 2), (2, 2), (1, 2)], closed=True)\n p = mpatches.PathPatch(path)\n assert str(p) == "PathPatch3((1, 2) ...)"\n\n p = mpatches.Polygon(np.empty((0, 2)))\n assert str(p) == "Polygon0()"\n\n data = [[1, 2], [2, 2], [1, 2]]\n p = mpatches.Polygon(data)\n assert str(p) == "Polygon3((1, 2) ...)"\n\n p = mpatches.FancyArrowPatch(path=path)\n assert str(p)[:27] == "FancyArrowPatch(Path(array("\n\n p = mpatches.FancyArrowPatch((1, 2), (3, 4))\n assert str(p) == "FancyArrowPatch((1, 2)->(3, 4))"\n\n p = mpatches.ConnectionPatch((1, 2), (3, 4), 'data')\n assert str(p) == "ConnectionPatch((1, 2), (3, 4))"\n\n s = mpatches.Shadow(p, 1, 1)\n assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))"\n\n # Not testing Arrow, FancyArrow here\n # because they seem to exist only for historical reasons.\n\n\n@image_comparison(['multi_color_hatch'], remove_text=True, style='default')\ndef test_multi_color_hatch():\n fig, ax = plt.subplots()\n\n rects = ax.bar(range(5), range(1, 6))\n for i, rect in enumerate(rects):\n rect.set_facecolor('none')\n rect.set_edgecolor(f'C{i}')\n rect.set_hatch('/')\n\n ax.autoscale_view()\n ax.autoscale(False)\n\n for i in range(5):\n with mpl.style.context({'hatch.color': f'C{i}'}):\n r = Rectangle((i - .8 / 2, 5), .8, 1, hatch='//', fc='none')\n ax.add_patch(r)\n\n\n@image_comparison(['units_rectangle.png'])\ndef test_units_rectangle():\n import matplotlib.testing.jpl_units as U\n U.register()\n\n p = mpatches.Rectangle((5*U.km, 6*U.km), 1*U.km, 2*U.km)\n\n fig, ax = plt.subplots()\n ax.add_patch(p)\n ax.set_xlim([4*U.km, 7*U.km])\n ax.set_ylim([5*U.km, 9*U.km])\n\n\n@image_comparison(['connection_patch.png'], style='mpl20', remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.024)\ndef test_connection_patch():\n fig, (ax1, ax2) = plt.subplots(1, 2)\n\n con = mpatches.ConnectionPatch(xyA=(0.1, 0.1), xyB=(0.9, 0.9),\n coordsA='data', coordsB='data',\n axesA=ax2, axesB=ax1,\n arrowstyle="->")\n ax2.add_artist(con)\n\n xyA = (0.6, 1.0) # in axes coordinates\n xyB = (0.0, 0.2) # x in axes coordinates, y in data coordinates\n coordsA = "axes fraction"\n coordsB = ax2.get_yaxis_transform()\n con = mpatches.ConnectionPatch(xyA=xyA, xyB=xyB, coordsA=coordsA,\n coordsB=coordsB, arrowstyle="-")\n ax2.add_artist(con)\n\n\n@check_figures_equal(extensions=["png"])\ndef test_connection_patch_fig(fig_test, fig_ref):\n # Test that connection patch can be added as figure artist, and that figure\n # pixels count negative values from the top right corner (this API may be\n # changed in the future).\n ax1, ax2 = fig_test.subplots(1, 2)\n con = mpatches.ConnectionPatch(\n xyA=(.3, .2), coordsA="data", axesA=ax1,\n xyB=(-30, -20), coordsB="figure pixels",\n arrowstyle="->", shrinkB=5)\n fig_test.add_artist(con)\n\n ax1, ax2 = fig_ref.subplots(1, 2)\n bb = fig_ref.bbox\n # Necessary so that pixel counts match on both sides.\n plt.rcParams["savefig.dpi"] = plt.rcParams["figure.dpi"]\n con = mpatches.ConnectionPatch(\n xyA=(.3, .2), coordsA="data", axesA=ax1,\n xyB=(bb.width - 30, bb.height - 20), coordsB="figure pixels",\n arrowstyle="->", shrinkB=5)\n fig_ref.add_artist(con)\n\n\n@check_figures_equal(extensions=["png"])\ndef test_connection_patch_pixel_points(fig_test, fig_ref):\n xyA_pts = (.3, .2)\n xyB_pts = (-30, -20)\n\n ax1, ax2 = fig_test.subplots(1, 2)\n con = mpatches.ConnectionPatch(xyA=xyA_pts, coordsA="axes points", axesA=ax1,\n xyB=xyB_pts, coordsB="figure points",\n arrowstyle="->", shrinkB=5)\n fig_test.add_artist(con)\n\n plt.rcParams["savefig.dpi"] = plt.rcParams["figure.dpi"]\n\n ax1, ax2 = fig_ref.subplots(1, 2)\n xyA_pix = (xyA_pts[0]*(fig_ref.dpi/72), xyA_pts[1]*(fig_ref.dpi/72))\n xyB_pix = (xyB_pts[0]*(fig_ref.dpi/72), xyB_pts[1]*(fig_ref.dpi/72))\n con = mpatches.ConnectionPatch(xyA=xyA_pix, coordsA="axes pixels", axesA=ax1,\n xyB=xyB_pix, coordsB="figure pixels",\n arrowstyle="->", shrinkB=5)\n fig_ref.add_artist(con)\n\n\ndef test_datetime_rectangle():\n # Check that creating a rectangle with timedeltas doesn't fail\n from datetime import datetime, timedelta\n\n start = datetime(2017, 1, 1, 0, 0, 0)\n delta = timedelta(seconds=16)\n patch = mpatches.Rectangle((start, 0), delta, 1)\n\n fig, ax = plt.subplots()\n ax.add_patch(patch)\n\n\ndef test_datetime_datetime_fails():\n from datetime import datetime\n\n start = datetime(2017, 1, 1, 0, 0, 0)\n dt_delta = datetime(1970, 1, 5) # Will be 5 days if units are done wrong.\n\n with pytest.raises(TypeError):\n mpatches.Rectangle((start, 0), dt_delta, 1)\n\n with pytest.raises(TypeError):\n mpatches.Rectangle((0, start), 1, dt_delta)\n\n\ndef test_contains_point():\n ell = mpatches.Ellipse((0.5, 0.5), 0.5, 1.0)\n points = [(0.0, 0.5), (0.2, 0.5), (0.25, 0.5), (0.5, 0.5)]\n path = ell.get_path()\n transform = ell.get_transform()\n radius = ell._process_radius(None)\n expected = np.array([path.contains_point(point,\n transform,\n radius) for point in points])\n result = np.array([ell.contains_point(point) for point in points])\n assert np.all(result == expected)\n\n\ndef test_contains_points():\n ell = mpatches.Ellipse((0.5, 0.5), 0.5, 1.0)\n points = [(0.0, 0.5), (0.2, 0.5), (0.25, 0.5), (0.5, 0.5)]\n path = ell.get_path()\n transform = ell.get_transform()\n radius = ell._process_radius(None)\n expected = path.contains_points(points, transform, radius)\n result = ell.contains_points(points)\n assert np.all(result == expected)\n\n\n# Currently fails with pdf/svg, probably because some parts assume a dpi of 72.\n@check_figures_equal(extensions=["png"])\ndef test_shadow(fig_test, fig_ref):\n xy = np.array([.2, .3])\n dxy = np.array([.1, .2])\n # We need to work around the nonsensical (dpi-dependent) interpretation of\n # offsets by the Shadow class...\n plt.rcParams["savefig.dpi"] = "figure"\n # Test image.\n a1 = fig_test.subplots()\n rect = mpatches.Rectangle(xy=xy, width=.5, height=.5)\n shadow = mpatches.Shadow(rect, ox=dxy[0], oy=dxy[1])\n a1.add_patch(rect)\n a1.add_patch(shadow)\n # Reference image.\n a2 = fig_ref.subplots()\n rect = mpatches.Rectangle(xy=xy, width=.5, height=.5)\n shadow = mpatches.Rectangle(\n xy=xy + fig_ref.dpi / 72 * dxy, width=.5, height=.5,\n fc=np.asarray(mcolors.to_rgb(rect.get_facecolor())) * .3,\n ec=np.asarray(mcolors.to_rgb(rect.get_facecolor())) * .3,\n alpha=.5)\n a2.add_patch(shadow)\n a2.add_patch(rect)\n\n\ndef test_fancyarrow_units():\n from datetime import datetime\n # Smoke test to check that FancyArrowPatch works with units\n dtime = datetime(2000, 1, 1)\n fig, ax = plt.subplots()\n arrow = FancyArrowPatch((0, dtime), (0.01, dtime))\n\n\ndef test_fancyarrow_setdata():\n fig, ax = plt.subplots()\n arrow = ax.arrow(0, 0, 10, 10, head_length=5, head_width=1, width=.5)\n expected1 = np.array(\n [[13.54, 13.54],\n [10.35, 9.65],\n [10.18, 9.82],\n [0.18, -0.18],\n [-0.18, 0.18],\n [9.82, 10.18],\n [9.65, 10.35],\n [13.54, 13.54]]\n )\n assert np.allclose(expected1, np.round(arrow.verts, 2))\n\n expected2 = np.array(\n [[16.71, 16.71],\n [16.71, 15.29],\n [16.71, 15.29],\n [1.71, 0.29],\n [0.29, 1.71],\n [15.29, 16.71],\n [15.29, 16.71],\n [16.71, 16.71]]\n )\n arrow.set_data(\n x=1, y=1, dx=15, dy=15, width=2, head_width=2, head_length=1\n )\n assert np.allclose(expected2, np.round(arrow.verts, 2))\n\n\n@image_comparison(["large_arc.svg"], style="mpl20")\ndef test_large_arc():\n fig, (ax1, ax2) = plt.subplots(1, 2)\n x = 210\n y = -2115\n diameter = 4261\n for ax in [ax1, ax2]:\n a = Arc((x, y), diameter, diameter, lw=2, color='k')\n ax.add_patch(a)\n ax.set_axis_off()\n ax.set_aspect('equal')\n # force the high accuracy case\n ax1.set_xlim(7, 8)\n ax1.set_ylim(5, 6)\n\n # force the low accuracy case\n ax2.set_xlim(-25000, 18000)\n ax2.set_ylim(-20000, 6600)\n\n\n@image_comparison(["all_quadrants_arcs.svg"], style="mpl20")\ndef test_rotated_arcs():\n fig, ax_arr = plt.subplots(2, 2, squeeze=False, figsize=(10, 10))\n\n scale = 10_000_000\n diag_centers = ((-1, -1), (-1, 1), (1, 1), (1, -1))\n on_axis_centers = ((0, 1), (1, 0), (0, -1), (-1, 0))\n skews = ((2, 2), (2, 1/10), (2, 1/100), (2, 1/1000))\n\n for ax, (sx, sy) in zip(ax_arr.ravel(), skews):\n k = 0\n for prescale, centers in zip((1 - .0001, (1 - .0001) / np.sqrt(2)),\n (on_axis_centers, diag_centers)):\n for j, (x_sign, y_sign) in enumerate(centers, start=k):\n a = Arc(\n (x_sign * scale * prescale,\n y_sign * scale * prescale),\n scale * sx,\n scale * sy,\n lw=4,\n color=f"C{j}",\n zorder=1 + j,\n angle=np.rad2deg(np.arctan2(y_sign, x_sign)) % 360,\n label=f'big {j}',\n gid=f'big {j}'\n )\n ax.add_patch(a)\n\n k = j+1\n ax.set_xlim(-scale / 4000, scale / 4000)\n ax.set_ylim(-scale / 4000, scale / 4000)\n ax.axhline(0, color="k")\n ax.axvline(0, color="k")\n ax.set_axis_off()\n ax.set_aspect("equal")\n\n\ndef test_fancyarrow_shape_error():\n with pytest.raises(ValueError, match="Got unknown shape: 'foo'"):\n FancyArrow(0, 0, 0.2, 0.2, shape='foo')\n\n\n@pytest.mark.parametrize('fmt, match', (\n ("foo", "Unknown style: 'foo'"),\n ("Round,foo", "Incorrect style argument: 'Round,foo'"),\n))\ndef test_boxstyle_errors(fmt, match):\n with pytest.raises(ValueError, match=match):\n BoxStyle(fmt)\n\n\n@image_comparison(baseline_images=['annulus'], extensions=['png'])\ndef test_annulus():\n\n fig, ax = plt.subplots()\n cir = Annulus((0.5, 0.5), 0.2, 0.05, fc='g') # circular annulus\n ell = Annulus((0.5, 0.5), (0.5, 0.3), 0.1, 45, # elliptical\n fc='m', ec='b', alpha=0.5, hatch='xxx')\n ax.add_patch(cir)\n ax.add_patch(ell)\n ax.set_aspect('equal')\n\n\n@image_comparison(baseline_images=['annulus'], extensions=['png'])\ndef test_annulus_setters():\n\n fig, ax = plt.subplots()\n cir = Annulus((0., 0.), 0.2, 0.01, fc='g') # circular annulus\n ell = Annulus((0., 0.), (1, 2), 0.1, 0, # elliptical\n fc='m', ec='b', alpha=0.5, hatch='xxx')\n ax.add_patch(cir)\n ax.add_patch(ell)\n ax.set_aspect('equal')\n\n cir.center = (0.5, 0.5)\n cir.radii = 0.2\n cir.width = 0.05\n\n ell.center = (0.5, 0.5)\n ell.radii = (0.5, 0.3)\n ell.width = 0.1\n ell.angle = 45\n\n\n@image_comparison(baseline_images=['annulus'], extensions=['png'])\ndef test_annulus_setters2():\n\n fig, ax = plt.subplots()\n cir = Annulus((0., 0.), 0.2, 0.01, fc='g') # circular annulus\n ell = Annulus((0., 0.), (1, 2), 0.1, 0, # elliptical\n fc='m', ec='b', alpha=0.5, hatch='xxx')\n ax.add_patch(cir)\n ax.add_patch(ell)\n ax.set_aspect('equal')\n\n cir.center = (0.5, 0.5)\n cir.set_semimajor(0.2)\n cir.set_semiminor(0.2)\n assert cir.radii == (0.2, 0.2)\n cir.width = 0.05\n\n ell.center = (0.5, 0.5)\n ell.set_semimajor(0.5)\n ell.set_semiminor(0.3)\n assert ell.radii == (0.5, 0.3)\n ell.width = 0.1\n ell.angle = 45\n\n\ndef test_degenerate_polygon():\n point = [0, 0]\n correct_extents = Bbox([point, point]).extents\n assert np.all(Polygon([point]).get_extents().extents == correct_extents)\n\n\n@pytest.mark.parametrize('kwarg', ('edgecolor', 'facecolor'))\ndef test_color_override_warning(kwarg):\n with pytest.warns(UserWarning,\n match="Setting the 'color' property will override "\n "the edgecolor or facecolor properties."):\n Patch(color='black', **{kwarg: 'black'})\n\n\ndef test_empty_verts():\n poly = Polygon(np.zeros((0, 2)))\n assert poly.get_verts() == []\n\n\ndef test_default_antialiased():\n patch = Patch()\n\n patch.set_antialiased(not rcParams['patch.antialiased'])\n assert patch.get_antialiased() == (not rcParams['patch.antialiased'])\n # Check that None resets the state\n patch.set_antialiased(None)\n assert patch.get_antialiased() == rcParams['patch.antialiased']\n\n\ndef test_default_linestyle():\n patch = Patch()\n patch.set_linestyle('--')\n patch.set_linestyle(None)\n assert patch.get_linestyle() == 'solid'\n\n\ndef test_default_capstyle():\n patch = Patch()\n assert patch.get_capstyle() == 'butt'\n\n\ndef test_default_joinstyle():\n patch = Patch()\n assert patch.get_joinstyle() == 'miter'\n\n\n@image_comparison(["autoscale_arc"], extensions=['png', 'svg'],\n style="mpl20", remove_text=True)\ndef test_autoscale_arc():\n fig, axs = plt.subplots(1, 3, figsize=(4, 1))\n arc_lists = (\n [Arc((0, 0), 1, 1, theta1=0, theta2=90)],\n [Arc((0.5, 0.5), 1.5, 0.5, theta1=10, theta2=20)],\n [Arc((0.5, 0.5), 1.5, 0.5, theta1=10, theta2=20),\n Arc((0.5, 0.5), 2.5, 0.5, theta1=110, theta2=120),\n Arc((0.5, 0.5), 3.5, 0.5, theta1=210, theta2=220),\n Arc((0.5, 0.5), 4.5, 0.5, theta1=310, theta2=320)])\n\n for ax, arcs in zip(axs, arc_lists):\n for arc in arcs:\n ax.add_patch(arc)\n ax.autoscale()\n\n\n@check_figures_equal(extensions=["png", 'svg', 'pdf', 'eps'])\ndef test_arc_in_collection(fig_test, fig_ref):\n arc1 = Arc([.5, .5], .5, 1, theta1=0, theta2=60, angle=20)\n arc2 = Arc([.5, .5], .5, 1, theta1=0, theta2=60, angle=20)\n col = mcollections.PatchCollection(patches=[arc2], facecolors='none',\n edgecolors='k')\n fig_ref.subplots().add_patch(arc1)\n fig_test.subplots().add_collection(col)\n\n\n@check_figures_equal(extensions=["png", 'svg', 'pdf', 'eps'])\ndef test_modifying_arc(fig_test, fig_ref):\n arc1 = Arc([.5, .5], .5, 1, theta1=0, theta2=60, angle=20)\n arc2 = Arc([.5, .5], 1.5, 1, theta1=0, theta2=60, angle=10)\n fig_ref.subplots().add_patch(arc1)\n fig_test.subplots().add_patch(arc2)\n arc2.set_width(.5)\n arc2.set_angle(20)\n\n\ndef test_arrow_set_data():\n fig, ax = plt.subplots()\n arrow = mpl.patches.Arrow(2, 0, 0, 10)\n expected1 = np.array(\n [[1.9, 0.],\n [2.1, -0.],\n [2.1, 8.],\n [2.3, 8.],\n [2., 10.],\n [1.7, 8.],\n [1.9, 8.],\n [1.9, 0.]]\n )\n assert np.allclose(expected1, np.round(arrow.get_verts(), 2))\n\n expected2 = np.array(\n [[0.39, 0.04],\n [0.61, -0.04],\n [3.01, 6.36],\n [3.24, 6.27],\n [3.5, 8.],\n [2.56, 6.53],\n [2.79, 6.44],\n [0.39, 0.04]]\n )\n arrow.set_data(x=.5, dx=3, dy=8, width=1.2)\n assert np.allclose(expected2, np.round(arrow.get_verts(), 2))\n\n\n@check_figures_equal(extensions=["png", "pdf", "svg", "eps"])\ndef test_set_and_get_hatch_linewidth(fig_test, fig_ref):\n ax_test = fig_test.add_subplot()\n ax_ref = fig_ref.add_subplot()\n\n lw = 2.0\n\n with plt.rc_context({"hatch.linewidth": lw}):\n ax_ref.add_patch(mpatches.Rectangle((0, 0), 1, 1, hatch="x"))\n\n ax_test.add_patch(mpatches.Rectangle((0, 0), 1, 1, hatch="x"))\n ax_test.patches[0].set_hatch_linewidth(lw)\n\n assert ax_ref.patches[0].get_hatch_linewidth() == lw\n assert ax_test.patches[0].get_hatch_linewidth() == lw\n | .venv\Lib\site-packages\matplotlib\tests\test_patches.py | test_patches.py | Python | 33,466 | 0.95 | 0.072927 | 0.079146 | python-kit | 773 | 2024-08-01T00:24:59.819162 | Apache-2.0 | true | 6c0f3c6fa2bec49bbcec185781c57d6b |
import platform\nimport re\n\nimport numpy as np\n\nfrom numpy.testing import assert_array_equal\nimport pytest\n\nfrom matplotlib import patches\nfrom matplotlib.path import Path\nfrom matplotlib.patches import Polygon\nfrom matplotlib.testing.decorators import image_comparison\nimport matplotlib.pyplot as plt\nfrom matplotlib import transforms\nfrom matplotlib.backend_bases import MouseEvent\n\n\ndef test_empty_closed_path():\n path = Path(np.zeros((0, 2)), closed=True)\n assert path.vertices.shape == (0, 2)\n assert path.codes is None\n assert_array_equal(path.get_extents().extents,\n transforms.Bbox.null().extents)\n\n\ndef test_readonly_path():\n path = Path.unit_circle()\n\n def modify_vertices():\n path.vertices = path.vertices * 2.0\n\n with pytest.raises(AttributeError):\n modify_vertices()\n\n\ndef test_path_exceptions():\n bad_verts1 = np.arange(12).reshape(4, 3)\n with pytest.raises(ValueError,\n match=re.escape(f'has shape {bad_verts1.shape}')):\n Path(bad_verts1)\n\n bad_verts2 = np.arange(12).reshape(2, 3, 2)\n with pytest.raises(ValueError,\n match=re.escape(f'has shape {bad_verts2.shape}')):\n Path(bad_verts2)\n\n good_verts = np.arange(12).reshape(6, 2)\n bad_codes = np.arange(2)\n msg = re.escape(f"Your vertices have shape {good_verts.shape} "\n f"but your codes have shape {bad_codes.shape}")\n with pytest.raises(ValueError, match=msg):\n Path(good_verts, bad_codes)\n\n\ndef test_point_in_path():\n # Test #1787\n path = Path._create_closed([(0, 0), (0, 1), (1, 1), (1, 0)])\n points = [(0.5, 0.5), (1.5, 0.5)]\n ret = path.contains_points(points)\n assert ret.dtype == 'bool'\n np.testing.assert_equal(ret, [True, False])\n\n\n@pytest.mark.parametrize(\n "other_path, inside, inverted_inside",\n [(Path([(0.25, 0.25), (0.25, 0.75), (0.75, 0.75), (0.75, 0.25), (0.25, 0.25)],\n closed=True), True, False),\n (Path([(-0.25, -0.25), (-0.25, 1.75), (1.75, 1.75), (1.75, -0.25), (-0.25, -0.25)],\n closed=True), False, True),\n (Path([(-0.25, -0.25), (-0.25, 1.75), (0.5, 0.5),\n (1.75, 1.75), (1.75, -0.25), (-0.25, -0.25)],\n closed=True), False, False),\n (Path([(0.25, 0.25), (0.25, 1.25), (1.25, 1.25), (1.25, 0.25), (0.25, 0.25)],\n closed=True), False, False),\n (Path([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)], closed=True), False, False),\n (Path([(2, 2), (2, 3), (3, 3), (3, 2), (2, 2)], closed=True), False, False)])\ndef test_contains_path(other_path, inside, inverted_inside):\n path = Path([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)], closed=True)\n assert path.contains_path(other_path) is inside\n assert other_path.contains_path(path) is inverted_inside\n\n\ndef test_contains_points_negative_radius():\n path = Path.unit_circle()\n\n points = [(0.0, 0.0), (1.25, 0.0), (0.9, 0.9)]\n result = path.contains_points(points, radius=-0.5)\n np.testing.assert_equal(result, [True, False, False])\n\n\n_test_paths = [\n # interior extrema determine extents and degenerate derivative\n Path([[0, 0], [1, 0], [1, 1], [0, 1]],\n [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]),\n # a quadratic curve\n Path([[0, 0], [0, 1], [1, 0]], [Path.MOVETO, Path.CURVE3, Path.CURVE3]),\n # a linear curve, degenerate vertically\n Path([[0, 1], [1, 1]], [Path.MOVETO, Path.LINETO]),\n # a point\n Path([[1, 2]], [Path.MOVETO]),\n]\n\n\n_test_path_extents = [(0., 0., 0.75, 1.), (0., 0., 1., 0.5), (0., 1., 1., 1.),\n (1., 2., 1., 2.)]\n\n\n@pytest.mark.parametrize('path, extents', zip(_test_paths, _test_path_extents))\ndef test_exact_extents(path, extents):\n # notice that if we just looked at the control points to get the bounding\n # box of each curve, we would get the wrong answers. For example, for\n # hard_curve = Path([[0, 0], [1, 0], [1, 1], [0, 1]],\n # [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4])\n # we would get that the extents area (0, 0, 1, 1). This code takes into\n # account the curved part of the path, which does not typically extend all\n # the way out to the control points.\n # Note that counterintuitively, path.get_extents() returns a Bbox, so we\n # have to get that Bbox's `.extents`.\n assert np.all(path.get_extents().extents == extents)\n\n\n@pytest.mark.parametrize('ignored_code', [Path.CLOSEPOLY, Path.STOP])\ndef test_extents_with_ignored_codes(ignored_code):\n # Check that STOP and CLOSEPOLY points are ignored when calculating extents\n # of a path with only straight lines\n path = Path([[0, 0],\n [1, 1],\n [2, 2]], [Path.MOVETO, Path.MOVETO, ignored_code])\n assert np.all(path.get_extents().extents == (0., 0., 1., 1.))\n\n\ndef test_point_in_path_nan():\n box = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])\n p = Path(box)\n test = np.array([[np.nan, 0.5]])\n contains = p.contains_points(test)\n assert len(contains) == 1\n assert not contains[0]\n\n\ndef test_nonlinear_containment():\n fig, ax = plt.subplots()\n ax.set(xscale="log", ylim=(0, 1))\n polygon = ax.axvspan(1, 10)\n assert polygon.get_path().contains_point(\n ax.transData.transform((5, .5)), polygon.get_transform())\n assert not polygon.get_path().contains_point(\n ax.transData.transform((.5, .5)), polygon.get_transform())\n assert not polygon.get_path().contains_point(\n ax.transData.transform((50, .5)), polygon.get_transform())\n\n\n@image_comparison(['arrow_contains_point.png'], remove_text=True, style='mpl20',\n tol=0 if platform.machine() == 'x86_64' else 0.027)\ndef test_arrow_contains_point():\n # fix bug (#8384)\n fig, ax = plt.subplots()\n ax.set_xlim((0, 2))\n ax.set_ylim((0, 2))\n\n # create an arrow with Curve style\n arrow = patches.FancyArrowPatch((0.5, 0.25), (1.5, 0.75),\n arrowstyle='->',\n mutation_scale=40)\n ax.add_patch(arrow)\n # create an arrow with Bracket style\n arrow1 = patches.FancyArrowPatch((0.5, 1), (1.5, 1.25),\n arrowstyle=']-[',\n mutation_scale=40)\n ax.add_patch(arrow1)\n # create an arrow with other arrow style\n arrow2 = patches.FancyArrowPatch((0.5, 1.5), (1.5, 1.75),\n arrowstyle='fancy',\n fill=False,\n mutation_scale=40)\n ax.add_patch(arrow2)\n patches_list = [arrow, arrow1, arrow2]\n\n # generate some points\n X, Y = np.meshgrid(np.arange(0, 2, 0.1),\n np.arange(0, 2, 0.1))\n for k, (x, y) in enumerate(zip(X.ravel(), Y.ravel())):\n xdisp, ydisp = ax.transData.transform([x, y])\n event = MouseEvent('button_press_event', fig.canvas, xdisp, ydisp)\n for m, patch in enumerate(patches_list):\n # set the points to red only if the arrow contains the point\n inside, res = patch.contains(event)\n if inside:\n ax.scatter(x, y, s=5, c="r")\n\n\n@image_comparison(['path_clipping.svg'], remove_text=True)\ndef test_path_clipping():\n fig = plt.figure(figsize=(6.0, 6.2))\n\n for i, xy in enumerate([\n [(200, 200), (200, 350), (400, 350), (400, 200)],\n [(200, 200), (200, 350), (400, 350), (400, 100)],\n [(200, 100), (200, 350), (400, 350), (400, 100)],\n [(200, 100), (200, 415), (400, 350), (400, 100)],\n [(200, 100), (200, 415), (400, 415), (400, 100)],\n [(200, 415), (400, 415), (400, 100), (200, 100)],\n [(400, 415), (400, 100), (200, 100), (200, 415)]]):\n ax = fig.add_subplot(4, 2, i+1)\n bbox = [0, 140, 640, 260]\n ax.set_xlim(bbox[0], bbox[0] + bbox[2])\n ax.set_ylim(bbox[1], bbox[1] + bbox[3])\n ax.add_patch(Polygon(\n xy, facecolor='none', edgecolor='red', closed=True))\n\n\n@image_comparison(['semi_log_with_zero.png'], style='mpl20')\ndef test_log_transform_with_zero():\n x = np.arange(-10, 10)\n y = (1.0 - 1.0/(x**2+1))**20\n\n fig, ax = plt.subplots()\n ax.semilogy(x, y, "-o", lw=15, markeredgecolor='k')\n ax.set_ylim(1e-7, 1)\n ax.grid(True)\n\n\ndef test_make_compound_path_empty():\n # We should be able to make a compound path with no arguments.\n # This makes it easier to write generic path based code.\n empty = Path.make_compound_path()\n assert empty.vertices.shape == (0, 2)\n r2 = Path.make_compound_path(empty, empty)\n assert r2.vertices.shape == (0, 2)\n assert r2.codes.shape == (0,)\n r3 = Path.make_compound_path(Path([(0, 0)]), empty)\n assert r3.vertices.shape == (1, 2)\n assert r3.codes.shape == (1,)\n\n\ndef test_make_compound_path_stops():\n zero = [0, 0]\n paths = 3*[Path([zero, zero], [Path.MOVETO, Path.STOP])]\n compound_path = Path.make_compound_path(*paths)\n # the choice to not preserve the terminal STOP is arbitrary, but\n # documented, so we test that it is in fact respected here\n assert np.sum(compound_path.codes == Path.STOP) == 0\n\n\n@image_comparison(['xkcd.png'], remove_text=True)\ndef test_xkcd():\n np.random.seed(0)\n\n x = np.linspace(0, 2 * np.pi, 100)\n y = np.sin(x)\n\n with plt.xkcd():\n fig, ax = plt.subplots()\n ax.plot(x, y)\n\n\n@image_comparison(['xkcd_marker.png'], remove_text=True)\ndef test_xkcd_marker():\n np.random.seed(0)\n\n x = np.linspace(0, 5, 8)\n y1 = x\n y2 = 5 - x\n y3 = 2.5 * np.ones(8)\n\n with plt.xkcd():\n fig, ax = plt.subplots()\n ax.plot(x, y1, '+', ms=10)\n ax.plot(x, y2, 'o', ms=10)\n ax.plot(x, y3, '^', ms=10)\n\n\n@image_comparison(['marker_paths.pdf'], remove_text=True)\ndef test_marker_paths_pdf():\n N = 7\n\n plt.errorbar(np.arange(N),\n np.ones(N) + 4,\n np.ones(N))\n plt.xlim(-1, N)\n plt.ylim(-1, 7)\n\n\n@image_comparison(['nan_path'], style='default', remove_text=True,\n extensions=['pdf', 'svg', 'eps', 'png'],\n tol=0 if platform.machine() == 'x86_64' else 0.009)\ndef test_nan_isolated_points():\n\n y0 = [0, np.nan, 2, np.nan, 4, 5, 6]\n y1 = [np.nan, 7, np.nan, 9, 10, np.nan, 12]\n\n fig, ax = plt.subplots()\n\n ax.plot(y0, '-o')\n ax.plot(y1, '-o')\n\n\ndef test_path_no_doubled_point_in_to_polygon():\n hand = np.array(\n [[1.64516129, 1.16145833],\n [1.64516129, 1.59375],\n [1.35080645, 1.921875],\n [1.375, 2.18229167],\n [1.68548387, 1.9375],\n [1.60887097, 2.55208333],\n [1.68548387, 2.69791667],\n [1.76209677, 2.56770833],\n [1.83064516, 1.97395833],\n [1.89516129, 2.75],\n [1.9516129, 2.84895833],\n [2.01209677, 2.76041667],\n [1.99193548, 1.99479167],\n [2.11290323, 2.63020833],\n [2.2016129, 2.734375],\n [2.25403226, 2.60416667],\n [2.14919355, 1.953125],\n [2.30645161, 2.36979167],\n [2.39112903, 2.36979167],\n [2.41532258, 2.1875],\n [2.1733871, 1.703125],\n [2.07782258, 1.16666667]])\n\n (r0, c0, r1, c1) = (1.0, 1.5, 2.1, 2.5)\n\n poly = Path(np.vstack((hand[:, 1], hand[:, 0])).T, closed=True)\n clip_rect = transforms.Bbox([[r0, c0], [r1, c1]])\n poly_clipped = poly.clip_to_bbox(clip_rect).to_polygons()[0]\n\n assert np.all(poly_clipped[-2] != poly_clipped[-1])\n assert np.all(poly_clipped[-1] == poly_clipped[0])\n\n\ndef test_path_to_polygons():\n data = [[10, 10], [20, 20]]\n p = Path(data)\n\n assert_array_equal(p.to_polygons(width=40, height=40), [])\n assert_array_equal(p.to_polygons(width=40, height=40, closed_only=False),\n [data])\n assert_array_equal(p.to_polygons(), [])\n assert_array_equal(p.to_polygons(closed_only=False), [data])\n\n data = [[10, 10], [20, 20], [30, 30]]\n closed_data = [[10, 10], [20, 20], [30, 30], [10, 10]]\n p = Path(data)\n\n assert_array_equal(p.to_polygons(width=40, height=40), [closed_data])\n assert_array_equal(p.to_polygons(width=40, height=40, closed_only=False),\n [data])\n assert_array_equal(p.to_polygons(), [closed_data])\n assert_array_equal(p.to_polygons(closed_only=False), [data])\n\n\ndef test_path_deepcopy():\n # Should not raise any error\n verts = [[0, 0], [1, 1]]\n codes = [Path.MOVETO, Path.LINETO]\n path1 = Path(verts)\n path2 = Path(verts, codes)\n path1_copy = path1.deepcopy()\n path2_copy = path2.deepcopy()\n assert path1 is not path1_copy\n assert path1.vertices is not path1_copy.vertices\n assert path2 is not path2_copy\n assert path2.vertices is not path2_copy.vertices\n assert path2.codes is not path2_copy.codes\n\n\ndef test_path_shallowcopy():\n # Should not raise any error\n verts = [[0, 0], [1, 1]]\n codes = [Path.MOVETO, Path.LINETO]\n path1 = Path(verts)\n path2 = Path(verts, codes)\n path1_copy = path1.copy()\n path2_copy = path2.copy()\n assert path1 is not path1_copy\n assert path1.vertices is path1_copy.vertices\n assert path2 is not path2_copy\n assert path2.vertices is path2_copy.vertices\n assert path2.codes is path2_copy.codes\n\n\n@pytest.mark.parametrize('phi', np.concatenate([\n np.array([0, 15, 30, 45, 60, 75, 90, 105, 120, 135]) + delta\n for delta in [-1, 0, 1]]))\ndef test_path_intersect_path(phi):\n # test for the range of intersection angles\n eps_array = [1e-5, 1e-8, 1e-10, 1e-12]\n\n transform = transforms.Affine2D().rotate(np.deg2rad(phi))\n\n # a and b intersect at angle phi\n a = Path([(-2, 0), (2, 0)])\n b = transform.transform_path(a)\n assert a.intersects_path(b) and b.intersects_path(a)\n\n # a and b touch at angle phi at (0, 0)\n a = Path([(0, 0), (2, 0)])\n b = transform.transform_path(a)\n assert a.intersects_path(b) and b.intersects_path(a)\n\n # a and b are orthogonal and intersect at (0, 3)\n a = transform.transform_path(Path([(0, 1), (0, 3)]))\n b = transform.transform_path(Path([(1, 3), (0, 3)]))\n assert a.intersects_path(b) and b.intersects_path(a)\n\n # a and b are collinear and intersect at (0, 3)\n a = transform.transform_path(Path([(0, 1), (0, 3)]))\n b = transform.transform_path(Path([(0, 5), (0, 3)]))\n assert a.intersects_path(b) and b.intersects_path(a)\n\n # self-intersect\n assert a.intersects_path(a)\n\n # a contains b\n a = transform.transform_path(Path([(0, 0), (5, 5)]))\n b = transform.transform_path(Path([(1, 1), (3, 3)]))\n assert a.intersects_path(b) and b.intersects_path(a)\n\n # a and b are collinear but do not intersect\n a = transform.transform_path(Path([(0, 1), (0, 5)]))\n b = transform.transform_path(Path([(3, 0), (3, 3)]))\n assert not a.intersects_path(b) and not b.intersects_path(a)\n\n # a and b are on the same line but do not intersect\n a = transform.transform_path(Path([(0, 1), (0, 5)]))\n b = transform.transform_path(Path([(0, 6), (0, 7)]))\n assert not a.intersects_path(b) and not b.intersects_path(a)\n\n # Note: 1e-13 is the absolute tolerance error used for\n # `isclose` function from src/_path.h\n\n # a and b are parallel but do not touch\n for eps in eps_array:\n a = transform.transform_path(Path([(0, 1), (0, 5)]))\n b = transform.transform_path(Path([(0 + eps, 1), (0 + eps, 5)]))\n assert not a.intersects_path(b) and not b.intersects_path(a)\n\n # a and b are on the same line but do not intersect (really close)\n for eps in eps_array:\n a = transform.transform_path(Path([(0, 1), (0, 5)]))\n b = transform.transform_path(Path([(0, 5 + eps), (0, 7)]))\n assert not a.intersects_path(b) and not b.intersects_path(a)\n\n # a and b are on the same line and intersect (really close)\n for eps in eps_array:\n a = transform.transform_path(Path([(0, 1), (0, 5)]))\n b = transform.transform_path(Path([(0, 5 - eps), (0, 7)]))\n assert a.intersects_path(b) and b.intersects_path(a)\n\n # b is the same as a but with an extra point\n a = transform.transform_path(Path([(0, 1), (0, 5)]))\n b = transform.transform_path(Path([(0, 1), (0, 2), (0, 5)]))\n assert a.intersects_path(b) and b.intersects_path(a)\n\n # a and b are collinear but do not intersect\n a = transform.transform_path(Path([(1, -1), (0, -1)]))\n b = transform.transform_path(Path([(0, 1), (0.9, 1)]))\n assert not a.intersects_path(b) and not b.intersects_path(a)\n\n # a and b are collinear but do not intersect\n a = transform.transform_path(Path([(0., -5.), (1., -5.)]))\n b = transform.transform_path(Path([(1., 5.), (0., 5.)]))\n assert not a.intersects_path(b) and not b.intersects_path(a)\n\n\n@pytest.mark.parametrize('offset', range(-720, 361, 45))\ndef test_full_arc(offset):\n low = offset\n high = 360 + offset\n\n path = Path.arc(low, high)\n mins = np.min(path.vertices, axis=0)\n maxs = np.max(path.vertices, axis=0)\n np.testing.assert_allclose(mins, -1)\n np.testing.assert_allclose(maxs, 1)\n\n\ndef test_disjoint_zero_length_segment():\n this_path = Path(\n np.array([\n [824.85064295, 2056.26489203],\n [861.69033931, 2041.00539016],\n [868.57864109, 2057.63522175],\n [831.73894473, 2072.89472361],\n [824.85064295, 2056.26489203]]),\n np.array([1, 2, 2, 2, 79], dtype=Path.code_type))\n\n outline_path = Path(\n np.array([\n [859.91051028, 2165.38461538],\n [859.06772495, 2149.30331334],\n [859.06772495, 2181.46591743],\n [859.91051028, 2165.38461538],\n [859.91051028, 2165.38461538]]),\n np.array([1, 2, 2, 2, 2],\n dtype=Path.code_type))\n\n assert not outline_path.intersects_path(this_path)\n assert not this_path.intersects_path(outline_path)\n\n\ndef test_intersect_zero_length_segment():\n this_path = Path(\n np.array([\n [0, 0],\n [1, 1],\n ]))\n\n outline_path = Path(\n np.array([\n [1, 0],\n [.5, .5],\n [.5, .5],\n [0, 1],\n ]))\n\n assert outline_path.intersects_path(this_path)\n assert this_path.intersects_path(outline_path)\n\n\ndef test_cleanup_closepoly():\n # if the first connected component of a Path ends in a CLOSEPOLY, but that\n # component contains a NaN, then Path.cleaned should ignore not just the\n # control points but also the CLOSEPOLY, since it has nowhere valid to\n # point.\n paths = [\n Path([[np.nan, np.nan], [np.nan, np.nan]],\n [Path.MOVETO, Path.CLOSEPOLY]),\n # we trigger a different path in the C++ code if we don't pass any\n # codes explicitly, so we must also make sure that this works\n Path([[np.nan, np.nan], [np.nan, np.nan]]),\n # we should also make sure that this cleanup works if there's some\n # multi-vertex curves\n Path([[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan],\n [np.nan, np.nan]],\n [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY])\n ]\n for p in paths:\n cleaned = p.cleaned(remove_nans=True)\n assert len(cleaned) == 1\n assert cleaned.codes[0] == Path.STOP\n\n\ndef test_interpolated_moveto():\n # Initial path has two subpaths with two LINETOs each\n vertices = np.array([[0, 0],\n [0, 1],\n [1, 2],\n [4, 4],\n [4, 5],\n [5, 5]])\n codes = [Path.MOVETO, Path.LINETO, Path.LINETO] * 2\n\n path = Path(vertices, codes)\n result = path.interpolated(3)\n\n # Result should have two subpaths with six LINETOs each\n expected_subpath_codes = [Path.MOVETO] + [Path.LINETO] * 6\n np.testing.assert_array_equal(result.codes, expected_subpath_codes * 2)\n\n\ndef test_interpolated_closepoly():\n codes = [Path.MOVETO] + [Path.LINETO]*2 + [Path.CLOSEPOLY]\n vertices = [(4, 3), (5, 4), (5, 3), (0, 0)]\n\n path = Path(vertices, codes)\n result = path.interpolated(2)\n\n expected_vertices = np.array([[4, 3],\n [4.5, 3.5],\n [5, 4],\n [5, 3.5],\n [5, 3],\n [4.5, 3],\n [4, 3]])\n expected_codes = [Path.MOVETO] + [Path.LINETO]*5 + [Path.CLOSEPOLY]\n\n np.testing.assert_allclose(result.vertices, expected_vertices)\n np.testing.assert_array_equal(result.codes, expected_codes)\n\n # Usually closepoly is the last vertex but does not have to be.\n codes += [Path.LINETO]\n vertices += [(2, 1)]\n\n path = Path(vertices, codes)\n result = path.interpolated(2)\n\n extra_expected_vertices = np.array([[3, 2],\n [2, 1]])\n expected_vertices = np.concatenate([expected_vertices, extra_expected_vertices])\n\n expected_codes += [Path.LINETO] * 2\n\n np.testing.assert_allclose(result.vertices, expected_vertices)\n np.testing.assert_array_equal(result.codes, expected_codes)\n\n\ndef test_interpolated_moveto_closepoly():\n # Initial path has two closed subpaths\n codes = ([Path.MOVETO] + [Path.LINETO]*2 + [Path.CLOSEPOLY]) * 2\n vertices = [(4, 3), (5, 4), (5, 3), (0, 0), (8, 6), (10, 8), (10, 6), (0, 0)]\n\n path = Path(vertices, codes)\n result = path.interpolated(2)\n\n expected_vertices1 = np.array([[4, 3],\n [4.5, 3.5],\n [5, 4],\n [5, 3.5],\n [5, 3],\n [4.5, 3],\n [4, 3]])\n expected_vertices = np.concatenate([expected_vertices1, expected_vertices1 * 2])\n expected_codes = ([Path.MOVETO] + [Path.LINETO]*5 + [Path.CLOSEPOLY]) * 2\n\n np.testing.assert_allclose(result.vertices, expected_vertices)\n np.testing.assert_array_equal(result.codes, expected_codes)\n\n\ndef test_interpolated_empty_path():\n path = Path(np.zeros((0, 2)))\n assert path.interpolated(42) is path\n | .venv\Lib\site-packages\matplotlib\tests\test_path.py | test_path.py | Python | 22,158 | 0.95 | 0.084936 | 0.114919 | python-kit | 596 | 2025-03-01T03:57:10.594823 | BSD-3-Clause | true | d0865d26db537181a88c68962683a605 |
import platform\n\nimport numpy as np\n\nfrom matplotlib.testing.decorators import image_comparison\nimport matplotlib.pyplot as plt\nimport matplotlib.patheffects as path_effects\nfrom matplotlib.path import Path\nimport matplotlib.patches as patches\nfrom matplotlib.backend_bases import RendererBase\nfrom matplotlib.patheffects import PathEffectRenderer\n\n\n@image_comparison(['patheffect1'], remove_text=True)\ndef test_patheffect1():\n ax1 = plt.subplot()\n ax1.imshow([[1, 2], [2, 3]])\n txt = ax1.annotate("test", (1., 1.), (0., 0),\n arrowprops=dict(arrowstyle="->",\n connectionstyle="angle3", lw=2),\n size=20, ha="center",\n path_effects=[path_effects.withStroke(linewidth=3,\n foreground="w")])\n txt.arrow_patch.set_path_effects([path_effects.Stroke(linewidth=5,\n foreground="w"),\n path_effects.Normal()])\n\n pe = [path_effects.withStroke(linewidth=3, foreground="w")]\n ax1.grid(True, linestyle="-", path_effects=pe)\n\n\n@image_comparison(['patheffect2'], remove_text=True, style='mpl20',\n tol=0 if platform.machine() == 'x86_64' else 0.06)\ndef test_patheffect2():\n\n ax2 = plt.subplot()\n arr = np.arange(25).reshape((5, 5))\n ax2.imshow(arr, interpolation='nearest')\n cntr = ax2.contour(arr, colors="k")\n cntr.set(path_effects=[path_effects.withStroke(linewidth=3, foreground="w")])\n\n clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)\n plt.setp(clbls,\n path_effects=[path_effects.withStroke(linewidth=3,\n foreground="w")])\n\n\n@image_comparison(['patheffect3'],\n tol=0 if platform.machine() == 'x86_64' else 0.019)\ndef test_patheffect3():\n p1, = plt.plot([1, 3, 5, 4, 3], 'o-b', lw=4)\n p1.set_path_effects([path_effects.SimpleLineShadow(),\n path_effects.Normal()])\n plt.title(\n r'testing$^{123}$',\n path_effects=[path_effects.withStroke(linewidth=1, foreground="r")])\n leg = plt.legend([p1], [r'Line 1$^2$'], fancybox=True, loc='upper left')\n leg.legendPatch.set_path_effects([path_effects.withSimplePatchShadow()])\n\n text = plt.text(2, 3, 'Drop test', color='white',\n bbox={'boxstyle': 'circle,pad=0.1', 'color': 'red'})\n pe = [path_effects.Stroke(linewidth=3.75, foreground='k'),\n path_effects.withSimplePatchShadow((6, -3), shadow_rgbFace='blue')]\n text.set_path_effects(pe)\n text.get_bbox_patch().set_path_effects(pe)\n\n pe = [path_effects.PathPatchEffect(offset=(4, -4), hatch='xxxx',\n facecolor='gray'),\n path_effects.PathPatchEffect(edgecolor='white', facecolor='black',\n lw=1.1)]\n\n t = plt.gcf().text(0.02, 0.1, 'Hatch shadow', fontsize=75, weight=1000,\n va='center')\n t.set_path_effects(pe)\n\n\n@image_comparison(['stroked_text.png'])\ndef test_patheffects_stroked_text():\n text_chunks = [\n 'A B C D E F G H I J K L',\n 'M N O P Q R S T U V W',\n 'X Y Z a b c d e f g h i j',\n 'k l m n o p q r s t u v',\n 'w x y z 0123456789',\n r"!@#$%^&*()-=_+[]\;'",\n ',./{}|:"<>?'\n ]\n font_size = 50\n\n ax = plt.axes((0, 0, 1, 1))\n for i, chunk in enumerate(text_chunks):\n text = ax.text(x=0.01, y=(0.9 - i * 0.13), s=chunk,\n fontdict={'ha': 'left', 'va': 'center',\n 'size': font_size, 'color': 'white'})\n\n text.set_path_effects([path_effects.Stroke(linewidth=font_size / 10,\n foreground='black'),\n path_effects.Normal()])\n\n ax.set_xlim(0, 1)\n ax.set_ylim(0, 1)\n ax.axis('off')\n\n\ndef test_PathEffect_points_to_pixels():\n fig = plt.figure(dpi=150)\n p1, = plt.plot(range(10))\n p1.set_path_effects([path_effects.SimpleLineShadow(),\n path_effects.Normal()])\n renderer = fig.canvas.get_renderer()\n pe_renderer = path_effects.PathEffectRenderer(\n p1.get_path_effects(), renderer)\n # Confirm that using a path effects renderer maintains point sizes\n # appropriately. Otherwise rendered font would be the wrong size.\n assert renderer.points_to_pixels(15) == pe_renderer.points_to_pixels(15)\n\n\ndef test_SimplePatchShadow_offset():\n pe = path_effects.SimplePatchShadow(offset=(4, 5))\n assert pe._offset == (4, 5)\n\n\n@image_comparison(['collection'], tol=0.03, style='mpl20')\ndef test_collection():\n x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100))\n data = np.sin(x) + np.cos(y)\n cs = plt.contour(data)\n cs.set(path_effects=[\n path_effects.PathPatchEffect(edgecolor='black', facecolor='none', linewidth=12),\n path_effects.Stroke(linewidth=5)])\n for text in plt.clabel(cs, colors='white'):\n text.set_path_effects([path_effects.withStroke(foreground='k',\n linewidth=3)])\n text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none',\n 'edgecolor': 'blue'})\n\n\n@image_comparison(['tickedstroke'], remove_text=True, extensions=['png'],\n tol=0.22) # Increased tolerance due to fixed clipping.\ndef test_tickedstroke():\n fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(12, 4))\n path = Path.unit_circle()\n patch = patches.PathPatch(path, facecolor='none', lw=2, path_effects=[\n path_effects.withTickedStroke(angle=-90, spacing=10,\n length=1)])\n\n ax1.add_patch(patch)\n ax1.axis('equal')\n ax1.set_xlim(-2, 2)\n ax1.set_ylim(-2, 2)\n\n ax2.plot([0, 1], [0, 1], label=' ',\n path_effects=[path_effects.withTickedStroke(spacing=7,\n angle=135)])\n nx = 101\n x = np.linspace(0.0, 1.0, nx)\n y = 0.3 * np.sin(x * 8) + 0.4\n ax2.plot(x, y, label=' ', path_effects=[path_effects.withTickedStroke()])\n\n ax2.legend()\n\n nx = 101\n ny = 105\n\n # Set up survey vectors\n xvec = np.linspace(0.001, 4.0, nx)\n yvec = np.linspace(0.001, 4.0, ny)\n\n # Set up survey matrices. Design disk loading and gear ratio.\n x1, x2 = np.meshgrid(xvec, yvec)\n\n # Evaluate some stuff to plot\n g1 = -(3 * x1 + x2 - 5.5)\n g2 = -(x1 + 2 * x2 - 4)\n g3 = .8 + x1 ** -3 - x2\n\n cg1 = ax3.contour(x1, x2, g1, [0], colors=('k',))\n cg1.set(path_effects=[path_effects.withTickedStroke(angle=135)])\n\n cg2 = ax3.contour(x1, x2, g2, [0], colors=('r',))\n cg2.set(path_effects=[path_effects.withTickedStroke(angle=60, length=2)])\n\n cg3 = ax3.contour(x1, x2, g3, [0], colors=('b',))\n cg3.set(path_effects=[path_effects.withTickedStroke(spacing=7)])\n\n ax3.set_xlim(0, 4)\n ax3.set_ylim(0, 4)\n\n\n@image_comparison(['spaces_and_newlines.png'], remove_text=True)\ndef test_patheffects_spaces_and_newlines():\n ax = plt.subplot()\n s1 = " "\n s2 = "\nNewline also causes problems"\n text1 = ax.text(0.5, 0.75, s1, ha='center', va='center', size=20,\n bbox={'color': 'salmon'})\n text2 = ax.text(0.5, 0.25, s2, ha='center', va='center', size=20,\n bbox={'color': 'thistle'})\n text1.set_path_effects([path_effects.Normal()])\n text2.set_path_effects([path_effects.Normal()])\n\n\ndef test_patheffects_overridden_methods_open_close_group():\n class CustomRenderer(RendererBase):\n def __init__(self):\n super().__init__()\n\n def open_group(self, s, gid=None):\n return "open_group overridden"\n\n def close_group(self, s):\n return "close_group overridden"\n\n renderer = PathEffectRenderer([path_effects.Normal()], CustomRenderer())\n\n assert renderer.open_group('s') == "open_group overridden"\n assert renderer.close_group('s') == "close_group overridden"\n | .venv\Lib\site-packages\matplotlib\tests\test_patheffects.py | test_patheffects.py | Python | 8,109 | 0.95 | 0.082949 | 0.02924 | node-utils | 894 | 2024-07-13T01:51:56.984462 | MIT | true | a2369a3bf1fc5bd3d06762f3659d2ce4 |
from io import BytesIO\nimport ast\nimport os\nimport sys\nimport pickle\nimport pickletools\n\nimport numpy as np\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib import cm\nfrom matplotlib.testing import subprocess_run_helper, is_ci_environment\nfrom matplotlib.testing.decorators import check_figures_equal\nfrom matplotlib.dates import rrulewrapper\nfrom matplotlib.lines import VertexSelector\nimport matplotlib.pyplot as plt\nimport matplotlib.transforms as mtransforms\nimport matplotlib.figure as mfigure\nfrom mpl_toolkits.axes_grid1 import axes_divider, parasite_axes # type: ignore[import]\n\n\ndef test_simple():\n fig = plt.figure()\n pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)\n\n ax = plt.subplot(121)\n pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)\n\n ax = plt.axes(projection='polar')\n plt.plot(np.arange(10), label='foobar')\n plt.legend()\n\n pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)\n\n# ax = plt.subplot(121, projection='hammer')\n# pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)\n\n plt.figure()\n plt.bar(x=np.arange(10), height=np.arange(10))\n pickle.dump(plt.gca(), BytesIO(), pickle.HIGHEST_PROTOCOL)\n\n fig = plt.figure()\n ax = plt.axes()\n plt.plot(np.arange(10))\n ax.set_yscale('log')\n pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)\n\n\ndef _generate_complete_test_figure(fig_ref):\n fig_ref.set_size_inches((10, 6))\n plt.figure(fig_ref)\n\n plt.suptitle('Can you fit any more in a figure?')\n\n # make some arbitrary data\n x, y = np.arange(8), np.arange(10)\n data = u = v = np.linspace(0, 10, 80).reshape(10, 8)\n v = np.sin(v * -0.6)\n\n # Ensure lists also pickle correctly.\n plt.subplot(3, 3, 1)\n plt.plot(list(range(10)))\n plt.ylabel("hello")\n\n plt.subplot(3, 3, 2)\n plt.contourf(data, hatches=['//', 'ooo'])\n plt.colorbar()\n\n plt.subplot(3, 3, 3)\n plt.pcolormesh(data)\n\n plt.subplot(3, 3, 4)\n plt.imshow(data)\n plt.ylabel("hello\nworld!")\n\n plt.subplot(3, 3, 5)\n plt.pcolor(data)\n\n ax = plt.subplot(3, 3, 6)\n ax.set_xlim(0, 7)\n ax.set_ylim(0, 9)\n plt.streamplot(x, y, u, v)\n\n ax = plt.subplot(3, 3, 7)\n ax.set_xlim(0, 7)\n ax.set_ylim(0, 9)\n plt.quiver(x, y, u, v)\n\n plt.subplot(3, 3, 8)\n plt.scatter(x, x ** 2, label='$x^2$')\n plt.legend(loc='upper left')\n\n plt.subplot(3, 3, 9)\n plt.errorbar(x, x * -0.5, xerr=0.2, yerr=0.4, label='$-.5 x$')\n plt.legend(draggable=True)\n\n # Ensure subfigure parenting works.\n subfigs = fig_ref.subfigures(2)\n subfigs[0].subplots(1, 2)\n subfigs[1].subplots(1, 2)\n\n fig_ref.align_ylabels() # Test handling of _align_label_groups Groupers.\n\n\n@mpl.style.context("default")\n@check_figures_equal(extensions=["png"])\ndef test_complete(fig_test, fig_ref):\n _generate_complete_test_figure(fig_ref)\n # plotting is done, now test its pickle-ability\n pkl = pickle.dumps(fig_ref, pickle.HIGHEST_PROTOCOL)\n # FigureCanvasAgg is picklable and GUI canvases are generally not, but there should\n # be no reference to the canvas in the pickle stream in either case. In order to\n # keep the test independent of GUI toolkits, run it with Agg and check that there's\n # no reference to FigureCanvasAgg in the pickle stream.\n assert "FigureCanvasAgg" not in [arg for op, arg, pos in pickletools.genops(pkl)]\n loaded = pickle.loads(pkl)\n loaded.canvas.draw()\n\n fig_test.set_size_inches(loaded.get_size_inches())\n fig_test.figimage(loaded.canvas.renderer.buffer_rgba())\n\n plt.close(loaded)\n\n\ndef _pickle_load_subprocess():\n import os\n import pickle\n\n path = os.environ['PICKLE_FILE_PATH']\n\n with open(path, 'rb') as blob:\n fig = pickle.load(blob)\n\n print(str(pickle.dumps(fig)))\n\n\n@mpl.style.context("default")\n@check_figures_equal(extensions=['png'])\ndef test_pickle_load_from_subprocess(fig_test, fig_ref, tmp_path):\n _generate_complete_test_figure(fig_ref)\n\n fp = tmp_path / 'sinus.pickle'\n assert not fp.exists()\n\n with fp.open('wb') as file:\n pickle.dump(fig_ref, file, pickle.HIGHEST_PROTOCOL)\n assert fp.exists()\n\n proc = subprocess_run_helper(\n _pickle_load_subprocess,\n timeout=60,\n extra_env={\n "PICKLE_FILE_PATH": str(fp),\n "MPLBACKEND": "Agg",\n # subprocess_run_helper will set SOURCE_DATE_EPOCH=0, so for a dirty tree,\n # the version will have the date 19700101. As we aren't trying to test the\n # version compatibility warning, force setuptools-scm to use the same\n # version as us.\n "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_MATPLOTLIB": mpl.__version__,\n },\n )\n\n loaded_fig = pickle.loads(ast.literal_eval(proc.stdout))\n\n loaded_fig.canvas.draw()\n\n fig_test.set_size_inches(loaded_fig.get_size_inches())\n fig_test.figimage(loaded_fig.canvas.renderer.buffer_rgba())\n\n plt.close(loaded_fig)\n\n\ndef test_gcf():\n fig = plt.figure("a label")\n buf = BytesIO()\n pickle.dump(fig, buf, pickle.HIGHEST_PROTOCOL)\n plt.close("all")\n assert plt._pylab_helpers.Gcf.figs == {} # No figures must be left.\n fig = pickle.loads(buf.getbuffer())\n assert plt._pylab_helpers.Gcf.figs != {} # A manager is there again.\n assert fig.get_label() == "a label"\n\n\ndef test_no_pyplot():\n # tests pickle-ability of a figure not created with pyplot\n from matplotlib.backends.backend_pdf import FigureCanvasPdf\n fig = mfigure.Figure()\n _ = FigureCanvasPdf(fig)\n ax = fig.add_subplot(1, 1, 1)\n ax.plot([1, 2, 3], [1, 2, 3])\n pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)\n\n\ndef test_renderer():\n from matplotlib.backends.backend_agg import RendererAgg\n renderer = RendererAgg(10, 20, 30)\n pickle.dump(renderer, BytesIO())\n\n\ndef test_image():\n # Prior to v1.4.0 the Image would cache data which was not picklable\n # once it had been drawn.\n from matplotlib.backends.backend_agg import new_figure_manager\n manager = new_figure_manager(1000)\n fig = manager.canvas.figure\n ax = fig.add_subplot(1, 1, 1)\n ax.imshow(np.arange(12).reshape(3, 4))\n manager.canvas.draw()\n pickle.dump(fig, BytesIO())\n\n\ndef test_polar():\n plt.subplot(polar=True)\n fig = plt.gcf()\n pf = pickle.dumps(fig)\n pickle.loads(pf)\n plt.draw()\n\n\nclass TransformBlob:\n def __init__(self):\n self.identity = mtransforms.IdentityTransform()\n self.identity2 = mtransforms.IdentityTransform()\n # Force use of the more complex composition.\n self.composite = mtransforms.CompositeGenericTransform(\n self.identity,\n self.identity2)\n # Check parent -> child links of TransformWrapper.\n self.wrapper = mtransforms.TransformWrapper(self.composite)\n # Check child -> parent links of TransformWrapper.\n self.composite2 = mtransforms.CompositeGenericTransform(\n self.wrapper,\n self.identity)\n\n\ndef test_transform():\n obj = TransformBlob()\n pf = pickle.dumps(obj)\n del obj\n\n obj = pickle.loads(pf)\n # Check parent -> child links of TransformWrapper.\n assert obj.wrapper._child == obj.composite\n # Check child -> parent links of TransformWrapper.\n assert [v() for v in obj.wrapper._parents.values()] == [obj.composite2]\n # Check input and output dimensions are set as expected.\n assert obj.wrapper.input_dims == obj.composite.input_dims\n assert obj.wrapper.output_dims == obj.composite.output_dims\n\n\ndef test_rrulewrapper():\n r = rrulewrapper(2)\n try:\n pickle.loads(pickle.dumps(r))\n except RecursionError:\n print('rrulewrapper pickling test failed')\n raise\n\n\ndef test_shared():\n fig, axs = plt.subplots(2, sharex=True)\n fig = pickle.loads(pickle.dumps(fig))\n fig.axes[0].set_xlim(10, 20)\n assert fig.axes[1].get_xlim() == (10, 20)\n\n\ndef test_inset_and_secondary():\n fig, ax = plt.subplots()\n ax.inset_axes([.1, .1, .3, .3])\n ax.secondary_xaxis("top", functions=(np.square, np.sqrt))\n pickle.loads(pickle.dumps(fig))\n\n\n@pytest.mark.parametrize("cmap", cm._colormaps.values())\ndef test_cmap(cmap):\n pickle.dumps(cmap)\n\n\ndef test_unpickle_canvas():\n fig = mfigure.Figure()\n assert fig.canvas is not None\n out = BytesIO()\n pickle.dump(fig, out)\n out.seek(0)\n fig2 = pickle.load(out)\n assert fig2.canvas is not None\n\n\ndef test_mpl_toolkits():\n ax = parasite_axes.host_axes([0, 0, 1, 1])\n axes_divider.make_axes_area_auto_adjustable(ax)\n assert type(pickle.loads(pickle.dumps(ax))) == parasite_axes.HostAxes\n\n\ndef test_standard_norm():\n assert type(pickle.loads(pickle.dumps(mpl.colors.LogNorm()))) \\n == mpl.colors.LogNorm\n\n\ndef test_dynamic_norm():\n logit_norm_instance = mpl.colors.make_norm_from_scale(\n mpl.scale.LogitScale, mpl.colors.Normalize)()\n assert type(pickle.loads(pickle.dumps(logit_norm_instance))) \\n == type(logit_norm_instance)\n\n\ndef test_vertexselector():\n line, = plt.plot([0, 1], picker=True)\n pickle.loads(pickle.dumps(VertexSelector(line)))\n\n\ndef test_cycler():\n ax = plt.figure().add_subplot()\n ax.set_prop_cycle(c=["c", "m", "y", "k"])\n ax.plot([1, 2])\n ax = pickle.loads(pickle.dumps(ax))\n l, = ax.plot([3, 4])\n assert l.get_color() == "m"\n\n\n# Run under an interactive backend to test that we don't try to pickle the\n# (interactive and non-picklable) canvas.\ndef _test_axeswidget_interactive():\n ax = plt.figure().add_subplot()\n pickle.dumps(mpl.widgets.Button(ax, "button"))\n\n\n@pytest.mark.xfail( # https://github.com/actions/setup-python/issues/649\n ('TF_BUILD' in os.environ or 'GITHUB_ACTION' in os.environ) and\n sys.platform == 'darwin' and sys.version_info[:2] < (3, 11),\n reason='Tk version mismatch on Azure macOS CI'\n )\ndef test_axeswidget_interactive():\n subprocess_run_helper(\n _test_axeswidget_interactive,\n timeout=120 if is_ci_environment() else 20,\n extra_env={'MPLBACKEND': 'tkagg'}\n )\n | .venv\Lib\site-packages\matplotlib\tests\test_pickle.py | test_pickle.py | Python | 10,014 | 0.95 | 0.091445 | 0.097276 | vue-tools | 977 | 2023-11-06T06:56:29.854208 | GPL-3.0 | true | 04287b0cedecfab98e36f93a09fc4b5a |
from io import BytesIO\nfrom pathlib import Path\n\nimport pytest\n\nfrom matplotlib.testing.decorators import image_comparison\nfrom matplotlib import cm, pyplot as plt\n\n\n@image_comparison(['pngsuite.png'], tol=0.04)\ndef test_pngsuite():\n files = sorted(\n (Path(__file__).parent / "baseline_images/pngsuite").glob("basn*.png"))\n\n plt.figure(figsize=(len(files), 2))\n\n for i, fname in enumerate(files):\n data = plt.imread(fname)\n cmap = None # use default colormap\n if data.ndim == 2:\n # keep grayscale images gray\n cmap = cm.gray\n # Using the old default data interpolation stage lets us\n # continue to use the existing reference image\n plt.imshow(data, extent=(i, i + 1, 0, 1), cmap=cmap,\n interpolation_stage='data')\n\n plt.gca().patch.set_facecolor("#ddffff")\n plt.gca().set_xlim(0, len(files))\n\n\ndef test_truncated_file(tmp_path):\n path = tmp_path / 'test.png'\n path_t = tmp_path / 'test_truncated.png'\n plt.savefig(path)\n with open(path, 'rb') as fin:\n buf = fin.read()\n with open(path_t, 'wb') as fout:\n fout.write(buf[:20])\n\n with pytest.raises(Exception):\n plt.imread(path_t)\n\n\ndef test_truncated_buffer():\n b = BytesIO()\n plt.savefig(b)\n b.seek(0)\n b2 = BytesIO(b.read(20))\n b2.seek(0)\n\n with pytest.raises(Exception):\n plt.imread(b2)\n | .venv\Lib\site-packages\matplotlib\tests\test_png.py | test_png.py | Python | 1,407 | 0.95 | 0.09434 | 0.075 | react-lib | 534 | 2025-05-29T23:41:57.438555 | BSD-3-Clause | true | 7c9f0aa11e4e477d259b059a3b4b46da |
import numpy as np\nfrom numpy.testing import assert_allclose\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nfrom matplotlib.testing.decorators import image_comparison, check_figures_equal\n\n\n@image_comparison(['polar_axes.png'], style='default', tol=0.012)\ndef test_polar_annotations():\n # You can specify the xypoint and the xytext in different positions and\n # coordinate systems, and optionally turn on a connecting line and mark the\n # point with a marker. Annotations work on polar axes too. In the example\n # below, the xy point is in native coordinates (xycoords defaults to\n # 'data'). For a polar axes, this is in (theta, radius) space. The text\n # in this example is placed in the fractional figure coordinate system.\n # Text keyword args like horizontal and vertical alignment are respected.\n\n # Setup some data\n r = np.arange(0.0, 1.0, 0.001)\n theta = 2.0 * 2.0 * np.pi * r\n\n fig = plt.figure()\n ax = fig.add_subplot(polar=True)\n line, = ax.plot(theta, r, color='#ee8d18', lw=3)\n line, = ax.plot((0, 0), (0, 1), color="#0000ff", lw=1)\n\n ind = 800\n thisr, thistheta = r[ind], theta[ind]\n ax.plot([thistheta], [thisr], 'o')\n ax.annotate('a polar annotation',\n xy=(thistheta, thisr), # theta, radius\n xytext=(0.05, 0.05), # fraction, fraction\n textcoords='figure fraction',\n arrowprops=dict(facecolor='black', shrink=0.05),\n horizontalalignment='left',\n verticalalignment='baseline',\n )\n\n ax.tick_params(axis='x', tick1On=True, tick2On=True, direction='out')\n\n\n@image_comparison(['polar_coords.png'], style='default', remove_text=True,\n tol=0.014)\ndef test_polar_coord_annotations():\n # You can also use polar notation on a cartesian axes. Here the native\n # coordinate system ('data') is cartesian, so you need to specify the\n # xycoords and textcoords as 'polar' if you want to use (theta, radius).\n el = mpl.patches.Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5)\n\n fig = plt.figure()\n ax = fig.add_subplot(aspect='equal')\n\n ax.add_artist(el)\n el.set_clip_box(ax.bbox)\n\n ax.annotate('the top',\n xy=(np.pi/2., 10.), # theta, radius\n xytext=(np.pi/3, 20.), # theta, radius\n xycoords='polar',\n textcoords='polar',\n arrowprops=dict(facecolor='black', shrink=0.05),\n horizontalalignment='left',\n verticalalignment='baseline',\n clip_on=True, # clip to the axes bounding box\n )\n\n ax.set_xlim(-20, 20)\n ax.set_ylim(-20, 20)\n\n\n@image_comparison(['polar_alignment.png'])\ndef test_polar_alignment():\n # Test changing the vertical/horizontal alignment of a polar graph.\n angles = np.arange(0, 360, 90)\n grid_values = [0, 0.2, 0.4, 0.6, 0.8, 1]\n\n fig = plt.figure()\n rect = [0.1, 0.1, 0.8, 0.8]\n\n horizontal = fig.add_axes(rect, polar=True, label='horizontal')\n horizontal.set_thetagrids(angles)\n\n vertical = fig.add_axes(rect, polar=True, label='vertical')\n vertical.patch.set_visible(False)\n\n for i in range(2):\n fig.axes[i].set_rgrids(\n grid_values, angle=angles[i],\n horizontalalignment='left', verticalalignment='top')\n\n\ndef test_polar_twice():\n fig = plt.figure()\n plt.polar([1, 2], [.1, .2])\n plt.polar([3, 4], [.3, .4])\n assert len(fig.axes) == 1, 'More than one polar Axes created.'\n\n\n@check_figures_equal(extensions=['png'])\ndef test_polar_wrap(fig_test, fig_ref):\n ax = fig_test.add_subplot(projection="polar")\n ax.plot(np.deg2rad([179, -179]), [0.2, 0.1])\n ax.plot(np.deg2rad([2, -2]), [0.2, 0.1])\n ax = fig_ref.add_subplot(projection="polar")\n ax.plot(np.deg2rad([179, 181]), [0.2, 0.1])\n ax.plot(np.deg2rad([2, 358]), [0.2, 0.1])\n\n\n@check_figures_equal(extensions=['png'])\ndef test_polar_units_1(fig_test, fig_ref):\n import matplotlib.testing.jpl_units as units\n units.register()\n xs = [30.0, 45.0, 60.0, 90.0]\n ys = [1.0, 2.0, 3.0, 4.0]\n\n plt.figure(fig_test.number)\n plt.polar([x * units.deg for x in xs], ys)\n\n ax = fig_ref.add_subplot(projection="polar")\n ax.plot(np.deg2rad(xs), ys)\n ax.set(xlabel="deg")\n\n\n@check_figures_equal(extensions=['png'])\ndef test_polar_units_2(fig_test, fig_ref):\n import matplotlib.testing.jpl_units as units\n units.register()\n xs = [30.0, 45.0, 60.0, 90.0]\n xs_deg = [x * units.deg for x in xs]\n ys = [1.0, 2.0, 3.0, 4.0]\n ys_km = [y * units.km for y in ys]\n\n plt.figure(fig_test.number)\n # test {theta,r}units.\n plt.polar(xs_deg, ys_km, thetaunits="rad", runits="km")\n assert isinstance(plt.gca().xaxis.get_major_formatter(),\n units.UnitDblFormatter)\n\n ax = fig_ref.add_subplot(projection="polar")\n ax.plot(np.deg2rad(xs), ys)\n ax.xaxis.set_major_formatter(mpl.ticker.FuncFormatter("{:.12}".format))\n ax.set(xlabel="rad", ylabel="km")\n\n\n@image_comparison(['polar_rmin.png'], style='default')\ndef test_polar_rmin():\n r = np.arange(0, 3.0, 0.01)\n theta = 2*np.pi*r\n\n fig = plt.figure()\n ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)\n ax.plot(theta, r)\n ax.set_rmax(2.0)\n ax.set_rmin(0.5)\n\n\n@image_comparison(['polar_negative_rmin.png'], style='default')\ndef test_polar_negative_rmin():\n r = np.arange(-3.0, 0.0, 0.01)\n theta = 2*np.pi*r\n\n fig = plt.figure()\n ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)\n ax.plot(theta, r)\n ax.set_rmax(0.0)\n ax.set_rmin(-3.0)\n\n\n@image_comparison(['polar_rorigin.png'], style='default')\ndef test_polar_rorigin():\n r = np.arange(0, 3.0, 0.01)\n theta = 2*np.pi*r\n\n fig = plt.figure()\n ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)\n ax.plot(theta, r)\n ax.set_rmax(2.0)\n ax.set_rmin(0.5)\n ax.set_rorigin(0.0)\n\n\n@image_comparison(['polar_invertedylim.png'], style='default')\ndef test_polar_invertedylim():\n fig = plt.figure()\n ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)\n ax.set_ylim(2, 0)\n\n\n@image_comparison(['polar_invertedylim_rorigin.png'], style='default')\ndef test_polar_invertedylim_rorigin():\n fig = plt.figure()\n ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)\n ax.yaxis.set_inverted(True)\n # Set the rlims to inverted (2, 0) without calling set_rlim, to check that\n # viewlims are correctly unstaled before draw()ing.\n ax.plot([0, 0], [0, 2], c="none")\n ax.margins(0)\n ax.set_rorigin(3)\n\n\n@image_comparison(['polar_theta_position.png'], style='default')\ndef test_polar_theta_position():\n r = np.arange(0, 3.0, 0.01)\n theta = 2*np.pi*r\n\n fig = plt.figure()\n ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)\n ax.plot(theta, r)\n ax.set_theta_zero_location("NW", 30)\n ax.set_theta_direction('clockwise')\n\n\n@image_comparison(['polar_rlabel_position.png'], style='default')\ndef test_polar_rlabel_position():\n fig = plt.figure()\n ax = fig.add_subplot(projection='polar')\n ax.set_rlabel_position(315)\n ax.tick_params(rotation='auto')\n\n\n@image_comparison(['polar_title_position.png'], style='mpl20')\ndef test_polar_title_position():\n fig = plt.figure()\n ax = fig.add_subplot(projection='polar')\n ax.set_title('foo')\n\n\n@image_comparison(['polar_theta_wedge.png'], style='default')\ndef test_polar_theta_limits():\n r = np.arange(0, 3.0, 0.01)\n theta = 2*np.pi*r\n\n theta_mins = np.arange(15.0, 361.0, 90.0)\n theta_maxs = np.arange(50.0, 361.0, 90.0)\n DIRECTIONS = ('out', 'in', 'inout')\n\n fig, axs = plt.subplots(len(theta_mins), len(theta_maxs),\n subplot_kw={'polar': True},\n figsize=(8, 6))\n\n for i, start in enumerate(theta_mins):\n for j, end in enumerate(theta_maxs):\n ax = axs[i, j]\n ax.plot(theta, r)\n if start < end:\n ax.set_thetamin(start)\n ax.set_thetamax(end)\n else:\n # Plot with clockwise orientation instead.\n ax.set_thetamin(end)\n ax.set_thetamax(start)\n ax.set_theta_direction('clockwise')\n ax.tick_params(tick1On=True, tick2On=True,\n direction=DIRECTIONS[i % len(DIRECTIONS)],\n rotation='auto')\n ax.yaxis.set_tick_params(label2On=True, rotation='auto')\n ax.xaxis.get_major_locator().base.set_params( # backcompat\n steps=[1, 2, 2.5, 5, 10])\n\n\n@check_figures_equal(extensions=["png"])\ndef test_polar_rlim(fig_test, fig_ref):\n ax = fig_test.subplots(subplot_kw={'polar': True})\n ax.set_rlim(top=10)\n ax.set_rlim(bottom=.5)\n\n ax = fig_ref.subplots(subplot_kw={'polar': True})\n ax.set_rmax(10.)\n ax.set_rmin(.5)\n\n\n@check_figures_equal(extensions=["png"])\ndef test_polar_rlim_bottom(fig_test, fig_ref):\n ax = fig_test.subplots(subplot_kw={'polar': True})\n ax.set_rlim(bottom=[.5, 10])\n\n ax = fig_ref.subplots(subplot_kw={'polar': True})\n ax.set_rmax(10.)\n ax.set_rmin(.5)\n\n\ndef test_polar_rlim_zero():\n ax = plt.figure().add_subplot(projection='polar')\n ax.plot(np.arange(10), np.arange(10) + .01)\n assert ax.get_ylim()[0] == 0\n\n\ndef test_polar_no_data():\n plt.subplot(projection="polar")\n ax = plt.gca()\n assert ax.get_rmin() == 0 and ax.get_rmax() == 1\n plt.close("all")\n # Used to behave differently (by triggering an autoscale with no data).\n plt.polar()\n ax = plt.gca()\n assert ax.get_rmin() == 0 and ax.get_rmax() == 1\n\n\ndef test_polar_default_log_lims():\n plt.subplot(projection='polar')\n ax = plt.gca()\n ax.set_rscale('log')\n assert ax.get_rmin() > 0\n\n\ndef test_polar_not_datalim_adjustable():\n ax = plt.figure().add_subplot(projection="polar")\n with pytest.raises(ValueError):\n ax.set_adjustable("datalim")\n\n\ndef test_polar_gridlines():\n fig = plt.figure()\n ax = fig.add_subplot(polar=True)\n # make all major grid lines lighter, only x grid lines set in 2.1.0\n ax.grid(alpha=0.2)\n # hide y tick labels, no effect in 2.1.0\n plt.setp(ax.yaxis.get_ticklabels(), visible=False)\n fig.canvas.draw()\n assert ax.xaxis.majorTicks[0].gridline.get_alpha() == .2\n assert ax.yaxis.majorTicks[0].gridline.get_alpha() == .2\n\n\ndef test_get_tightbbox_polar():\n fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})\n fig.canvas.draw()\n bb = ax.get_tightbbox(fig.canvas.get_renderer())\n assert_allclose(\n bb.extents, [107.7778, 29.2778, 539.7847, 450.7222], rtol=1e-03)\n\n\n@check_figures_equal(extensions=["png"])\ndef test_polar_interpolation_steps_constant_r(fig_test, fig_ref):\n # Check that an extra half-turn doesn't make any difference -- modulo\n # antialiasing, which we disable here.\n p1 = (fig_test.add_subplot(121, projection="polar")\n .bar([0], [1], 3*np.pi, edgecolor="none", antialiased=False))\n p2 = (fig_test.add_subplot(122, projection="polar")\n .bar([0], [1], -3*np.pi, edgecolor="none", antialiased=False))\n p3 = (fig_ref.add_subplot(121, projection="polar")\n .bar([0], [1], 2*np.pi, edgecolor="none", antialiased=False))\n p4 = (fig_ref.add_subplot(122, projection="polar")\n .bar([0], [1], -2*np.pi, edgecolor="none", antialiased=False))\n\n\n@check_figures_equal(extensions=["png"])\ndef test_polar_interpolation_steps_variable_r(fig_test, fig_ref):\n l, = fig_test.add_subplot(projection="polar").plot([0, np.pi/2], [1, 2])\n l.get_path()._interpolation_steps = 100\n fig_ref.add_subplot(projection="polar").plot(\n np.linspace(0, np.pi/2, 101), np.linspace(1, 2, 101))\n\n\ndef test_thetalim_valid_invalid():\n ax = plt.subplot(projection='polar')\n ax.set_thetalim(0, 2 * np.pi) # doesn't raise.\n ax.set_thetalim(thetamin=800, thetamax=440) # doesn't raise.\n with pytest.raises(ValueError,\n match='angle range must be less than a full circle'):\n ax.set_thetalim(0, 3 * np.pi)\n with pytest.raises(ValueError,\n match='angle range must be less than a full circle'):\n ax.set_thetalim(thetamin=800, thetamax=400)\n\n\ndef test_thetalim_args():\n ax = plt.subplot(projection='polar')\n ax.set_thetalim(0, 1)\n assert tuple(np.radians((ax.get_thetamin(), ax.get_thetamax()))) == (0, 1)\n ax.set_thetalim((2, 3))\n assert tuple(np.radians((ax.get_thetamin(), ax.get_thetamax()))) == (2, 3)\n\n\ndef test_default_thetalocator():\n # Ideally we would check AAAABBC, but the smallest axes currently puts a\n # single tick at 150° because MaxNLocator doesn't have a way to accept 15°\n # while rejecting 150°.\n fig, axs = plt.subplot_mosaic(\n "AAAABB.", subplot_kw={"projection": "polar"})\n for ax in axs.values():\n ax.set_thetalim(0, np.pi)\n for ax in axs.values():\n ticklocs = np.degrees(ax.xaxis.get_majorticklocs()).tolist()\n assert pytest.approx(90) in ticklocs\n assert pytest.approx(100) not in ticklocs\n\n\ndef test_axvspan():\n ax = plt.subplot(projection="polar")\n span = ax.axvspan(0, np.pi/4)\n assert span.get_path()._interpolation_steps > 1\n\n\n@check_figures_equal(extensions=["png"])\ndef test_remove_shared_polar(fig_ref, fig_test):\n # Removing shared polar axes used to crash. Test removing them, keeping in\n # both cases just the lower left axes of a grid to avoid running into a\n # separate issue (now being fixed) of ticklabel visibility for shared axes.\n axs = fig_ref.subplots(\n 2, 2, sharex=True, subplot_kw={"projection": "polar"})\n for i in [0, 1, 3]:\n axs.flat[i].remove()\n axs = fig_test.subplots(\n 2, 2, sharey=True, subplot_kw={"projection": "polar"})\n for i in [0, 1, 3]:\n axs.flat[i].remove()\n\n\ndef test_shared_polar_keeps_ticklabels():\n fig, axs = plt.subplots(\n 2, 2, subplot_kw={"projection": "polar"}, sharex=True, sharey=True)\n fig.canvas.draw()\n assert axs[0, 1].xaxis.majorTicks[0].get_visible()\n assert axs[0, 1].yaxis.majorTicks[0].get_visible()\n fig, axs = plt.subplot_mosaic(\n "ab\ncd", subplot_kw={"projection": "polar"}, sharex=True, sharey=True)\n fig.canvas.draw()\n assert axs["b"].xaxis.majorTicks[0].get_visible()\n assert axs["b"].yaxis.majorTicks[0].get_visible()\n\n\ndef test_axvline_axvspan_do_not_modify_rlims():\n ax = plt.subplot(projection="polar")\n ax.axvspan(0, 1)\n ax.axvline(.5)\n ax.plot([.1, .2])\n assert ax.get_ylim() == (0, .2)\n\n\ndef test_cursor_precision():\n ax = plt.subplot(projection="polar")\n # Higher radii correspond to higher theta-precisions.\n assert ax.format_coord(0, 0.005) == "θ=0.0π (0°), r=0.005"\n assert ax.format_coord(0, .1) == "θ=0.00π (0°), r=0.100"\n assert ax.format_coord(0, 1) == "θ=0.000π (0.0°), r=1.000"\n assert ax.format_coord(1, 0.005) == "θ=0.3π (57°), r=0.005"\n assert ax.format_coord(1, .1) == "θ=0.32π (57°), r=0.100"\n assert ax.format_coord(1, 1) == "θ=0.318π (57.3°), r=1.000"\n assert ax.format_coord(2, 0.005) == "θ=0.6π (115°), r=0.005"\n assert ax.format_coord(2, .1) == "θ=0.64π (115°), r=0.100"\n assert ax.format_coord(2, 1) == "θ=0.637π (114.6°), r=1.000"\n\n\ndef test_custom_fmt_data():\n ax = plt.subplot(projection="polar")\n def millions(x):\n return '$%1.1fM' % (x*1e-6)\n\n # Test only x formatter\n ax.fmt_xdata = None\n ax.fmt_ydata = millions\n assert ax.format_coord(12, 2e7) == "θ=3.8197186342π (687.54935416°), r=$20.0M"\n assert ax.format_coord(1234, 2e6) == "θ=392.794399551π (70702.9919191°), r=$2.0M"\n assert ax.format_coord(3, 100) == "θ=0.95493π (171.887°), r=$0.0M"\n\n # Test only y formatter\n ax.fmt_xdata = millions\n ax.fmt_ydata = None\n assert ax.format_coord(2e5, 1) == "θ=$0.2M, r=1.000"\n assert ax.format_coord(1, .1) == "θ=$0.0M, r=0.100"\n assert ax.format_coord(1e6, 0.005) == "θ=$1.0M, r=0.005"\n\n # Test both x and y formatters\n ax.fmt_xdata = millions\n ax.fmt_ydata = millions\n assert ax.format_coord(2e6, 2e4*3e5) == "θ=$2.0M, r=$6000.0M"\n assert ax.format_coord(1e18, 12891328123) == "θ=$1000000000000.0M, r=$12891.3M"\n assert ax.format_coord(63**7, 1081968*1024) == "θ=$3938980.6M, r=$1107.9M"\n\n\n@image_comparison(['polar_log.png'], style='default')\ndef test_polar_log():\n fig = plt.figure()\n ax = fig.add_subplot(polar=True)\n\n ax.set_rscale('log')\n ax.set_rlim(1, 1000)\n\n n = 100\n ax.plot(np.linspace(0, 2 * np.pi, n), np.logspace(0, 2, n))\n\n\ndef test_polar_neg_theta_lims():\n fig = plt.figure()\n ax = fig.add_subplot(projection='polar')\n ax.set_thetalim(-np.pi, np.pi)\n labels = [l.get_text() for l in ax.xaxis.get_ticklabels()]\n assert labels == ['-180°', '-135°', '-90°', '-45°', '0°', '45°', '90°', '135°']\n\n\n@pytest.mark.parametrize("order", ["before", "after"])\n@image_comparison(baseline_images=['polar_errorbar.png'], remove_text=True,\n style='mpl20')\ndef test_polar_errorbar(order):\n theta = np.arange(0, 2 * np.pi, np.pi / 8)\n r = theta / np.pi / 2 + 0.5\n fig = plt.figure(figsize=(5, 5))\n ax = fig.add_subplot(projection='polar')\n if order == "before":\n ax.set_theta_zero_location("N")\n ax.set_theta_direction(-1)\n ax.errorbar(theta, r, xerr=0.1, yerr=0.1, capsize=7, fmt="o", c="seagreen")\n else:\n ax.errorbar(theta, r, xerr=0.1, yerr=0.1, capsize=7, fmt="o", c="seagreen")\n ax.set_theta_zero_location("N")\n ax.set_theta_direction(-1)\n | .venv\Lib\site-packages\matplotlib\tests\test_polar.py | test_polar.py | Python | 17,607 | 0.95 | 0.108268 | 0.077307 | python-kit | 49 | 2024-12-19T01:18:20.333512 | GPL-3.0 | true | a069d3c3d850035767fa2e5cf5e141c1 |
import re\nimport sys\n\nimport numpy as np\nimport pytest\n\nfrom matplotlib import _preprocess_data\nfrom matplotlib.axes import Axes\nfrom matplotlib.testing import subprocess_run_for_testing\nfrom matplotlib.testing.decorators import check_figures_equal\n\n# Notes on testing the plotting functions itself\n# * the individual decorated plotting functions are tested in 'test_axes.py'\n# * that pyplot functions accept a data kwarg is only tested in\n# test_axes.test_pie_linewidth_0\n\n\n# this gets used in multiple tests, so define it here\n@_preprocess_data(replace_names=["x", "y"], label_namer="y")\ndef plot_func(ax, x, y, ls="x", label=None, w="xyz"):\n return f"x: {list(x)}, y: {list(y)}, ls: {ls}, w: {w}, label: {label}"\n\n\nall_funcs = [plot_func]\nall_func_ids = ['plot_func']\n\n\ndef test_compiletime_checks():\n """Test decorator invocations -> no replacements."""\n\n def func(ax, x, y): pass\n def func_args(ax, x, y, *args): pass\n def func_kwargs(ax, x, y, **kwargs): pass\n def func_no_ax_args(*args, **kwargs): pass\n\n # this is ok\n _preprocess_data(replace_names=["x", "y"])(func)\n _preprocess_data(replace_names=["x", "y"])(func_kwargs)\n # this has "enough" information to do all the replaces\n _preprocess_data(replace_names=["x", "y"])(func_args)\n\n # no positional_parameter_names but needed due to replaces\n with pytest.raises(AssertionError):\n # z is unknown\n _preprocess_data(replace_names=["x", "y", "z"])(func_args)\n\n # no replacements at all -> all ok...\n _preprocess_data(replace_names=[], label_namer=None)(func)\n _preprocess_data(replace_names=[], label_namer=None)(func_args)\n _preprocess_data(replace_names=[], label_namer=None)(func_kwargs)\n _preprocess_data(replace_names=[], label_namer=None)(func_no_ax_args)\n\n # label namer is unknown\n with pytest.raises(AssertionError):\n _preprocess_data(label_namer="z")(func)\n\n with pytest.raises(AssertionError):\n _preprocess_data(label_namer="z")(func_args)\n\n\n@pytest.mark.parametrize('func', all_funcs, ids=all_func_ids)\ndef test_function_call_without_data(func):\n """Test without data -> no replacements."""\n assert (func(None, "x", "y") ==\n "x: ['x'], y: ['y'], ls: x, w: xyz, label: None")\n assert (func(None, x="x", y="y") ==\n "x: ['x'], y: ['y'], ls: x, w: xyz, label: None")\n assert (func(None, "x", "y", label="") ==\n "x: ['x'], y: ['y'], ls: x, w: xyz, label: ")\n assert (func(None, "x", "y", label="text") ==\n "x: ['x'], y: ['y'], ls: x, w: xyz, label: text")\n assert (func(None, x="x", y="y", label="") ==\n "x: ['x'], y: ['y'], ls: x, w: xyz, label: ")\n assert (func(None, x="x", y="y", label="text") ==\n "x: ['x'], y: ['y'], ls: x, w: xyz, label: text")\n\n\n@pytest.mark.parametrize('func', all_funcs, ids=all_func_ids)\ndef test_function_call_with_dict_input(func):\n """Tests with dict input, unpacking via preprocess_pipeline"""\n data = {'a': 1, 'b': 2}\n assert (func(None, data.keys(), data.values()) ==\n "x: ['a', 'b'], y: [1, 2], ls: x, w: xyz, label: None")\n\n\n@pytest.mark.parametrize('func', all_funcs, ids=all_func_ids)\ndef test_function_call_with_dict_data(func):\n """Test with dict data -> label comes from the value of 'x' parameter."""\n data = {"a": [1, 2], "b": [8, 9], "w": "NOT"}\n assert (func(None, "a", "b", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b")\n assert (func(None, x="a", y="b", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b")\n assert (func(None, "a", "b", label="", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")\n assert (func(None, "a", "b", label="text", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")\n assert (func(None, x="a", y="b", label="", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")\n assert (func(None, x="a", y="b", label="text", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")\n\n\n@pytest.mark.parametrize('func', all_funcs, ids=all_func_ids)\ndef test_function_call_with_dict_data_not_in_data(func):\n """Test the case that one var is not in data -> half replaces, half kept"""\n data = {"a": [1, 2], "w": "NOT"}\n assert (func(None, "a", "b", data=data) ==\n "x: [1, 2], y: ['b'], ls: x, w: xyz, label: b")\n assert (func(None, x="a", y="b", data=data) ==\n "x: [1, 2], y: ['b'], ls: x, w: xyz, label: b")\n assert (func(None, "a", "b", label="", data=data) ==\n "x: [1, 2], y: ['b'], ls: x, w: xyz, label: ")\n assert (func(None, "a", "b", label="text", data=data) ==\n "x: [1, 2], y: ['b'], ls: x, w: xyz, label: text")\n assert (func(None, x="a", y="b", label="", data=data) ==\n "x: [1, 2], y: ['b'], ls: x, w: xyz, label: ")\n assert (func(None, x="a", y="b", label="text", data=data) ==\n "x: [1, 2], y: ['b'], ls: x, w: xyz, label: text")\n\n\n@pytest.mark.parametrize('func', all_funcs, ids=all_func_ids)\ndef test_function_call_with_pandas_data(func, pd):\n """Test with pandas dataframe -> label comes from ``data["col"].name``."""\n data = pd.DataFrame({"a": np.array([1, 2], dtype=np.int32),\n "b": np.array([8, 9], dtype=np.int32),\n "w": ["NOT", "NOT"]})\n\n assert (func(None, "a", "b", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b")\n assert (func(None, x="a", y="b", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b")\n assert (func(None, "a", "b", label="", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")\n assert (func(None, "a", "b", label="text", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")\n assert (func(None, x="a", y="b", label="", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")\n assert (func(None, x="a", y="b", label="text", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")\n\n\ndef test_function_call_replace_all():\n """Test without a "replace_names" argument, all vars should be replaced."""\n data = {"a": [1, 2], "b": [8, 9], "x": "xyz"}\n\n @_preprocess_data(label_namer="y")\n def func_replace_all(ax, x, y, ls="x", label=None, w="NOT"):\n return f"x: {list(x)}, y: {list(y)}, ls: {ls}, w: {w}, label: {label}"\n\n assert (func_replace_all(None, "a", "b", w="x", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b")\n assert (func_replace_all(None, x="a", y="b", w="x", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b")\n assert (func_replace_all(None, "a", "b", w="x", label="", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")\n assert (\n func_replace_all(None, "a", "b", w="x", label="text", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")\n assert (\n func_replace_all(None, x="a", y="b", w="x", label="", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")\n assert (\n func_replace_all(None, x="a", y="b", w="x", label="text", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")\n\n\ndef test_no_label_replacements():\n """Test with "label_namer=None" -> no label replacement at all."""\n\n @_preprocess_data(replace_names=["x", "y"], label_namer=None)\n def func_no_label(ax, x, y, ls="x", label=None, w="xyz"):\n return f"x: {list(x)}, y: {list(y)}, ls: {ls}, w: {w}, label: {label}"\n\n data = {"a": [1, 2], "b": [8, 9], "w": "NOT"}\n assert (func_no_label(None, "a", "b", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: None")\n assert (func_no_label(None, x="a", y="b", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: None")\n assert (func_no_label(None, "a", "b", label="", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")\n assert (func_no_label(None, "a", "b", label="text", data=data) ==\n "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")\n\n\ndef test_more_args_than_pos_parameter():\n @_preprocess_data(replace_names=["x", "y"], label_namer="y")\n def func(ax, x, y, z=1):\n pass\n\n data = {"a": [1, 2], "b": [8, 9], "w": "NOT"}\n with pytest.raises(TypeError):\n func(None, "a", "b", "z", "z", data=data)\n\n\ndef test_docstring_addition():\n @_preprocess_data()\n def funcy(ax, *args, **kwargs):\n """\n Parameters\n ----------\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n """\n\n assert re.search(r"all parameters also accept a string", funcy.__doc__)\n assert not re.search(r"the following parameters", funcy.__doc__)\n\n @_preprocess_data(replace_names=[])\n def funcy(ax, x, y, z, bar=None):\n """\n Parameters\n ----------\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n """\n\n assert not re.search(r"all parameters also accept a string", funcy.__doc__)\n assert not re.search(r"the following parameters", funcy.__doc__)\n\n @_preprocess_data(replace_names=["bar"])\n def funcy(ax, x, y, z, bar=None):\n """\n Parameters\n ----------\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n """\n\n assert not re.search(r"all parameters also accept a string", funcy.__doc__)\n assert not re.search(r"the following parameters .*: \*bar\*\.",\n funcy.__doc__)\n\n @_preprocess_data(replace_names=["x", "t"])\n def funcy(ax, x, y, z, t=None):\n """\n Parameters\n ----------\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n """\n\n assert not re.search(r"all parameters also accept a string", funcy.__doc__)\n assert not re.search(r"the following parameters .*: \*x\*, \*t\*\.",\n funcy.__doc__)\n\n\ndef test_data_parameter_replacement():\n """\n Test that the docstring contains the correct *data* parameter stub\n for all methods that we run _preprocess_data() on.\n """\n program = (\n "import logging; "\n "logging.basicConfig(level=logging.DEBUG); "\n "import matplotlib.pyplot as plt"\n )\n cmd = [sys.executable, "-c", program]\n completed_proc = subprocess_run_for_testing(\n cmd, text=True, capture_output=True\n )\n assert 'data parameter docstring error' not in completed_proc.stderr\n\n\nclass TestPlotTypes:\n\n plotters = [Axes.scatter, Axes.bar, Axes.plot]\n\n @pytest.mark.parametrize('plotter', plotters)\n @check_figures_equal(extensions=['png'])\n def test_dict_unpack(self, plotter, fig_test, fig_ref):\n x = [1, 2, 3]\n y = [4, 5, 6]\n ddict = dict(zip(x, y))\n\n plotter(fig_test.subplots(),\n ddict.keys(), ddict.values())\n plotter(fig_ref.subplots(), x, y)\n\n @pytest.mark.parametrize('plotter', plotters)\n @check_figures_equal(extensions=['png'])\n def test_data_kwarg(self, plotter, fig_test, fig_ref):\n x = [1, 2, 3]\n y = [4, 5, 6]\n\n plotter(fig_test.subplots(), 'xval', 'yval',\n data={'xval': x, 'yval': y})\n plotter(fig_ref.subplots(), x, y)\n | .venv\Lib\site-packages\matplotlib\tests\test_preprocess_data.py | test_preprocess_data.py | Python | 11,363 | 0.95 | 0.09375 | 0.04721 | vue-tools | 689 | 2023-12-23T12:59:50.424206 | BSD-3-Clause | true | 045c783a039f9d277624bcd34e2558c6 |
import difflib\n\nimport numpy as np\nimport sys\nfrom pathlib import Path\n\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib.testing import subprocess_run_for_testing\nfrom matplotlib import pyplot as plt\n\n\ndef test_pyplot_up_to_date(tmp_path):\n pytest.importorskip("black")\n\n gen_script = Path(mpl.__file__).parents[2] / "tools/boilerplate.py"\n if not gen_script.exists():\n pytest.skip("boilerplate.py not found")\n orig_contents = Path(plt.__file__).read_text()\n plt_file = tmp_path / 'pyplot.py'\n plt_file.write_text(orig_contents, 'utf-8')\n\n subprocess_run_for_testing(\n [sys.executable, str(gen_script), str(plt_file)],\n check=True)\n new_contents = plt_file.read_text('utf-8')\n\n if orig_contents != new_contents:\n diff_msg = '\n'.join(\n difflib.unified_diff(\n orig_contents.split('\n'), new_contents.split('\n'),\n fromfile='found pyplot.py',\n tofile='expected pyplot.py',\n n=0, lineterm=''))\n pytest.fail(\n "pyplot.py is not up-to-date. Please run "\n "'python tools/boilerplate.py' to update pyplot.py. "\n "This needs to be done from an environment where your "\n "current working copy is installed (e.g. 'pip install -e'd). "\n "Here is a diff of unexpected differences:\n%s" % diff_msg\n )\n\n\ndef test_copy_docstring_and_deprecators(recwarn):\n @mpl._api.rename_parameter(mpl.__version__, "old", "new")\n @mpl._api.make_keyword_only(mpl.__version__, "kwo")\n def func(new, kwo=None):\n pass\n\n @plt._copy_docstring_and_deprecators(func)\n def wrapper_func(new, kwo=None):\n pass\n\n wrapper_func(None)\n wrapper_func(new=None)\n wrapper_func(None, kwo=None)\n wrapper_func(new=None, kwo=None)\n assert not recwarn\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n wrapper_func(old=None)\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n wrapper_func(None, None)\n\n\ndef test_pyplot_box():\n fig, ax = plt.subplots()\n plt.box(False)\n assert not ax.get_frame_on()\n plt.box(True)\n assert ax.get_frame_on()\n plt.box()\n assert not ax.get_frame_on()\n plt.box()\n assert ax.get_frame_on()\n\n\ndef test_stackplot_smoke():\n # Small smoke test for stackplot (see #12405)\n plt.stackplot([1, 2, 3], [1, 2, 3])\n\n\ndef test_nrows_error():\n with pytest.raises(TypeError):\n plt.subplot(nrows=1)\n with pytest.raises(TypeError):\n plt.subplot(ncols=1)\n\n\ndef test_ioff():\n plt.ion()\n assert mpl.is_interactive()\n with plt.ioff():\n assert not mpl.is_interactive()\n assert mpl.is_interactive()\n\n plt.ioff()\n assert not mpl.is_interactive()\n with plt.ioff():\n assert not mpl.is_interactive()\n assert not mpl.is_interactive()\n\n\ndef test_ion():\n plt.ioff()\n assert not mpl.is_interactive()\n with plt.ion():\n assert mpl.is_interactive()\n assert not mpl.is_interactive()\n\n plt.ion()\n assert mpl.is_interactive()\n with plt.ion():\n assert mpl.is_interactive()\n assert mpl.is_interactive()\n\n\ndef test_nested_ion_ioff():\n # initial state is interactive\n plt.ion()\n\n # mixed ioff/ion\n with plt.ioff():\n assert not mpl.is_interactive()\n with plt.ion():\n assert mpl.is_interactive()\n assert not mpl.is_interactive()\n assert mpl.is_interactive()\n\n # redundant contexts\n with plt.ioff():\n with plt.ioff():\n assert not mpl.is_interactive()\n assert mpl.is_interactive()\n\n with plt.ion():\n plt.ioff()\n assert mpl.is_interactive()\n\n # initial state is not interactive\n plt.ioff()\n\n # mixed ioff/ion\n with plt.ion():\n assert mpl.is_interactive()\n with plt.ioff():\n assert not mpl.is_interactive()\n assert mpl.is_interactive()\n assert not mpl.is_interactive()\n\n # redundant contexts\n with plt.ion():\n with plt.ion():\n assert mpl.is_interactive()\n assert not mpl.is_interactive()\n\n with plt.ioff():\n plt.ion()\n assert not mpl.is_interactive()\n\n\ndef test_close():\n try:\n plt.close(1.1)\n except TypeError as e:\n assert str(e) == "close() argument must be a Figure, an int, " \\n "a string, or None, not <class 'float'>"\n\n\ndef test_subplot_reuse():\n ax1 = plt.subplot(121)\n assert ax1 is plt.gca()\n ax2 = plt.subplot(122)\n assert ax2 is plt.gca()\n ax3 = plt.subplot(121)\n assert ax1 is plt.gca()\n assert ax1 is ax3\n\n\ndef test_axes_kwargs():\n # plt.axes() always creates new axes, even if axes kwargs differ.\n plt.figure()\n ax = plt.axes()\n ax1 = plt.axes()\n assert ax is not None\n assert ax1 is not ax\n plt.close()\n\n plt.figure()\n ax = plt.axes(projection='polar')\n ax1 = plt.axes(projection='polar')\n assert ax is not None\n assert ax1 is not ax\n plt.close()\n\n plt.figure()\n ax = plt.axes(projection='polar')\n ax1 = plt.axes()\n assert ax is not None\n assert ax1.name == 'rectilinear'\n assert ax1 is not ax\n plt.close()\n\n\ndef test_subplot_replace_projection():\n # plt.subplot() searches for axes with the same subplot spec, and if one\n # exists, and the kwargs match returns it, create a new one if they do not\n fig = plt.figure()\n ax = plt.subplot(1, 2, 1)\n ax1 = plt.subplot(1, 2, 1)\n ax2 = plt.subplot(1, 2, 2)\n ax3 = plt.subplot(1, 2, 1, projection='polar')\n ax4 = plt.subplot(1, 2, 1, projection='polar')\n assert ax is not None\n assert ax1 is ax\n assert ax2 is not ax\n assert ax3 is not ax\n assert ax3 is ax4\n\n assert ax in fig.axes\n assert ax2 in fig.axes\n assert ax3 in fig.axes\n\n assert ax.name == 'rectilinear'\n assert ax2.name == 'rectilinear'\n assert ax3.name == 'polar'\n\n\ndef test_subplot_kwarg_collision():\n ax1 = plt.subplot(projection='polar', theta_offset=0)\n ax2 = plt.subplot(projection='polar', theta_offset=0)\n assert ax1 is ax2\n ax1.remove()\n ax3 = plt.subplot(projection='polar', theta_offset=1)\n assert ax1 is not ax3\n assert ax1 not in plt.gcf().axes\n\n\ndef test_gca():\n # plt.gca() returns an existing axes, unless there were no axes.\n plt.figure()\n ax = plt.gca()\n ax1 = plt.gca()\n assert ax is not None\n assert ax1 is ax\n plt.close()\n\n\ndef test_subplot_projection_reuse():\n # create an Axes\n ax1 = plt.subplot(111)\n # check that it is current\n assert ax1 is plt.gca()\n # make sure we get it back if we ask again\n assert ax1 is plt.subplot(111)\n # remove it\n ax1.remove()\n # create a polar plot\n ax2 = plt.subplot(111, projection='polar')\n assert ax2 is plt.gca()\n # this should have deleted the first axes\n assert ax1 not in plt.gcf().axes\n # assert we get it back if no extra parameters passed\n assert ax2 is plt.subplot(111)\n ax2.remove()\n # now check explicitly setting the projection to rectilinear\n # makes a new axes\n ax3 = plt.subplot(111, projection='rectilinear')\n assert ax3 is plt.gca()\n assert ax3 is not ax2\n assert ax2 not in plt.gcf().axes\n\n\ndef test_subplot_polar_normalization():\n ax1 = plt.subplot(111, projection='polar')\n ax2 = plt.subplot(111, polar=True)\n ax3 = plt.subplot(111, polar=True, projection='polar')\n assert ax1 is ax2\n assert ax1 is ax3\n\n with pytest.raises(ValueError,\n match="polar=True, yet projection='3d'"):\n ax2 = plt.subplot(111, polar=True, projection='3d')\n\n\ndef test_subplot_change_projection():\n created_axes = set()\n ax = plt.subplot()\n created_axes.add(ax)\n projections = ('aitoff', 'hammer', 'lambert', 'mollweide',\n 'polar', 'rectilinear', '3d')\n for proj in projections:\n ax.remove()\n ax = plt.subplot(projection=proj)\n assert ax is plt.subplot()\n assert ax.name == proj\n created_axes.add(ax)\n # Check that each call created a new Axes.\n assert len(created_axes) == 1 + len(projections)\n\n\ndef test_polar_second_call():\n # the first call creates the axes with polar projection\n ln1, = plt.polar(0., 1., 'ro')\n assert isinstance(ln1, mpl.lines.Line2D)\n # the second call should reuse the existing axes\n ln2, = plt.polar(1.57, .5, 'bo')\n assert isinstance(ln2, mpl.lines.Line2D)\n assert ln1.axes is ln2.axes\n\n\ndef test_fallback_position():\n # check that position kwarg works if rect not supplied\n axref = plt.axes([0.2, 0.2, 0.5, 0.5])\n axtest = plt.axes(position=[0.2, 0.2, 0.5, 0.5])\n np.testing.assert_allclose(axtest.bbox.get_points(),\n axref.bbox.get_points())\n\n # check that position kwarg ignored if rect is supplied\n axref = plt.axes([0.2, 0.2, 0.5, 0.5])\n axtest = plt.axes([0.2, 0.2, 0.5, 0.5], position=[0.1, 0.1, 0.8, 0.8])\n np.testing.assert_allclose(axtest.bbox.get_points(),\n axref.bbox.get_points())\n\n\ndef test_set_current_figure_via_subfigure():\n fig1 = plt.figure()\n subfigs = fig1.subfigures(2)\n\n plt.figure()\n assert plt.gcf() != fig1\n\n current = plt.figure(subfigs[1])\n assert plt.gcf() == fig1\n assert current == fig1\n\n\ndef test_set_current_axes_on_subfigure():\n fig = plt.figure()\n subfigs = fig.subfigures(2)\n\n ax = subfigs[0].subplots(1, squeeze=True)\n subfigs[1].subplots(1, squeeze=True)\n\n assert plt.gca() != ax\n plt.sca(ax)\n assert plt.gca() == ax\n\n\ndef test_pylab_integration():\n IPython = pytest.importorskip("IPython")\n mpl.testing.subprocess_run_helper(\n IPython.start_ipython,\n "--pylab",\n "-c",\n ";".join((\n "import matplotlib.pyplot as plt",\n "assert plt._REPL_DISPLAYHOOK == plt._ReplDisplayHook.IPYTHON",\n )),\n timeout=60,\n )\n\n\ndef test_doc_pyplot_summary():\n """Test that pyplot_summary lists all the plot functions."""\n pyplot_docs = Path(__file__).parent / '../../../doc/api/pyplot_summary.rst'\n if not pyplot_docs.exists():\n pytest.skip("Documentation sources not available")\n\n def extract_documented_functions(lines):\n """\n Return a list of all the functions that are mentioned in the\n autosummary blocks contained in *lines*.\n\n An autosummary block looks like this::\n\n .. autosummary::\n :toctree: _as_gen\n :template: autosummary.rst\n :nosignatures:\n\n plot\n plot_date\n\n """\n functions = []\n in_autosummary = False\n for line in lines:\n if not in_autosummary:\n if line.startswith(".. autosummary::"):\n in_autosummary = True\n else:\n if not line or line.startswith(" :"):\n # empty line or autosummary parameter\n continue\n if not line[0].isspace():\n # no more indentation: end of autosummary block\n in_autosummary = False\n continue\n functions.append(line.strip())\n return functions\n\n lines = pyplot_docs.read_text().split("\n")\n doc_functions = set(extract_documented_functions(lines))\n plot_commands = set(plt._get_pyplot_commands())\n missing = plot_commands.difference(doc_functions)\n if missing:\n raise AssertionError(\n f"The following pyplot functions are not listed in the "\n f"documentation. Please add them to doc/api/pyplot_summary.rst: "\n f"{missing!r}")\n extra = doc_functions.difference(plot_commands)\n if extra:\n raise AssertionError(\n f"The following functions are listed in the pyplot documentation, "\n f"but they do not exist in pyplot. "\n f"Please remove them from doc/api/pyplot_summary.rst: {extra!r}")\n\n\ndef test_minor_ticks():\n plt.figure()\n plt.plot(np.arange(1, 10))\n tick_pos, tick_labels = plt.xticks(minor=True)\n assert np.all(tick_labels == np.array([], dtype=np.float64))\n assert tick_labels == []\n\n plt.yticks(ticks=[3.5, 6.5], labels=["a", "b"], minor=True)\n ax = plt.gca()\n tick_pos = ax.get_yticks(minor=True)\n tick_labels = ax.get_yticklabels(minor=True)\n assert np.all(tick_pos == np.array([3.5, 6.5]))\n assert [l.get_text() for l in tick_labels] == ['a', 'b']\n\n\ndef test_switch_backend_no_close():\n plt.switch_backend('agg')\n fig = plt.figure()\n fig = plt.figure()\n assert len(plt.get_fignums()) == 2\n plt.switch_backend('agg')\n assert len(plt.get_fignums()) == 2\n plt.switch_backend('svg')\n assert len(plt.get_fignums()) == 2\n\n\ndef figure_hook_example(figure):\n figure._test_was_here = True\n\n\ndef test_figure_hook():\n\n test_rc = {\n 'figure.hooks': ['matplotlib.tests.test_pyplot:figure_hook_example']\n }\n with mpl.rc_context(test_rc):\n fig = plt.figure()\n\n assert fig._test_was_here\n\n\ndef test_multiple_same_figure_calls():\n fig = plt.figure(1, figsize=(1, 2))\n with pytest.warns(UserWarning, match="Ignoring specified arguments in this call"):\n fig2 = plt.figure(1, figsize=np.array([3, 4]))\n with pytest.warns(UserWarning, match="Ignoring specified arguments in this call"):\n plt.figure(fig, figsize=np.array([5, 6]))\n assert fig is fig2\n fig3 = plt.figure(1) # Checks for false warnings\n assert fig is fig3\n\n\ndef test_close_all_warning():\n fig1 = plt.figure()\n\n # Check that the warning is issued when 'all' is passed to plt.figure\n with pytest.warns(UserWarning, match="closes all existing figures"):\n fig2 = plt.figure("all")\n\n\ndef test_matshow():\n fig = plt.figure()\n arr = [[0, 1], [1, 2]]\n\n # Smoke test that matshow does not ask for a new figsize on the existing figure\n plt.matshow(arr, fignum=fig.number)\n | .venv\Lib\site-packages\matplotlib\tests\test_pyplot.py | test_pyplot.py | Python | 13,910 | 0.95 | 0.119588 | 0.074935 | vue-tools | 398 | 2024-09-20T18:38:37.765854 | Apache-2.0 | true | 0e9e69876d134741305b9a78deb72a87 |
import platform\nimport sys\n\nimport numpy as np\nimport pytest\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.testing.decorators import image_comparison\nfrom matplotlib.testing.decorators import check_figures_equal\n\n\ndef draw_quiver(ax, **kwargs):\n X, Y = np.meshgrid(np.arange(0, 2 * np.pi, 1),\n np.arange(0, 2 * np.pi, 1))\n U = np.cos(X)\n V = np.sin(Y)\n\n Q = ax.quiver(U, V, **kwargs)\n return Q\n\n\n@pytest.mark.skipif(platform.python_implementation() != 'CPython',\n reason='Requires CPython')\ndef test_quiver_memory_leak():\n fig, ax = plt.subplots()\n\n Q = draw_quiver(ax)\n ttX = Q.X\n orig_refcount = sys.getrefcount(ttX)\n Q.remove()\n\n del Q\n\n assert sys.getrefcount(ttX) < orig_refcount\n\n\n@pytest.mark.skipif(platform.python_implementation() != 'CPython',\n reason='Requires CPython')\ndef test_quiver_key_memory_leak():\n fig, ax = plt.subplots()\n\n Q = draw_quiver(ax)\n\n qk = ax.quiverkey(Q, 0.5, 0.92, 2, r'$2 \frac{m}{s}$',\n labelpos='W',\n fontproperties={'weight': 'bold'})\n orig_refcount = sys.getrefcount(qk)\n qk.remove()\n assert sys.getrefcount(qk) < orig_refcount\n\n\ndef test_quiver_number_of_args():\n X = [1, 2]\n with pytest.raises(\n TypeError,\n match='takes from 2 to 5 positional arguments but 1 were given'):\n plt.quiver(X)\n with pytest.raises(\n TypeError,\n match='takes from 2 to 5 positional arguments but 6 were given'):\n plt.quiver(X, X, X, X, X, X)\n\n\ndef test_quiver_arg_sizes():\n X2 = [1, 2]\n X3 = [1, 2, 3]\n with pytest.raises(\n ValueError, match=('X and Y must be the same size, but '\n 'X.size is 2 and Y.size is 3.')):\n plt.quiver(X2, X3, X2, X2)\n with pytest.raises(\n ValueError, match=('Argument U has a size 3 which does not match '\n '2, the number of arrow positions')):\n plt.quiver(X2, X2, X3, X2)\n with pytest.raises(\n ValueError, match=('Argument V has a size 3 which does not match '\n '2, the number of arrow positions')):\n plt.quiver(X2, X2, X2, X3)\n with pytest.raises(\n ValueError, match=('Argument C has a size 3 which does not match '\n '2, the number of arrow positions')):\n plt.quiver(X2, X2, X2, X2, X3)\n\n\ndef test_no_warnings():\n fig, ax = plt.subplots()\n X, Y = np.meshgrid(np.arange(15), np.arange(10))\n U = V = np.ones_like(X)\n phi = (np.random.rand(15, 10) - .5) * 150\n ax.quiver(X, Y, U, V, angles=phi)\n fig.canvas.draw() # Check that no warning is emitted.\n\n\ndef test_zero_headlength():\n # Based on report by Doug McNeil:\n # https://discourse.matplotlib.org/t/quiver-warnings/16722\n fig, ax = plt.subplots()\n X, Y = np.meshgrid(np.arange(10), np.arange(10))\n U, V = np.cos(X), np.sin(Y)\n ax.quiver(U, V, headlength=0, headaxislength=0)\n fig.canvas.draw() # Check that no warning is emitted.\n\n\n@image_comparison(['quiver_animated_test_image.png'])\ndef test_quiver_animate():\n # Tests fix for #2616\n fig, ax = plt.subplots()\n Q = draw_quiver(ax, animated=True)\n ax.quiverkey(Q, 0.5, 0.92, 2, r'$2 \frac{m}{s}$',\n labelpos='W', fontproperties={'weight': 'bold'})\n\n\n@image_comparison(['quiver_with_key_test_image.png'])\ndef test_quiver_with_key():\n fig, ax = plt.subplots()\n ax.margins(0.1)\n Q = draw_quiver(ax)\n ax.quiverkey(Q, 0.5, 0.95, 2,\n r'$2\, \mathrm{m}\, \mathrm{s}^{-1}$',\n angle=-10,\n coordinates='figure',\n labelpos='W',\n fontproperties={'weight': 'bold', 'size': 'large'})\n\n\n@image_comparison(['quiver_single_test_image.png'], remove_text=True)\ndef test_quiver_single():\n fig, ax = plt.subplots()\n ax.margins(0.1)\n ax.quiver([1], [1], [2], [2])\n\n\ndef test_quiver_copy():\n fig, ax = plt.subplots()\n uv = dict(u=np.array([1.1]), v=np.array([2.0]))\n q0 = ax.quiver([1], [1], uv['u'], uv['v'])\n uv['v'][0] = 0\n assert q0.V[0] == 2.0\n\n\n@image_comparison(['quiver_key_pivot.png'], remove_text=True)\ndef test_quiver_key_pivot():\n fig, ax = plt.subplots()\n\n u, v = np.mgrid[0:2*np.pi:10j, 0:2*np.pi:10j]\n\n q = ax.quiver(np.sin(u), np.cos(v))\n ax.set_xlim(-2, 11)\n ax.set_ylim(-2, 11)\n ax.quiverkey(q, 0.5, 1, 1, 'N', labelpos='N')\n ax.quiverkey(q, 1, 0.5, 1, 'E', labelpos='E')\n ax.quiverkey(q, 0.5, 0, 1, 'S', labelpos='S')\n ax.quiverkey(q, 0, 0.5, 1, 'W', labelpos='W')\n\n\n@image_comparison(['quiver_key_xy.png'], remove_text=True)\ndef test_quiver_key_xy():\n # With scale_units='xy', ensure quiverkey still matches its quiver.\n # Note that the quiver and quiverkey lengths depend on the axes aspect\n # ratio, and that with angles='xy' their angles also depend on the axes\n # aspect ratio.\n X = np.arange(8)\n Y = np.zeros(8)\n angles = X * (np.pi / 4)\n uv = np.exp(1j * angles)\n U = uv.real\n V = uv.imag\n fig, axs = plt.subplots(2)\n for ax, angle_str in zip(axs, ('uv', 'xy')):\n ax.set_xlim(-1, 8)\n ax.set_ylim(-0.2, 0.2)\n q = ax.quiver(X, Y, U, V, pivot='middle',\n units='xy', width=0.05,\n scale=2, scale_units='xy',\n angles=angle_str)\n for x, angle in zip((0.2, 0.5, 0.8), (0, 45, 90)):\n ax.quiverkey(q, X=x, Y=0.8, U=1, angle=angle, label='', color='b')\n\n\n@image_comparison(['barbs_test_image.png'], remove_text=True)\ndef test_barbs():\n x = np.linspace(-5, 5, 5)\n X, Y = np.meshgrid(x, x)\n U, V = 12*X, 12*Y\n fig, ax = plt.subplots()\n ax.barbs(X, Y, U, V, np.hypot(U, V), fill_empty=True, rounding=False,\n sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3),\n cmap='viridis')\n\n\n@image_comparison(['barbs_pivot_test_image.png'], remove_text=True)\ndef test_barbs_pivot():\n x = np.linspace(-5, 5, 5)\n X, Y = np.meshgrid(x, x)\n U, V = 12*X, 12*Y\n fig, ax = plt.subplots()\n ax.barbs(X, Y, U, V, fill_empty=True, rounding=False, pivot=1.7,\n sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3))\n ax.scatter(X, Y, s=49, c='black')\n\n\n@image_comparison(['barbs_test_flip.png'], remove_text=True)\ndef test_barbs_flip():\n """Test barbs with an array for flip_barb."""\n x = np.linspace(-5, 5, 5)\n X, Y = np.meshgrid(x, x)\n U, V = 12*X, 12*Y\n fig, ax = plt.subplots()\n ax.barbs(X, Y, U, V, fill_empty=True, rounding=False, pivot=1.7,\n sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3),\n flip_barb=Y < 0)\n\n\ndef test_barb_copy():\n fig, ax = plt.subplots()\n u = np.array([1.1])\n v = np.array([2.2])\n b0 = ax.barbs([1], [1], u, v)\n u[0] = 0\n assert b0.u[0] == 1.1\n v[0] = 0\n assert b0.v[0] == 2.2\n\n\ndef test_bad_masked_sizes():\n """Test error handling when given differing sized masked arrays."""\n x = np.arange(3)\n y = np.arange(3)\n u = np.ma.array(15. * np.ones((4,)))\n v = np.ma.array(15. * np.ones_like(u))\n u[1] = np.ma.masked\n v[1] = np.ma.masked\n fig, ax = plt.subplots()\n with pytest.raises(ValueError):\n ax.barbs(x, y, u, v)\n\n\ndef test_angles_and_scale():\n # angles array + scale_units kwarg\n fig, ax = plt.subplots()\n X, Y = np.meshgrid(np.arange(15), np.arange(10))\n U = V = np.ones_like(X)\n phi = (np.random.rand(15, 10) - .5) * 150\n ax.quiver(X, Y, U, V, angles=phi, scale_units='xy')\n\n\n@image_comparison(['quiver_xy.png'], remove_text=True)\ndef test_quiver_xy():\n # simple arrow pointing from SW to NE\n fig, ax = plt.subplots(subplot_kw=dict(aspect='equal'))\n ax.quiver(0, 0, 1, 1, angles='xy', scale_units='xy', scale=1)\n ax.set_xlim(0, 1.1)\n ax.set_ylim(0, 1.1)\n ax.grid()\n\n\ndef test_quiverkey_angles():\n # Check that only a single arrow is plotted for a quiverkey when an array\n # of angles is given to the original quiver plot\n fig, ax = plt.subplots()\n\n X, Y = np.meshgrid(np.arange(2), np.arange(2))\n U = V = angles = np.ones_like(X)\n\n q = ax.quiver(X, Y, U, V, angles=angles)\n qk = ax.quiverkey(q, 1, 1, 2, 'Label')\n # The arrows are only created when the key is drawn\n fig.canvas.draw()\n assert len(qk.verts) == 1\n\n\ndef test_quiverkey_angles_xy_aitoff():\n # GH 26316 and GH 26748\n # Test that only one arrow will be plotted with non-cartesian\n # when angles='xy' and/or scale_units='xy'\n\n # only for test purpose\n # scale_units='xy' may not be a valid use case for non-cartesian\n kwargs_list = [\n {'angles': 'xy'},\n {'angles': 'xy', 'scale_units': 'xy'},\n {'scale_units': 'xy'}\n ]\n\n for kwargs_dict in kwargs_list:\n\n x = np.linspace(-np.pi, np.pi, 11)\n y = np.ones_like(x) * np.pi / 6\n vx = np.zeros_like(x)\n vy = np.ones_like(x)\n\n fig = plt.figure()\n ax = fig.add_subplot(projection='aitoff')\n q = ax.quiver(x, y, vx, vy, **kwargs_dict)\n qk = ax.quiverkey(q, 0, 0, 1, '1 units')\n\n fig.canvas.draw()\n assert len(qk.verts) == 1\n\n\ndef test_quiverkey_angles_scale_units_cartesian():\n # GH 26316\n # Test that only one arrow will be plotted with normal cartesian\n # when angles='xy' and/or scale_units='xy'\n\n kwargs_list = [\n {'angles': 'xy'},\n {'angles': 'xy', 'scale_units': 'xy'},\n {'scale_units': 'xy'}\n ]\n\n for kwargs_dict in kwargs_list:\n X = [0, -1, 0]\n Y = [0, -1, 0]\n U = [1, -1, 1]\n V = [1, -1, 0]\n\n fig, ax = plt.subplots()\n q = ax.quiver(X, Y, U, V, **kwargs_dict)\n ax.quiverkey(q, X=0.3, Y=1.1, U=1,\n label='Quiver key, length = 1', labelpos='E')\n qk = ax.quiverkey(q, 0, 0, 1, '1 units')\n\n fig.canvas.draw()\n assert len(qk.verts) == 1\n\n\ndef test_quiver_setuvc_numbers():\n """Check that it is possible to set all arrow UVC to the same numbers"""\n\n fig, ax = plt.subplots()\n\n X, Y = np.meshgrid(np.arange(2), np.arange(2))\n U = V = np.ones_like(X)\n\n q = ax.quiver(X, Y, U, V)\n q.set_UVC(0, 1)\n\n\ndef draw_quiverkey_zorder_argument(fig, zorder=None):\n """Draw Quiver and QuiverKey using zorder argument"""\n x = np.arange(1, 6, 1)\n y = np.arange(1, 6, 1)\n X, Y = np.meshgrid(x, y)\n U, V = 2, 2\n\n ax = fig.subplots()\n q = ax.quiver(X, Y, U, V, pivot='middle')\n ax.set_xlim(0.5, 5.5)\n ax.set_ylim(0.5, 5.5)\n if zorder is None:\n ax.quiverkey(q, 4, 4, 25, coordinates='data',\n label='U', color='blue')\n ax.quiverkey(q, 5.5, 2, 20, coordinates='data',\n label='V', color='blue', angle=90)\n else:\n ax.quiverkey(q, 4, 4, 25, coordinates='data',\n label='U', color='blue', zorder=zorder)\n ax.quiverkey(q, 5.5, 2, 20, coordinates='data',\n label='V', color='blue', angle=90, zorder=zorder)\n\n\ndef draw_quiverkey_setzorder(fig, zorder=None):\n """Draw Quiver and QuiverKey using set_zorder"""\n x = np.arange(1, 6, 1)\n y = np.arange(1, 6, 1)\n X, Y = np.meshgrid(x, y)\n U, V = 2, 2\n\n ax = fig.subplots()\n q = ax.quiver(X, Y, U, V, pivot='middle')\n ax.set_xlim(0.5, 5.5)\n ax.set_ylim(0.5, 5.5)\n qk1 = ax.quiverkey(q, 4, 4, 25, coordinates='data',\n label='U', color='blue')\n qk2 = ax.quiverkey(q, 5.5, 2, 20, coordinates='data',\n label='V', color='blue', angle=90)\n if zorder is not None:\n qk1.set_zorder(zorder)\n qk2.set_zorder(zorder)\n\n\n@pytest.mark.parametrize('zorder', [0, 2, 5, None])\n@check_figures_equal(extensions=['png'])\ndef test_quiverkey_zorder(fig_test, fig_ref, zorder):\n draw_quiverkey_zorder_argument(fig_test, zorder=zorder)\n draw_quiverkey_setzorder(fig_ref, zorder=zorder)\n | .venv\Lib\site-packages\matplotlib\tests\test_quiver.py | test_quiver.py | Python | 11,953 | 0.95 | 0.098191 | 0.065147 | node-utils | 27 | 2025-01-22T12:57:19.358449 | Apache-2.0 | true | f08a8ca83ef7df00a8f53587efb8a58a |
import copy\nimport os\nimport subprocess\nimport sys\nfrom unittest import mock\n\nfrom cycler import cycler, Cycler\nfrom packaging.version import parse as parse_version\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib import _api, _c_internal_utils\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mcolors\nimport numpy as np\nfrom matplotlib.rcsetup import (\n validate_bool,\n validate_color,\n validate_colorlist,\n _validate_color_or_linecolor,\n validate_cycler,\n validate_float,\n validate_fontstretch,\n validate_fontweight,\n validate_hatch,\n validate_hist_bins,\n validate_int,\n validate_markevery,\n validate_stringlist,\n validate_sketch,\n _validate_linestyle,\n _listify_validator)\nfrom matplotlib.testing import subprocess_run_for_testing\n\n\ndef test_rcparams(tmp_path):\n mpl.rc('text', usetex=False)\n mpl.rc('lines', linewidth=22)\n\n usetex = mpl.rcParams['text.usetex']\n linewidth = mpl.rcParams['lines.linewidth']\n\n rcpath = tmp_path / 'test_rcparams.rc'\n rcpath.write_text('lines.linewidth: 33', encoding='utf-8')\n\n # test context given dictionary\n with mpl.rc_context(rc={'text.usetex': not usetex}):\n assert mpl.rcParams['text.usetex'] == (not usetex)\n assert mpl.rcParams['text.usetex'] == usetex\n\n # test context given filename (mpl.rc sets linewidth to 33)\n with mpl.rc_context(fname=rcpath):\n assert mpl.rcParams['lines.linewidth'] == 33\n assert mpl.rcParams['lines.linewidth'] == linewidth\n\n # test context given filename and dictionary\n with mpl.rc_context(fname=rcpath, rc={'lines.linewidth': 44}):\n assert mpl.rcParams['lines.linewidth'] == 44\n assert mpl.rcParams['lines.linewidth'] == linewidth\n\n # test context as decorator (and test reusability, by calling func twice)\n @mpl.rc_context({'lines.linewidth': 44})\n def func():\n assert mpl.rcParams['lines.linewidth'] == 44\n\n func()\n func()\n\n # test rc_file\n mpl.rc_file(rcpath)\n assert mpl.rcParams['lines.linewidth'] == 33\n\n\ndef test_RcParams_class():\n rc = mpl.RcParams({'font.cursive': ['Apple Chancery',\n 'Textile',\n 'Zapf Chancery',\n 'cursive'],\n 'font.family': 'sans-serif',\n 'font.weight': 'normal',\n 'font.size': 12})\n\n expected_repr = """\nRcParams({'font.cursive': ['Apple Chancery',\n 'Textile',\n 'Zapf Chancery',\n 'cursive'],\n 'font.family': ['sans-serif'],\n 'font.size': 12.0,\n 'font.weight': 'normal'})""".lstrip()\n\n assert expected_repr == repr(rc)\n\n expected_str = """\nfont.cursive: ['Apple Chancery', 'Textile', 'Zapf Chancery', 'cursive']\nfont.family: ['sans-serif']\nfont.size: 12.0\nfont.weight: normal""".lstrip()\n\n assert expected_str == str(rc)\n\n # test the find_all functionality\n assert ['font.cursive', 'font.size'] == sorted(rc.find_all('i[vz]'))\n assert ['font.family'] == list(rc.find_all('family'))\n\n\ndef test_rcparams_update():\n rc = mpl.RcParams({'figure.figsize': (3.5, 42)})\n bad_dict = {'figure.figsize': (3.5, 42, 1)}\n # make sure validation happens on input\n with pytest.raises(ValueError):\n rc.update(bad_dict)\n\n\ndef test_rcparams_init():\n with pytest.raises(ValueError):\n mpl.RcParams({'figure.figsize': (3.5, 42, 1)})\n\n\ndef test_nargs_cycler():\n from matplotlib.rcsetup import cycler as ccl\n with pytest.raises(TypeError, match='3 were given'):\n # cycler() takes 0-2 arguments.\n ccl(ccl(color=list('rgb')), 2, 3)\n\n\ndef test_Bug_2543():\n # Test that it possible to add all values to itself / deepcopy\n # https://github.com/matplotlib/matplotlib/issues/2543\n # We filter warnings at this stage since a number of them are raised\n # for deprecated rcparams as they should. We don't want these in the\n # printed in the test suite.\n with _api.suppress_matplotlib_deprecation_warning():\n with mpl.rc_context():\n _copy = mpl.rcParams.copy()\n for key in _copy:\n mpl.rcParams[key] = _copy[key]\n with mpl.rc_context():\n copy.deepcopy(mpl.rcParams)\n with pytest.raises(ValueError):\n validate_bool(None)\n with pytest.raises(ValueError):\n with mpl.rc_context():\n mpl.rcParams['svg.fonttype'] = True\n\n\nlegend_color_tests = [\n ('face', {'color': 'r'}, mcolors.to_rgba('r')),\n ('face', {'color': 'inherit', 'axes.facecolor': 'r'},\n mcolors.to_rgba('r')),\n ('face', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g')),\n ('edge', {'color': 'r'}, mcolors.to_rgba('r')),\n ('edge', {'color': 'inherit', 'axes.edgecolor': 'r'},\n mcolors.to_rgba('r')),\n ('edge', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g'))\n]\nlegend_color_test_ids = [\n 'same facecolor',\n 'inherited facecolor',\n 'different facecolor',\n 'same edgecolor',\n 'inherited edgecolor',\n 'different facecolor',\n]\n\n\n@pytest.mark.parametrize('color_type, param_dict, target', legend_color_tests,\n ids=legend_color_test_ids)\ndef test_legend_colors(color_type, param_dict, target):\n param_dict[f'legend.{color_type}color'] = param_dict.pop('color')\n get_func = f'get_{color_type}color'\n\n with mpl.rc_context(param_dict):\n _, ax = plt.subplots()\n ax.plot(range(3), label='test')\n leg = ax.legend()\n assert getattr(leg.legendPatch, get_func)() == target\n\n\ndef test_mfc_rcparams():\n mpl.rcParams['lines.markerfacecolor'] = 'r'\n ln = mpl.lines.Line2D([1, 2], [1, 2])\n assert ln.get_markerfacecolor() == 'r'\n\n\ndef test_mec_rcparams():\n mpl.rcParams['lines.markeredgecolor'] = 'r'\n ln = mpl.lines.Line2D([1, 2], [1, 2])\n assert ln.get_markeredgecolor() == 'r'\n\n\ndef test_axes_titlecolor_rcparams():\n mpl.rcParams['axes.titlecolor'] = 'r'\n _, ax = plt.subplots()\n title = ax.set_title("Title")\n assert title.get_color() == 'r'\n\n\ndef test_Issue_1713(tmp_path):\n rcpath = tmp_path / 'test_rcparams.rc'\n rcpath.write_text('timezone: UTC', encoding='utf-8')\n with mock.patch('locale.getpreferredencoding', return_value='UTF-32-BE'):\n rc = mpl.rc_params_from_file(rcpath, True, False)\n assert rc.get('timezone') == 'UTC'\n\n\ndef test_animation_frame_formats():\n # Animation frame_format should allow any of the following\n # if any of these are not allowed, an exception will be raised\n # test for gh issue #17908\n for fmt in ['png', 'jpeg', 'tiff', 'raw', 'rgba', 'ppm',\n 'sgi', 'bmp', 'pbm', 'svg']:\n mpl.rcParams['animation.frame_format'] = fmt\n\n\ndef generate_validator_testcases(valid):\n validation_tests = (\n {'validator': validate_bool,\n 'success': (*((_, True) for _ in\n ('t', 'y', 'yes', 'on', 'true', '1', 1, True)),\n *((_, False) for _ in\n ('f', 'n', 'no', 'off', 'false', '0', 0, False))),\n 'fail': ((_, ValueError)\n for _ in ('aardvark', 2, -1, [], ))\n },\n {'validator': validate_stringlist,\n 'success': (('', []),\n ('a,b', ['a', 'b']),\n ('aardvark', ['aardvark']),\n ('aardvark, ', ['aardvark']),\n ('aardvark, ,', ['aardvark']),\n (['a', 'b'], ['a', 'b']),\n (('a', 'b'), ['a', 'b']),\n (iter(['a', 'b']), ['a', 'b']),\n (np.array(['a', 'b']), ['a', 'b']),\n ),\n 'fail': ((set(), ValueError),\n (1, ValueError),\n )\n },\n {'validator': _listify_validator(validate_int, n=2),\n 'success': ((_, [1, 2])\n for _ in ('1, 2', [1.5, 2.5], [1, 2],\n (1, 2), np.array((1, 2)))),\n 'fail': ((_, ValueError)\n for _ in ('aardvark', ('a', 1),\n (1, 2, 3)\n ))\n },\n {'validator': _listify_validator(validate_float, n=2),\n 'success': ((_, [1.5, 2.5])\n for _ in ('1.5, 2.5', [1.5, 2.5], [1.5, 2.5],\n (1.5, 2.5), np.array((1.5, 2.5)))),\n 'fail': ((_, ValueError)\n for _ in ('aardvark', ('a', 1), (1, 2, 3), (None, ), None))\n },\n {'validator': validate_cycler,\n 'success': (('cycler("color", "rgb")',\n cycler("color", 'rgb')),\n (cycler('linestyle', ['-', '--']),\n cycler('linestyle', ['-', '--'])),\n ("""(cycler("color", ["r", "g", "b"]) +\n cycler("mew", [2, 3, 5]))""",\n (cycler("color", 'rgb') +\n cycler("markeredgewidth", [2, 3, 5]))),\n ("cycler(c='rgb', lw=[1, 2, 3])",\n cycler('color', 'rgb') + cycler('linewidth', [1, 2, 3])),\n ("cycler('c', 'rgb') * cycler('linestyle', ['-', '--'])",\n (cycler('color', 'rgb') *\n cycler('linestyle', ['-', '--']))),\n (cycler('ls', ['-', '--']),\n cycler('linestyle', ['-', '--'])),\n (cycler(mew=[2, 5]),\n cycler('markeredgewidth', [2, 5])),\n ),\n # This is *so* incredibly important: validate_cycler() eval's\n # an arbitrary string! I think I have it locked down enough,\n # and that is what this is testing.\n # TODO: Note that these tests are actually insufficient, as it may\n # be that they raised errors, but still did an action prior to\n # raising the exception. We should devise some additional tests\n # for that...\n 'fail': ((4, ValueError), # Gotta be a string or Cycler object\n ('cycler("bleh, [])', ValueError), # syntax error\n ('Cycler("linewidth", [1, 2, 3])',\n ValueError), # only 'cycler()' function is allowed\n # do not allow dunder in string literals\n ("cycler('c', [j.__class__(j) for j in ['r', 'b']])",\n ValueError),\n ("cycler('c', [j. __class__(j) for j in ['r', 'b']])",\n ValueError),\n ("cycler('c', [j.\t__class__(j) for j in ['r', 'b']])",\n ValueError),\n ("cycler('c', [j.\u000c__class__(j) for j in ['r', 'b']])",\n ValueError),\n ("cycler('c', [j.__class__(j).lower() for j in ['r', 'b']])",\n ValueError),\n ('1 + 2', ValueError), # doesn't produce a Cycler object\n ('os.system("echo Gotcha")', ValueError), # os not available\n ('import os', ValueError), # should not be able to import\n ('def badjuju(a): return a; badjuju(cycler("color", "rgb"))',\n ValueError), # Should not be able to define anything\n # even if it does return a cycler\n ('cycler("waka", [1, 2, 3])', ValueError), # not a property\n ('cycler(c=[1, 2, 3])', ValueError), # invalid values\n ("cycler(lw=['a', 'b', 'c'])", ValueError), # invalid values\n (cycler('waka', [1, 3, 5]), ValueError), # not a property\n (cycler('color', ['C1', 'r', 'g']), ValueError) # no CN\n )\n },\n {'validator': validate_hatch,\n 'success': (('--|', '--|'), ('\\oO', '\\oO'),\n ('/+*/.x', '/+*/.x'), ('', '')),\n 'fail': (('--_', ValueError),\n (8, ValueError),\n ('X', ValueError)),\n },\n {'validator': validate_colorlist,\n 'success': (('r,g,b', ['r', 'g', 'b']),\n (['r', 'g', 'b'], ['r', 'g', 'b']),\n ('r, ,', ['r']),\n (['', 'g', 'blue'], ['g', 'blue']),\n ([np.array([1, 0, 0]), np.array([0, 1, 0])],\n np.array([[1, 0, 0], [0, 1, 0]])),\n (np.array([[1, 0, 0], [0, 1, 0]]),\n np.array([[1, 0, 0], [0, 1, 0]])),\n ),\n 'fail': (('fish', ValueError),\n ),\n },\n {'validator': validate_color,\n 'success': (('None', 'none'),\n ('none', 'none'),\n ('AABBCC', '#AABBCC'), # RGB hex code\n ('AABBCC00', '#AABBCC00'), # RGBA hex code\n ('tab:blue', 'tab:blue'), # named color\n ('C12', 'C12'), # color from cycle\n ('(0, 1, 0)', (0.0, 1.0, 0.0)), # RGB tuple\n ((0, 1, 0), (0, 1, 0)), # non-string version\n ('(0, 1, 0, 1)', (0.0, 1.0, 0.0, 1.0)), # RGBA tuple\n ((0, 1, 0, 1), (0, 1, 0, 1)), # non-string version\n ),\n 'fail': (('tab:veryblue', ValueError), # invalid name\n ('(0, 1)', ValueError), # tuple with length < 3\n ('(0, 1, 0, 1, 0)', ValueError), # tuple with length > 4\n ('(0, 1, none)', ValueError), # cannot cast none to float\n ('(0, 1, "0.5")', ValueError), # last one not a float\n ),\n },\n {'validator': _validate_color_or_linecolor,\n 'success': (('linecolor', 'linecolor'),\n ('markerfacecolor', 'markerfacecolor'),\n ('mfc', 'markerfacecolor'),\n ('markeredgecolor', 'markeredgecolor'),\n ('mec', 'markeredgecolor')\n ),\n 'fail': (('line', ValueError),\n ('marker', ValueError)\n )\n },\n {'validator': validate_hist_bins,\n 'success': (('auto', 'auto'),\n ('fd', 'fd'),\n ('10', 10),\n ('1, 2, 3', [1, 2, 3]),\n ([1, 2, 3], [1, 2, 3]),\n (np.arange(15), np.arange(15))\n ),\n 'fail': (('aardvark', ValueError),\n )\n },\n {'validator': validate_markevery,\n 'success': ((None, None),\n (1, 1),\n (0.1, 0.1),\n ((1, 1), (1, 1)),\n ((0.1, 0.1), (0.1, 0.1)),\n ([1, 2, 3], [1, 2, 3]),\n (slice(2), slice(None, 2, None)),\n (slice(1, 2, 3), slice(1, 2, 3))\n ),\n 'fail': (((1, 2, 3), TypeError),\n ([1, 2, 0.3], TypeError),\n (['a', 2, 3], TypeError),\n ([1, 2, 'a'], TypeError),\n ((0.1, 0.2, 0.3), TypeError),\n ((0.1, 2, 3), TypeError),\n ((1, 0.2, 0.3), TypeError),\n ((1, 0.1), TypeError),\n ((0.1, 1), TypeError),\n (('abc'), TypeError),\n ((1, 'a'), TypeError),\n ((0.1, 'b'), TypeError),\n (('a', 1), TypeError),\n (('a', 0.1), TypeError),\n ('abc', TypeError),\n ('a', TypeError),\n (object(), TypeError)\n )\n },\n {'validator': _validate_linestyle,\n 'success': (('-', '-'), ('solid', 'solid'),\n ('--', '--'), ('dashed', 'dashed'),\n ('-.', '-.'), ('dashdot', 'dashdot'),\n (':', ':'), ('dotted', 'dotted'),\n ('', ''), (' ', ' '),\n ('None', 'none'), ('none', 'none'),\n ('DoTtEd', 'dotted'), # case-insensitive\n ('1, 3', (0, (1, 3))),\n ([1.23, 456], (0, [1.23, 456.0])),\n ([1, 2, 3, 4], (0, [1.0, 2.0, 3.0, 4.0])),\n ((0, [1, 2]), (0, [1, 2])),\n ((-1, [1, 2]), (-1, [1, 2])),\n ),\n 'fail': (('aardvark', ValueError), # not a valid string\n (b'dotted', ValueError),\n ('dotted'.encode('utf-16'), ValueError),\n ([1, 2, 3], ValueError), # sequence with odd length\n (1.23, ValueError), # not a sequence\n (("a", [1, 2]), ValueError), # wrong explicit offset\n ((None, [1, 2]), ValueError), # wrong explicit offset\n ((1, [1, 2, 3]), ValueError), # odd length sequence\n (([1, 2], 1), ValueError), # inverted offset/onoff\n )\n },\n )\n\n for validator_dict in validation_tests:\n validator = validator_dict['validator']\n if valid:\n for arg, target in validator_dict['success']:\n yield validator, arg, target\n else:\n for arg, error_type in validator_dict['fail']:\n yield validator, arg, error_type\n\n\n@pytest.mark.parametrize('validator, arg, target',\n generate_validator_testcases(True))\ndef test_validator_valid(validator, arg, target):\n res = validator(arg)\n if isinstance(target, np.ndarray):\n np.testing.assert_equal(res, target)\n elif not isinstance(target, Cycler):\n assert res == target\n else:\n # Cyclers can't simply be asserted equal. They don't implement __eq__\n assert list(res) == list(target)\n\n\n@pytest.mark.parametrize('validator, arg, exception_type',\n generate_validator_testcases(False))\ndef test_validator_invalid(validator, arg, exception_type):\n with pytest.raises(exception_type):\n validator(arg)\n\n\n@pytest.mark.parametrize('weight, parsed_weight', [\n ('bold', 'bold'),\n ('BOLD', ValueError), # weight is case-sensitive\n (100, 100),\n ('100', 100),\n (np.array(100), 100),\n # fractional fontweights are not defined. This should actually raise a\n # ValueError, but historically did not.\n (20.6, 20),\n ('20.6', ValueError),\n ([100], ValueError),\n])\ndef test_validate_fontweight(weight, parsed_weight):\n if parsed_weight is ValueError:\n with pytest.raises(ValueError):\n validate_fontweight(weight)\n else:\n assert validate_fontweight(weight) == parsed_weight\n\n\n@pytest.mark.parametrize('stretch, parsed_stretch', [\n ('expanded', 'expanded'),\n ('EXPANDED', ValueError), # stretch is case-sensitive\n (100, 100),\n ('100', 100),\n (np.array(100), 100),\n # fractional fontweights are not defined. This should actually raise a\n # ValueError, but historically did not.\n (20.6, 20),\n ('20.6', ValueError),\n ([100], ValueError),\n])\ndef test_validate_fontstretch(stretch, parsed_stretch):\n if parsed_stretch is ValueError:\n with pytest.raises(ValueError):\n validate_fontstretch(stretch)\n else:\n assert validate_fontstretch(stretch) == parsed_stretch\n\n\ndef test_keymaps():\n key_list = [k for k in mpl.rcParams if 'keymap' in k]\n for k in key_list:\n assert isinstance(mpl.rcParams[k], list)\n\n\ndef test_no_backend_reset_rccontext():\n assert mpl.rcParams['backend'] != 'module://aardvark'\n with mpl.rc_context():\n mpl.rcParams['backend'] = 'module://aardvark'\n assert mpl.rcParams['backend'] == 'module://aardvark'\n\n\ndef test_rcparams_reset_after_fail():\n # There was previously a bug that meant that if rc_context failed and\n # raised an exception due to issues in the supplied rc parameters, the\n # global rc parameters were left in a modified state.\n with mpl.rc_context(rc={'text.usetex': False}):\n assert mpl.rcParams['text.usetex'] is False\n with pytest.raises(KeyError):\n with mpl.rc_context(rc={'text.usetex': True, 'test.blah': True}):\n pass\n assert mpl.rcParams['text.usetex'] is False\n\n\n@pytest.mark.skipif(sys.platform != "linux", reason="Linux only")\ndef test_backend_fallback_headless_invalid_backend(tmp_path):\n env = {**os.environ,\n "DISPLAY": "", "WAYLAND_DISPLAY": "",\n "MPLBACKEND": "", "MPLCONFIGDIR": str(tmp_path)}\n # plotting should fail with the tkagg backend selected in a headless environment\n with pytest.raises(subprocess.CalledProcessError):\n subprocess_run_for_testing(\n [sys.executable, "-c",\n "import matplotlib;"\n "matplotlib.use('tkagg');"\n "import matplotlib.pyplot;"\n "matplotlib.pyplot.plot(42);"\n ],\n env=env, check=True, stderr=subprocess.DEVNULL)\n\n\n@pytest.mark.skipif(sys.platform != "linux", reason="Linux only")\ndef test_backend_fallback_headless_auto_backend(tmp_path):\n # specify a headless mpl environment, but request a graphical (tk) backend\n env = {**os.environ,\n "DISPLAY": "", "WAYLAND_DISPLAY": "",\n "MPLBACKEND": "TkAgg", "MPLCONFIGDIR": str(tmp_path)}\n\n # allow fallback to an available interactive backend explicitly in configuration\n rc_path = tmp_path / "matplotlibrc"\n rc_path.write_text("backend_fallback: true")\n\n # plotting should succeed, by falling back to use the generic agg backend\n backend = subprocess_run_for_testing(\n [sys.executable, "-c",\n "import matplotlib.pyplot;"\n "matplotlib.pyplot.plot(42);"\n "print(matplotlib.get_backend());"\n ],\n env=env, text=True, check=True, capture_output=True).stdout\n assert backend.strip().lower() == "agg"\n\n\n@pytest.mark.skipif(\n sys.platform == "linux" and not _c_internal_utils.xdisplay_is_valid(),\n reason="headless")\ndef test_backend_fallback_headful(tmp_path):\n if parse_version(pytest.__version__) >= parse_version('8.2.0'):\n pytest_kwargs = dict(exc_type=ImportError)\n else:\n pytest_kwargs = {}\n\n pytest.importorskip("tkinter", **pytest_kwargs)\n env = {**os.environ, "MPLBACKEND": "", "MPLCONFIGDIR": str(tmp_path)}\n backend = subprocess_run_for_testing(\n [sys.executable, "-c",\n "import matplotlib as mpl; "\n "sentinel = mpl.rcsetup._auto_backend_sentinel; "\n # Check that access on another instance does not resolve the sentinel.\n "assert mpl.RcParams({'backend': sentinel})['backend'] == sentinel; "\n "assert mpl.rcParams._get('backend') == sentinel; "\n "assert mpl.get_backend(auto_select=False) is None; "\n "import matplotlib.pyplot; "\n "print(matplotlib.get_backend())"],\n env=env, text=True, check=True, capture_output=True).stdout\n # The actual backend will depend on what's installed, but at least tkagg is\n # present.\n assert backend.strip().lower() != "agg"\n\n\ndef test_deprecation(monkeypatch):\n monkeypatch.setitem(\n mpl._deprecated_map, "patch.linewidth",\n ("0.0", "axes.linewidth", lambda old: 2 * old, lambda new: new / 2))\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n assert mpl.rcParams["patch.linewidth"] \\n == mpl.rcParams["axes.linewidth"] / 2\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n mpl.rcParams["patch.linewidth"] = 1\n assert mpl.rcParams["axes.linewidth"] == 2\n\n monkeypatch.setitem(\n mpl._deprecated_ignore_map, "patch.edgecolor",\n ("0.0", "axes.edgecolor"))\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n assert mpl.rcParams["patch.edgecolor"] \\n == mpl.rcParams["axes.edgecolor"]\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n mpl.rcParams["patch.edgecolor"] = "#abcd"\n assert mpl.rcParams["axes.edgecolor"] != "#abcd"\n\n monkeypatch.setitem(\n mpl._deprecated_ignore_map, "patch.force_edgecolor",\n ("0.0", None))\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n assert mpl.rcParams["patch.force_edgecolor"] is None\n\n monkeypatch.setitem(\n mpl._deprecated_remain_as_none, "svg.hashsalt",\n ("0.0",))\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n mpl.rcParams["svg.hashsalt"] = "foobar"\n assert mpl.rcParams["svg.hashsalt"] == "foobar" # Doesn't warn.\n mpl.rcParams["svg.hashsalt"] = None # Doesn't warn.\n\n mpl.rcParams.update(mpl.rcParams.copy()) # Doesn't warn.\n # Note that the warning suppression actually arises from the\n # iteration over the updater rcParams being protected by\n # suppress_matplotlib_deprecation_warning, rather than any explicit check.\n\n\n@pytest.mark.parametrize("value", [\n "best",\n 1,\n "1",\n (0.9, .7),\n (-0.9, .7),\n "(0.9, .7)"\n])\ndef test_rcparams_legend_loc(value):\n # rcParams['legend.loc'] should allow any of the following formats.\n # if any of these are not allowed, an exception will be raised\n # test for gh issue #22338\n mpl.rcParams["legend.loc"] = value\n\n\n@pytest.mark.parametrize("value", [\n "best",\n 1,\n (0.9, .7),\n (-0.9, .7),\n])\ndef test_rcparams_legend_loc_from_file(tmp_path, value):\n # rcParams['legend.loc'] should be settable from matplotlibrc.\n # if any of these are not allowed, an exception will be raised.\n # test for gh issue #22338\n rc_path = tmp_path / "matplotlibrc"\n rc_path.write_text(f"legend.loc: {value}")\n\n with mpl.rc_context(fname=rc_path):\n assert mpl.rcParams["legend.loc"] == value\n\n\n@pytest.mark.parametrize("value", [(1, 2, 3), '1, 2, 3', '(1, 2, 3)'])\ndef test_validate_sketch(value):\n mpl.rcParams["path.sketch"] = value\n assert mpl.rcParams["path.sketch"] == (1, 2, 3)\n assert validate_sketch(value) == (1, 2, 3)\n\n\n@pytest.mark.parametrize("value", [1, '1', '1 2 3'])\ndef test_validate_sketch_error(value):\n with pytest.raises(ValueError, match="scale, length, randomness"):\n validate_sketch(value)\n with pytest.raises(ValueError, match="scale, length, randomness"):\n mpl.rcParams["path.sketch"] = value\n\n\n@pytest.mark.parametrize("value", ['1, 2, 3', '(1,2,3)'])\ndef test_rcparams_path_sketch_from_file(tmp_path, value):\n rc_path = tmp_path / "matplotlibrc"\n rc_path.write_text(f"path.sketch: {value}")\n with mpl.rc_context(fname=rc_path):\n assert mpl.rcParams["path.sketch"] == (1, 2, 3)\n | .venv\Lib\site-packages\matplotlib\tests\test_rcparams.py | test_rcparams.py | Python | 26,506 | 0.95 | 0.09824 | 0.083752 | node-utils | 798 | 2024-08-11T08:50:02.513212 | MIT | true | c1d539f2e29f257c40c5c82836f2344c |
import pytest\nfrom numpy.testing import assert_allclose, assert_array_equal\n\nfrom matplotlib.sankey import Sankey\nfrom matplotlib.testing.decorators import check_figures_equal\n\n\ndef test_sankey():\n # lets just create a sankey instance and check the code runs\n sankey = Sankey()\n sankey.add()\n\n\ndef test_label():\n s = Sankey(flows=[0.25], labels=['First'], orientations=[-1])\n assert s.diagrams[0].texts[0].get_text() == 'First\n0.25'\n\n\ndef test_format_using_callable():\n # test using callable by slightly incrementing above label example\n\n def show_three_decimal_places(value):\n return f'{value:.3f}'\n\n s = Sankey(flows=[0.25], labels=['First'], orientations=[-1],\n format=show_three_decimal_places)\n\n assert s.diagrams[0].texts[0].get_text() == 'First\n0.250'\n\n\n@pytest.mark.parametrize('kwargs, msg', (\n ({'gap': -1}, "'gap' is negative"),\n ({'gap': 1, 'radius': 2}, "'radius' is greater than 'gap'"),\n ({'head_angle': -1}, "'head_angle' is negative"),\n ({'tolerance': -1}, "'tolerance' is negative"),\n ({'flows': [1, -1], 'orientations': [-1, 0, 1]},\n r"The shapes of 'flows' \(2,\) and 'orientations'"),\n ({'flows': [1, -1], 'labels': ['a', 'b', 'c']},\n r"The shapes of 'flows' \(2,\) and 'labels'"),\n ))\ndef test_sankey_errors(kwargs, msg):\n with pytest.raises(ValueError, match=msg):\n Sankey(**kwargs)\n\n\n@pytest.mark.parametrize('kwargs, msg', (\n ({'trunklength': -1}, "'trunklength' is negative"),\n ({'flows': [0.2, 0.3], 'prior': 0}, "The scaled sum of the connected"),\n ({'prior': -1}, "The index of the prior diagram is negative"),\n ({'prior': 1}, "The index of the prior diagram is 1"),\n ({'connect': (-1, 1), 'prior': 0}, "At least one of the connection"),\n ({'connect': (2, 1), 'prior': 0}, "The connection index to the source"),\n ({'connect': (1, 3), 'prior': 0}, "The connection index to this dia"),\n ({'connect': (1, 1), 'prior': 0, 'flows': [-0.2, 0.2],\n 'orientations': [2]}, "The value of orientations"),\n ({'connect': (1, 1), 'prior': 0, 'flows': [-0.2, 0.2],\n 'pathlengths': [2]}, "The lengths of 'flows'"),\n ))\ndef test_sankey_add_errors(kwargs, msg):\n sankey = Sankey()\n with pytest.raises(ValueError, match=msg):\n sankey.add(flows=[0.2, -0.2])\n sankey.add(**kwargs)\n\n\ndef test_sankey2():\n s = Sankey(flows=[0.25, -0.25, 0.5, -0.5], labels=['Foo'],\n orientations=[-1], unit='Bar')\n sf = s.finish()\n assert_array_equal(sf[0].flows, [0.25, -0.25, 0.5, -0.5])\n assert sf[0].angles == [1, 3, 1, 3]\n assert all([text.get_text()[0:3] == 'Foo' for text in sf[0].texts])\n assert all([text.get_text()[-3:] == 'Bar' for text in sf[0].texts])\n assert sf[0].text.get_text() == ''\n assert_allclose(sf[0].tips,\n [(-1.375, -0.52011255),\n (1.375, -0.75506044),\n (-0.75, -0.41522509),\n (0.75, -0.8599479)])\n\n s = Sankey(flows=[0.25, -0.25, 0, 0.5, -0.5], labels=['Foo'],\n orientations=[-1], unit='Bar')\n sf = s.finish()\n assert_array_equal(sf[0].flows, [0.25, -0.25, 0, 0.5, -0.5])\n assert sf[0].angles == [1, 3, None, 1, 3]\n assert_allclose(sf[0].tips,\n [(-1.375, -0.52011255),\n (1.375, -0.75506044),\n (0, 0),\n (-0.75, -0.41522509),\n (0.75, -0.8599479)])\n\n\n@check_figures_equal(extensions=['png'])\ndef test_sankey3(fig_test, fig_ref):\n ax_test = fig_test.gca()\n s_test = Sankey(ax=ax_test, flows=[0.25, -0.25, -0.25, 0.25, 0.5, -0.5],\n orientations=[1, -1, 1, -1, 0, 0])\n s_test.finish()\n\n ax_ref = fig_ref.gca()\n s_ref = Sankey(ax=ax_ref)\n s_ref.add(flows=[0.25, -0.25, -0.25, 0.25, 0.5, -0.5],\n orientations=[1, -1, 1, -1, 0, 0])\n s_ref.finish()\n | .venv\Lib\site-packages\matplotlib\tests\test_sankey.py | test_sankey.py | Python | 3,900 | 0.95 | 0.095238 | 0.023529 | node-utils | 81 | 2025-01-20T10:11:20.448586 | Apache-2.0 | true | 875eed882b8dad64d79dc49b01962424 |
import copy\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.scale import (\n AsinhScale, AsinhTransform,\n LogTransform, InvertedLogTransform,\n SymmetricalLogTransform)\nimport matplotlib.scale as mscale\nfrom matplotlib.ticker import AsinhLocator, LogFormatterSciNotation\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\n\nimport numpy as np\nfrom numpy.testing import assert_allclose\nimport io\nimport pytest\n\n\n@check_figures_equal(extensions=['png'])\ndef test_log_scales(fig_test, fig_ref):\n ax_test = fig_test.add_subplot(122, yscale='log', xscale='symlog')\n ax_test.axvline(24.1)\n ax_test.axhline(24.1)\n xlim = ax_test.get_xlim()\n ylim = ax_test.get_ylim()\n ax_ref = fig_ref.add_subplot(122, yscale='log', xscale='symlog')\n ax_ref.set(xlim=xlim, ylim=ylim)\n ax_ref.plot([24.1, 24.1], ylim, 'b')\n ax_ref.plot(xlim, [24.1, 24.1], 'b')\n\n\ndef test_symlog_mask_nan():\n # Use a transform round-trip to verify that the forward and inverse\n # transforms work, and that they respect nans and/or masking.\n slt = SymmetricalLogTransform(10, 2, 1)\n slti = slt.inverted()\n\n x = np.arange(-1.5, 5, 0.5)\n out = slti.transform_non_affine(slt.transform_non_affine(x))\n assert_allclose(out, x)\n assert type(out) is type(x)\n\n x[4] = np.nan\n out = slti.transform_non_affine(slt.transform_non_affine(x))\n assert_allclose(out, x)\n assert type(out) is type(x)\n\n x = np.ma.array(x)\n out = slti.transform_non_affine(slt.transform_non_affine(x))\n assert_allclose(out, x)\n assert type(out) is type(x)\n\n x[3] = np.ma.masked\n out = slti.transform_non_affine(slt.transform_non_affine(x))\n assert_allclose(out, x)\n assert type(out) is type(x)\n\n\n@image_comparison(['logit_scales.png'], remove_text=True)\ndef test_logit_scales():\n fig, ax = plt.subplots()\n\n # Typical extinction curve for logit\n x = np.array([0.001, 0.003, 0.01, 0.03, 0.1, 0.2, 0.3, 0.4, 0.5,\n 0.6, 0.7, 0.8, 0.9, 0.97, 0.99, 0.997, 0.999])\n y = 1.0 / x\n\n ax.plot(x, y)\n ax.set_xscale('logit')\n ax.grid(True)\n bbox = ax.get_tightbbox(fig.canvas.get_renderer())\n assert np.isfinite(bbox.x0)\n assert np.isfinite(bbox.y0)\n\n\ndef test_log_scatter():\n """Issue #1799"""\n fig, ax = plt.subplots(1)\n\n x = np.arange(10)\n y = np.arange(10) - 1\n\n ax.scatter(x, y)\n\n buf = io.BytesIO()\n fig.savefig(buf, format='pdf')\n\n buf = io.BytesIO()\n fig.savefig(buf, format='eps')\n\n buf = io.BytesIO()\n fig.savefig(buf, format='svg')\n\n\ndef test_logscale_subs():\n fig, ax = plt.subplots()\n ax.set_yscale('log', subs=np.array([2, 3, 4]))\n # force draw\n fig.canvas.draw()\n\n\n@image_comparison(['logscale_mask.png'], remove_text=True)\ndef test_logscale_mask():\n # Check that zero values are masked correctly on log scales.\n # See github issue 8045\n xs = np.linspace(0, 50, 1001)\n\n fig, ax = plt.subplots()\n ax.plot(np.exp(-xs**2))\n fig.canvas.draw()\n ax.set(yscale="log")\n\n\ndef test_extra_kwargs_raise():\n fig, ax = plt.subplots()\n\n for scale in ['linear', 'log', 'symlog']:\n with pytest.raises(TypeError):\n ax.set_yscale(scale, foo='mask')\n\n\ndef test_logscale_invert_transform():\n fig, ax = plt.subplots()\n ax.set_yscale('log')\n # get transformation from data to axes\n tform = (ax.transAxes + ax.transData.inverted()).inverted()\n\n # direct test of log transform inversion\n inverted_transform = LogTransform(base=2).inverted()\n assert isinstance(inverted_transform, InvertedLogTransform)\n assert inverted_transform.base == 2\n\n\ndef test_logscale_transform_repr():\n fig, ax = plt.subplots()\n ax.set_yscale('log')\n repr(ax.transData)\n repr(LogTransform(10, nonpositive='clip'))\n\n\n@image_comparison(['logscale_nonpos_values.png'],\n remove_text=True, tol=0.02, style='mpl20')\ndef test_logscale_nonpos_values():\n np.random.seed(19680801)\n xs = np.random.normal(size=int(1e3))\n fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)\n ax1.hist(xs, range=(-5, 5), bins=10)\n ax1.set_yscale('log')\n ax2.hist(xs, range=(-5, 5), bins=10)\n ax2.set_yscale('log', nonpositive='mask')\n\n xdata = np.arange(0, 10, 0.01)\n ydata = np.exp(-xdata)\n edata = 0.2*(10-xdata)*np.cos(5*xdata)*np.exp(-xdata)\n\n ax3.fill_between(xdata, ydata - edata, ydata + edata)\n ax3.set_yscale('log')\n\n x = np.logspace(-1, 1)\n y = x ** 3\n yerr = x**2\n ax4.errorbar(x, y, yerr=yerr)\n\n ax4.set_yscale('log')\n ax4.set_xscale('log')\n\n\ndef test_invalid_log_lims():\n # Check that invalid log scale limits are ignored\n fig, ax = plt.subplots()\n ax.scatter(range(0, 4), range(0, 4))\n\n ax.set_xscale('log')\n original_xlim = ax.get_xlim()\n with pytest.warns(UserWarning):\n ax.set_xlim(left=0)\n assert ax.get_xlim() == original_xlim\n with pytest.warns(UserWarning):\n ax.set_xlim(right=-1)\n assert ax.get_xlim() == original_xlim\n\n ax.set_yscale('log')\n original_ylim = ax.get_ylim()\n with pytest.warns(UserWarning):\n ax.set_ylim(bottom=0)\n assert ax.get_ylim() == original_ylim\n with pytest.warns(UserWarning):\n ax.set_ylim(top=-1)\n assert ax.get_ylim() == original_ylim\n\n\n@image_comparison(['function_scales.png'], remove_text=True, style='mpl20')\ndef test_function_scale():\n def inverse(x):\n return x**2\n\n def forward(x):\n return x**(1/2)\n\n fig, ax = plt.subplots()\n\n x = np.arange(1, 1000)\n\n ax.plot(x, x)\n ax.set_xscale('function', functions=(forward, inverse))\n ax.set_xlim(1, 1000)\n\n\ndef test_pass_scale():\n # test passing a scale object works...\n fig, ax = plt.subplots()\n scale = mscale.LogScale(axis=None)\n ax.set_xscale(scale)\n scale = mscale.LogScale(axis=None)\n ax.set_yscale(scale)\n assert ax.xaxis.get_scale() == 'log'\n assert ax.yaxis.get_scale() == 'log'\n\n\ndef test_scale_deepcopy():\n sc = mscale.LogScale(axis='x', base=10)\n sc2 = copy.deepcopy(sc)\n assert str(sc.get_transform()) == str(sc2.get_transform())\n assert sc._transform is not sc2._transform\n\n\nclass TestAsinhScale:\n def test_transforms(self):\n a0 = 17.0\n a = np.linspace(-50, 50, 100)\n\n forward = AsinhTransform(a0)\n inverse = forward.inverted()\n invinv = inverse.inverted()\n\n a_forward = forward.transform_non_affine(a)\n a_inverted = inverse.transform_non_affine(a_forward)\n assert_allclose(a_inverted, a)\n\n a_invinv = invinv.transform_non_affine(a)\n assert_allclose(a_invinv, a0 * np.arcsinh(a / a0))\n\n def test_init(self):\n fig, ax = plt.subplots()\n\n s = AsinhScale(axis=None, linear_width=23.0)\n assert s.linear_width == 23\n assert s._base == 10\n assert s._subs == (2, 5)\n\n tx = s.get_transform()\n assert isinstance(tx, AsinhTransform)\n assert tx.linear_width == s.linear_width\n\n def test_base_init(self):\n fig, ax = plt.subplots()\n\n s3 = AsinhScale(axis=None, base=3)\n assert s3._base == 3\n assert s3._subs == (2,)\n\n s7 = AsinhScale(axis=None, base=7, subs=(2, 4))\n assert s7._base == 7\n assert s7._subs == (2, 4)\n\n def test_fmtloc(self):\n class DummyAxis:\n def __init__(self):\n self.fields = {}\n def set(self, **kwargs):\n self.fields.update(**kwargs)\n def set_major_formatter(self, f):\n self.fields['major_formatter'] = f\n\n ax0 = DummyAxis()\n s0 = AsinhScale(axis=ax0, base=0)\n s0.set_default_locators_and_formatters(ax0)\n assert isinstance(ax0.fields['major_locator'], AsinhLocator)\n assert isinstance(ax0.fields['major_formatter'], str)\n\n ax5 = DummyAxis()\n s7 = AsinhScale(axis=ax5, base=5)\n s7.set_default_locators_and_formatters(ax5)\n assert isinstance(ax5.fields['major_locator'], AsinhLocator)\n assert isinstance(ax5.fields['major_formatter'],\n LogFormatterSciNotation)\n\n def test_bad_scale(self):\n fig, ax = plt.subplots()\n\n with pytest.raises(ValueError):\n AsinhScale(axis=None, linear_width=0)\n with pytest.raises(ValueError):\n AsinhScale(axis=None, linear_width=-1)\n s0 = AsinhScale(axis=None, )\n s1 = AsinhScale(axis=None, linear_width=3.0)\n | .venv\Lib\site-packages\matplotlib\tests\test_scale.py | test_scale.py | Python | 8,429 | 0.95 | 0.098305 | 0.044444 | vue-tools | 740 | 2023-12-26T22:15:48.566688 | MIT | true | aa1337ed9be775be3c6f8987692fb55b |
import base64\nimport io\nimport platform\n\nimport numpy as np\nfrom numpy.testing import assert_array_almost_equal, assert_array_equal\n\nimport pytest\n\nfrom matplotlib.testing.decorators import (\n check_figures_equal, image_comparison, remove_ticks_and_titles)\nimport matplotlib.pyplot as plt\n\nfrom matplotlib import patches, transforms\nfrom matplotlib.path import Path\n\n\n# NOTE: All of these tests assume that path.simplify is set to True\n# (the default)\n\n@image_comparison(['clipping'], remove_text=True)\ndef test_clipping():\n t = np.arange(0.0, 2.0, 0.01)\n s = np.sin(2*np.pi*t)\n\n fig, ax = plt.subplots()\n ax.plot(t, s, linewidth=1.0)\n ax.set_ylim((-0.20, -0.28))\n\n\n@image_comparison(['overflow'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.007)\ndef test_overflow():\n x = np.array([1.0, 2.0, 3.0, 2.0e5])\n y = np.arange(len(x))\n\n fig, ax = plt.subplots()\n ax.plot(x, y)\n ax.set_xlim(2, 6)\n\n\n@image_comparison(['clipping_diamond'], remove_text=True)\ndef test_diamond():\n x = np.array([0.0, 1.0, 0.0, -1.0, 0.0])\n y = np.array([1.0, 0.0, -1.0, 0.0, 1.0])\n\n fig, ax = plt.subplots()\n ax.plot(x, y)\n ax.set_xlim(-0.6, 0.6)\n ax.set_ylim(-0.6, 0.6)\n\n\ndef test_clipping_out_of_bounds():\n # Should work on a Path *without* codes.\n path = Path([(0, 0), (1, 2), (2, 1)])\n simplified = path.cleaned(clip=(10, 10, 20, 20))\n assert_array_equal(simplified.vertices, [(0, 0)])\n assert simplified.codes == [Path.STOP]\n\n # Should work on a Path *with* codes, and no curves.\n path = Path([(0, 0), (1, 2), (2, 1)],\n [Path.MOVETO, Path.LINETO, Path.LINETO])\n simplified = path.cleaned(clip=(10, 10, 20, 20))\n assert_array_equal(simplified.vertices, [(0, 0)])\n assert simplified.codes == [Path.STOP]\n\n # A Path with curves does not do any clipping yet.\n path = Path([(0, 0), (1, 2), (2, 3)],\n [Path.MOVETO, Path.CURVE3, Path.CURVE3])\n simplified = path.cleaned()\n simplified_clipped = path.cleaned(clip=(10, 10, 20, 20))\n assert_array_equal(simplified.vertices, simplified_clipped.vertices)\n assert_array_equal(simplified.codes, simplified_clipped.codes)\n\n\ndef test_noise():\n np.random.seed(0)\n x = np.random.uniform(size=50000) * 50\n\n fig, ax = plt.subplots()\n p1 = ax.plot(x, solid_joinstyle='round', linewidth=2.0)\n\n # Ensure that the path's transform takes the new axes limits into account.\n fig.canvas.draw()\n path = p1[0].get_path()\n transform = p1[0].get_transform()\n path = transform.transform_path(path)\n simplified = path.cleaned(simplify=True)\n\n assert simplified.vertices.size == 25512\n\n\ndef test_antiparallel_simplification():\n def _get_simplified(x, y):\n fig, ax = plt.subplots()\n p1 = ax.plot(x, y)\n\n path = p1[0].get_path()\n transform = p1[0].get_transform()\n path = transform.transform_path(path)\n simplified = path.cleaned(simplify=True)\n simplified = transform.inverted().transform_path(simplified)\n\n return simplified\n\n # test ending on a maximum\n x = [0, 0, 0, 0, 0, 1]\n y = [.5, 1, -1, 1, 2, .5]\n\n simplified = _get_simplified(x, y)\n\n assert_array_almost_equal([[0., 0.5],\n [0., -1.],\n [0., 2.],\n [1., 0.5]],\n simplified.vertices[:-2, :])\n\n # test ending on a minimum\n x = [0, 0, 0, 0, 0, 1]\n y = [.5, 1, -1, 1, -2, .5]\n\n simplified = _get_simplified(x, y)\n\n assert_array_almost_equal([[0., 0.5],\n [0., 1.],\n [0., -2.],\n [1., 0.5]],\n simplified.vertices[:-2, :])\n\n # test ending in between\n x = [0, 0, 0, 0, 0, 1]\n y = [.5, 1, -1, 1, 0, .5]\n\n simplified = _get_simplified(x, y)\n\n assert_array_almost_equal([[0., 0.5],\n [0., 1.],\n [0., -1.],\n [0., 0.],\n [1., 0.5]],\n simplified.vertices[:-2, :])\n\n # test no anti-parallel ending at max\n x = [0, 0, 0, 0, 0, 1]\n y = [.5, 1, 2, 1, 3, .5]\n\n simplified = _get_simplified(x, y)\n\n assert_array_almost_equal([[0., 0.5],\n [0., 3.],\n [1., 0.5]],\n simplified.vertices[:-2, :])\n\n # test no anti-parallel ending in middle\n x = [0, 0, 0, 0, 0, 1]\n y = [.5, 1, 2, 1, 1, .5]\n\n simplified = _get_simplified(x, y)\n\n assert_array_almost_equal([[0., 0.5],\n [0., 2.],\n [0., 1.],\n [1., 0.5]],\n simplified.vertices[:-2, :])\n\n\n# Only consider angles in 0 <= angle <= pi/2, otherwise\n# using min/max will get the expected results out of order:\n# min/max for simplification code depends on original vector,\n# and if angle is outside above range then simplification\n# min/max will be opposite from actual min/max.\n@pytest.mark.parametrize('angle', [0, np.pi/4, np.pi/3, np.pi/2])\n@pytest.mark.parametrize('offset', [0, .5])\ndef test_angled_antiparallel(angle, offset):\n scale = 5\n np.random.seed(19680801)\n # get 15 random offsets\n # TODO: guarantee offset > 0 results in some offsets < 0\n vert_offsets = (np.random.rand(15) - offset) * scale\n # always start at 0 so rotation makes sense\n vert_offsets[0] = 0\n # always take the first step the same direction\n vert_offsets[1] = 1\n # compute points along a diagonal line\n x = np.sin(angle) * vert_offsets\n y = np.cos(angle) * vert_offsets\n\n # will check these later\n x_max = x[1:].max()\n x_min = x[1:].min()\n\n y_max = y[1:].max()\n y_min = y[1:].min()\n\n if offset > 0:\n p_expected = Path([[0, 0],\n [x_max, y_max],\n [x_min, y_min],\n [x[-1], y[-1]],\n [0, 0]],\n codes=[1, 2, 2, 2, 0])\n\n else:\n p_expected = Path([[0, 0],\n [x_max, y_max],\n [x[-1], y[-1]],\n [0, 0]],\n codes=[1, 2, 2, 0])\n\n p = Path(np.vstack([x, y]).T)\n p2 = p.cleaned(simplify=True)\n\n assert_array_almost_equal(p_expected.vertices,\n p2.vertices)\n assert_array_equal(p_expected.codes, p2.codes)\n\n\ndef test_sine_plus_noise():\n np.random.seed(0)\n x = (np.sin(np.linspace(0, np.pi * 2.0, 50000)) +\n np.random.uniform(size=50000) * 0.01)\n\n fig, ax = plt.subplots()\n p1 = ax.plot(x, solid_joinstyle='round', linewidth=2.0)\n\n # Ensure that the path's transform takes the new axes limits into account.\n fig.canvas.draw()\n path = p1[0].get_path()\n transform = p1[0].get_transform()\n path = transform.transform_path(path)\n simplified = path.cleaned(simplify=True)\n\n assert simplified.vertices.size == 25240\n\n\n@image_comparison(['simplify_curve'], remove_text=True, tol=0.017)\ndef test_simplify_curve():\n pp1 = patches.PathPatch(\n Path([(0, 0), (1, 0), (1, 1), (np.nan, 1), (0, 0), (2, 0), (2, 2),\n (0, 0)],\n [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CURVE3,\n Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY]),\n fc="none")\n\n fig, ax = plt.subplots()\n ax.add_patch(pp1)\n ax.set_xlim((0, 2))\n ax.set_ylim((0, 2))\n\n\n@check_figures_equal()\ndef test_closed_path_nan_removal(fig_test, fig_ref):\n ax_test = fig_test.subplots(2, 2).flatten()\n ax_ref = fig_ref.subplots(2, 2).flatten()\n\n # NaN on the first point also removes the last point, because it's closed.\n path = Path(\n [[-3, np.nan], [3, -3], [3, 3], [-3, 3], [-3, -3]],\n [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])\n ax_test[0].add_patch(patches.PathPatch(path, facecolor='none'))\n path = Path(\n [[-3, np.nan], [3, -3], [3, 3], [-3, 3], [-3, np.nan]],\n [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO])\n ax_ref[0].add_patch(patches.PathPatch(path, facecolor='none'))\n\n # NaN on second-last point should not re-close.\n path = Path(\n [[-2, -2], [2, -2], [2, 2], [-2, np.nan], [-2, -2]],\n [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])\n ax_test[0].add_patch(patches.PathPatch(path, facecolor='none'))\n path = Path(\n [[-2, -2], [2, -2], [2, 2], [-2, np.nan], [-2, -2]],\n [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO])\n ax_ref[0].add_patch(patches.PathPatch(path, facecolor='none'))\n\n # Test multiple loops in a single path (with same paths as above).\n path = Path(\n [[-3, np.nan], [3, -3], [3, 3], [-3, 3], [-3, -3],\n [-2, -2], [2, -2], [2, 2], [-2, np.nan], [-2, -2]],\n [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY,\n Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])\n ax_test[1].add_patch(patches.PathPatch(path, facecolor='none'))\n path = Path(\n [[-3, np.nan], [3, -3], [3, 3], [-3, 3], [-3, np.nan],\n [-2, -2], [2, -2], [2, 2], [-2, np.nan], [-2, -2]],\n [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO,\n Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO])\n ax_ref[1].add_patch(patches.PathPatch(path, facecolor='none'))\n\n # NaN in first point of CURVE3 should not re-close, and hide entire curve.\n path = Path(\n [[-1, -1], [1, -1], [1, np.nan], [0, 1], [-1, 1], [-1, -1]],\n [Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO,\n Path.CLOSEPOLY])\n ax_test[2].add_patch(patches.PathPatch(path, facecolor='none'))\n path = Path(\n [[-1, -1], [1, -1], [1, np.nan], [0, 1], [-1, 1], [-1, -1]],\n [Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO,\n Path.CLOSEPOLY])\n ax_ref[2].add_patch(patches.PathPatch(path, facecolor='none'))\n\n # NaN in second point of CURVE3 should not re-close, and hide entire curve\n # plus next line segment.\n path = Path(\n [[-3, -3], [3, -3], [3, 0], [0, np.nan], [-3, 3], [-3, -3]],\n [Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO,\n Path.LINETO])\n ax_test[2].add_patch(patches.PathPatch(path, facecolor='none'))\n path = Path(\n [[-3, -3], [3, -3], [3, 0], [0, np.nan], [-3, 3], [-3, -3]],\n [Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO,\n Path.LINETO])\n ax_ref[2].add_patch(patches.PathPatch(path, facecolor='none'))\n\n # NaN in first point of CURVE4 should not re-close, and hide entire curve.\n path = Path(\n [[-1, -1], [1, -1], [1, np.nan], [0, 0], [0, 1], [-1, 1], [-1, -1]],\n [Path.MOVETO, Path.LINETO, Path.CURVE4, Path.CURVE4, Path.CURVE4,\n Path.LINETO, Path.CLOSEPOLY])\n ax_test[3].add_patch(patches.PathPatch(path, facecolor='none'))\n path = Path(\n [[-1, -1], [1, -1], [1, np.nan], [0, 0], [0, 1], [-1, 1], [-1, -1]],\n [Path.MOVETO, Path.LINETO, Path.CURVE4, Path.CURVE4, Path.CURVE4,\n Path.LINETO, Path.CLOSEPOLY])\n ax_ref[3].add_patch(patches.PathPatch(path, facecolor='none'))\n\n # NaN in second point of CURVE4 should not re-close, and hide entire curve.\n path = Path(\n [[-2, -2], [2, -2], [2, 0], [0, np.nan], [0, 2], [-2, 2], [-2, -2]],\n [Path.MOVETO, Path.LINETO, Path.CURVE4, Path.CURVE4, Path.CURVE4,\n Path.LINETO, Path.LINETO])\n ax_test[3].add_patch(patches.PathPatch(path, facecolor='none'))\n path = Path(\n [[-2, -2], [2, -2], [2, 0], [0, np.nan], [0, 2], [-2, 2], [-2, -2]],\n [Path.MOVETO, Path.LINETO, Path.CURVE4, Path.CURVE4, Path.CURVE4,\n Path.LINETO, Path.LINETO])\n ax_ref[3].add_patch(patches.PathPatch(path, facecolor='none'))\n\n # NaN in third point of CURVE4 should not re-close, and hide entire curve\n # plus next line segment.\n path = Path(\n [[-3, -3], [3, -3], [3, 0], [0, 0], [0, np.nan], [-3, 3], [-3, -3]],\n [Path.MOVETO, Path.LINETO, Path.CURVE4, Path.CURVE4, Path.CURVE4,\n Path.LINETO, Path.LINETO])\n ax_test[3].add_patch(patches.PathPatch(path, facecolor='none'))\n path = Path(\n [[-3, -3], [3, -3], [3, 0], [0, 0], [0, np.nan], [-3, 3], [-3, -3]],\n [Path.MOVETO, Path.LINETO, Path.CURVE4, Path.CURVE4, Path.CURVE4,\n Path.LINETO, Path.LINETO])\n ax_ref[3].add_patch(patches.PathPatch(path, facecolor='none'))\n\n # Keep everything clean.\n for ax in [*ax_test.flat, *ax_ref.flat]:\n ax.set(xlim=(-3.5, 3.5), ylim=(-3.5, 3.5))\n remove_ticks_and_titles(fig_test)\n remove_ticks_and_titles(fig_ref)\n\n\n@check_figures_equal()\ndef test_closed_path_clipping(fig_test, fig_ref):\n vertices = []\n for roll in range(8):\n offset = 0.1 * roll + 0.1\n\n # A U-like pattern.\n pattern = [\n [-0.5, 1.5], [-0.5, -0.5], [1.5, -0.5], [1.5, 1.5], # Outer square\n # With a notch in the top.\n [1 - offset / 2, 1.5], [1 - offset / 2, offset],\n [offset / 2, offset], [offset / 2, 1.5],\n ]\n\n # Place the initial/final point anywhere in/out of the clipping area.\n pattern = np.roll(pattern, roll, axis=0)\n pattern = np.concatenate((pattern, pattern[:1, :]))\n\n vertices.append(pattern)\n\n # Multiple subpaths are used here to ensure they aren't broken by closed\n # loop clipping.\n codes = np.full(len(vertices[0]), Path.LINETO)\n codes[0] = Path.MOVETO\n codes[-1] = Path.CLOSEPOLY\n codes = np.tile(codes, len(vertices))\n vertices = np.concatenate(vertices)\n\n fig_test.set_size_inches((5, 5))\n path = Path(vertices, codes)\n fig_test.add_artist(patches.PathPatch(path, facecolor='none'))\n\n # For reference, we draw the same thing, but unclosed by using a line to\n # the last point only.\n fig_ref.set_size_inches((5, 5))\n codes = codes.copy()\n codes[codes == Path.CLOSEPOLY] = Path.LINETO\n path = Path(vertices, codes)\n fig_ref.add_artist(patches.PathPatch(path, facecolor='none'))\n\n\n@image_comparison(['hatch_simplify'], remove_text=True)\ndef test_hatch():\n fig, ax = plt.subplots()\n ax.add_patch(plt.Rectangle((0, 0), 1, 1, fill=False, hatch="/"))\n ax.set_xlim((0.45, 0.55))\n ax.set_ylim((0.45, 0.55))\n\n\n@image_comparison(['fft_peaks'], remove_text=True)\ndef test_fft_peaks():\n fig, ax = plt.subplots()\n t = np.arange(65536)\n p1 = ax.plot(abs(np.fft.fft(np.sin(2*np.pi*.01*t)*np.blackman(len(t)))))\n\n # Ensure that the path's transform takes the new axes limits into account.\n fig.canvas.draw()\n path = p1[0].get_path()\n transform = p1[0].get_transform()\n path = transform.transform_path(path)\n simplified = path.cleaned(simplify=True)\n\n assert simplified.vertices.size == 36\n\n\ndef test_start_with_moveto():\n # Should be entirely clipped away to a single MOVETO\n data = b"""\nZwAAAAku+v9UAQAA+Tj6/z8CAADpQ/r/KAMAANlO+v8QBAAAyVn6//UEAAC6ZPr/2gUAAKpv+v+8\nBgAAm3r6/50HAACLhfr/ewgAAHyQ+v9ZCQAAbZv6/zQKAABepvr/DgsAAE+x+v/lCwAAQLz6/7wM\nAAAxx/r/kA0AACPS+v9jDgAAFN36/zQPAAAF6Pr/AxAAAPfy+v/QEAAA6f36/5wRAADbCPv/ZhIA\nAMwT+/8uEwAAvh77//UTAACwKfv/uRQAAKM0+/98FQAAlT/7/z0WAACHSvv//RYAAHlV+/+7FwAA\nbGD7/3cYAABea/v/MRkAAFF2+//pGQAARIH7/6AaAAA3jPv/VRsAACmX+/8JHAAAHKL7/7ocAAAP\nrfv/ah0AAAO4+/8YHgAA9sL7/8QeAADpzfv/bx8AANzY+/8YIAAA0OP7/78gAADD7vv/ZCEAALf5\n+/8IIgAAqwT8/6kiAACeD/z/SiMAAJIa/P/oIwAAhiX8/4QkAAB6MPz/HyUAAG47/P+4JQAAYkb8\n/1AmAABWUfz/5SYAAEpc/P95JwAAPmf8/wsoAAAzcvz/nCgAACd9/P8qKQAAHIj8/7cpAAAQk/z/\nQyoAAAWe/P/MKgAA+aj8/1QrAADus/z/2isAAOO+/P9eLAAA2Mn8/+AsAADM1Pz/YS0AAMHf/P/g\nLQAAtur8/10uAACr9fz/2C4AAKEA/f9SLwAAlgv9/8ovAACLFv3/QDAAAIAh/f+1MAAAdSz9/ycx\nAABrN/3/mDEAAGBC/f8IMgAAVk39/3UyAABLWP3/4TIAAEFj/f9LMwAANm79/7MzAAAsef3/GjQA\nACKE/f9+NAAAF4/9/+E0AAANmv3/QzUAAAOl/f+iNQAA+a/9/wA2AADvuv3/XDYAAOXF/f+2NgAA\n29D9/w83AADR2/3/ZjcAAMfm/f+7NwAAvfH9/w44AACz/P3/XzgAAKkH/v+vOAAAnxL+//04AACW\nHf7/SjkAAIwo/v+UOQAAgjP+/905AAB5Pv7/JDoAAG9J/v9pOgAAZVT+/606AABcX/7/7zoAAFJq\n/v8vOwAASXX+/207AAA/gP7/qjsAADaL/v/lOwAALZb+/x48AAAjof7/VTwAABqs/v+LPAAAELf+\n/788AAAHwv7/8TwAAP7M/v8hPQAA9df+/1A9AADr4v7/fT0AAOLt/v+oPQAA2fj+/9E9AADQA///\n+T0AAMYO//8fPgAAvRn//0M+AAC0JP//ZT4AAKsv//+GPgAAojr//6U+AACZRf//wj4AAJBQ///d\nPgAAh1v///c+AAB+Zv//Dz8AAHRx//8lPwAAa3z//zk/AABih///TD8AAFmS//9dPwAAUJ3//2w/\nAABHqP//ej8AAD6z//+FPwAANb7//48/AAAsyf//lz8AACPU//+ePwAAGt///6M/AAAR6v//pj8A\nAAj1//+nPwAA/////w=="""\n\n verts = np.frombuffer(base64.decodebytes(data), dtype='<i4')\n verts = verts.reshape((len(verts) // 2, 2))\n path = Path(verts)\n segs = path.iter_segments(transforms.IdentityTransform(),\n clip=(0.0, 0.0, 100.0, 100.0))\n segs = list(segs)\n assert len(segs) == 1\n assert segs[0][1] == Path.MOVETO\n\n\ndef test_throw_rendering_complexity_exceeded():\n plt.rcParams['path.simplify'] = False\n xx = np.arange(2_000_000)\n yy = np.random.rand(2_000_000)\n yy[1000] = np.nan\n\n fig, ax = plt.subplots()\n ax.plot(xx, yy)\n with pytest.raises(OverflowError):\n fig.savefig(io.BytesIO())\n\n\n@image_comparison(['clipper_edge'], remove_text=True)\ndef test_clipper():\n dat = (0, 1, 0, 2, 0, 3, 0, 4, 0, 5)\n fig = plt.figure(figsize=(2, 1))\n fig.subplots_adjust(left=0, bottom=0, wspace=0, hspace=0)\n\n ax = fig.add_axes((0, 0, 1.0, 1.0), ylim=(0, 5), autoscale_on=False)\n ax.plot(dat)\n ax.xaxis.set_major_locator(plt.MultipleLocator(1))\n ax.yaxis.set_major_locator(plt.MultipleLocator(1))\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n\n ax.set_xlim(5, 9)\n\n\n@image_comparison(['para_equal_perp'], remove_text=True)\ndef test_para_equal_perp():\n x = np.array([0, 1, 2, 1, 0, -1, 0, 1] + [1] * 128)\n y = np.array([1, 1, 2, 1, 0, -1, 0, 0] + [0] * 128)\n\n fig, ax = plt.subplots()\n ax.plot(x + 1, y + 1)\n ax.plot(x + 1, y + 1, 'ro')\n\n\n@image_comparison(['clipping_with_nans'])\ndef test_clipping_with_nans():\n x = np.linspace(0, 3.14 * 2, 3000)\n y = np.sin(x)\n x[::100] = np.nan\n\n fig, ax = plt.subplots()\n ax.plot(x, y)\n ax.set_ylim(-0.25, 0.25)\n\n\ndef test_clipping_full():\n p = Path([[1e30, 1e30]] * 5)\n simplified = list(p.iter_segments(clip=[0, 0, 100, 100]))\n assert simplified == []\n\n p = Path([[50, 40], [75, 65]], [1, 2])\n simplified = list(p.iter_segments(clip=[0, 0, 100, 100]))\n assert ([(list(x), y) for x, y in simplified] ==\n [([50, 40], 1), ([75, 65], 2)])\n\n p = Path([[50, 40]], [1])\n simplified = list(p.iter_segments(clip=[0, 0, 100, 100]))\n assert ([(list(x), y) for x, y in simplified] ==\n [([50, 40], 1)])\n\n\ndef test_simplify_closepoly():\n # The values of the vertices in a CLOSEPOLY should always be ignored,\n # in favor of the most recent MOVETO's vertex values\n paths = [Path([(1, 1), (2, 1), (2, 2), (np.nan, np.nan)],\n [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]),\n Path([(1, 1), (2, 1), (2, 2), (40, 50)],\n [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])]\n expected_path = Path([(1, 1), (2, 1), (2, 2), (1, 1), (1, 1), (0, 0)],\n [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,\n Path.LINETO, Path.STOP])\n\n for path in paths:\n simplified_path = path.cleaned(simplify=True)\n assert_array_equal(expected_path.vertices, simplified_path.vertices)\n assert_array_equal(expected_path.codes, simplified_path.codes)\n\n # test that a compound path also works\n path = Path([(1, 1), (2, 1), (2, 2), (np.nan, np.nan),\n (-1, 0), (-2, 0), (-2, 1), (np.nan, np.nan)],\n [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY,\n Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])\n expected_path = Path([(1, 1), (2, 1), (2, 2), (1, 1),\n (-1, 0), (-2, 0), (-2, 1), (-1, 0), (-1, 0), (0, 0)],\n [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,\n Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,\n Path.LINETO, Path.STOP])\n\n simplified_path = path.cleaned(simplify=True)\n assert_array_equal(expected_path.vertices, simplified_path.vertices)\n assert_array_equal(expected_path.codes, simplified_path.codes)\n\n # test for a path with an invalid MOVETO\n # CLOSEPOLY with an invalid MOVETO should be ignored\n path = Path([(1, 0), (1, -1), (2, -1),\n (np.nan, np.nan), (-1, -1), (-2, 1), (-1, 1),\n (2, 2), (0, -1)],\n [Path.MOVETO, Path.LINETO, Path.LINETO,\n Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,\n Path.CLOSEPOLY, Path.LINETO])\n expected_path = Path([(1, 0), (1, -1), (2, -1),\n (np.nan, np.nan), (-1, -1), (-2, 1), (-1, 1),\n (0, -1), (0, -1), (0, 0)],\n [Path.MOVETO, Path.LINETO, Path.LINETO,\n Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,\n Path.LINETO, Path.LINETO, Path.STOP])\n\n simplified_path = path.cleaned(simplify=True)\n assert_array_equal(expected_path.vertices, simplified_path.vertices)\n assert_array_equal(expected_path.codes, simplified_path.codes)\n | .venv\Lib\site-packages\matplotlib\tests\test_simplification.py | test_simplification.py | Python | 21,570 | 0.95 | 0.054291 | 0.104121 | awesome-app | 188 | 2025-03-13T15:44:37.252555 | BSD-3-Clause | true | c30798e776319eb19142a435969fb31b |
"""\nTesting that skewed Axes properly work.\n"""\n\nfrom contextlib import ExitStack\nimport itertools\nimport platform\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing.decorators import image_comparison\n\nfrom matplotlib.axes import Axes\nimport matplotlib.transforms as transforms\nimport matplotlib.axis as maxis\nimport matplotlib.spines as mspines\nimport matplotlib.patches as mpatch\nfrom matplotlib.projections import register_projection\n\n\n# The sole purpose of this class is to look at the upper, lower, or total\n# interval as appropriate and see what parts of the tick to draw, if any.\nclass SkewXTick(maxis.XTick):\n def draw(self, renderer):\n with ExitStack() as stack:\n for artist in [self.gridline, self.tick1line, self.tick2line,\n self.label1, self.label2]:\n stack.callback(artist.set_visible, artist.get_visible())\n needs_lower = transforms.interval_contains(\n self.axes.lower_xlim, self.get_loc())\n needs_upper = transforms.interval_contains(\n self.axes.upper_xlim, self.get_loc())\n self.tick1line.set_visible(\n self.tick1line.get_visible() and needs_lower)\n self.label1.set_visible(\n self.label1.get_visible() and needs_lower)\n self.tick2line.set_visible(\n self.tick2line.get_visible() and needs_upper)\n self.label2.set_visible(\n self.label2.get_visible() and needs_upper)\n super().draw(renderer)\n\n def get_view_interval(self):\n return self.axes.xaxis.get_view_interval()\n\n\n# This class exists to provide two separate sets of intervals to the tick,\n# as well as create instances of the custom tick\nclass SkewXAxis(maxis.XAxis):\n def _get_tick(self, major):\n return SkewXTick(self.axes, None, major=major)\n\n def get_view_interval(self):\n return self.axes.upper_xlim[0], self.axes.lower_xlim[1]\n\n\n# This class exists to calculate the separate data range of the\n# upper X-axis and draw the spine there. It also provides this range\n# to the X-axis artist for ticking and gridlines\nclass SkewSpine(mspines.Spine):\n def _adjust_location(self):\n pts = self._path.vertices\n if self.spine_type == 'top':\n pts[:, 0] = self.axes.upper_xlim\n else:\n pts[:, 0] = self.axes.lower_xlim\n\n\n# This class handles registration of the skew-xaxes as a projection as well\n# as setting up the appropriate transformations. It also overrides standard\n# spines and axes instances as appropriate.\nclass SkewXAxes(Axes):\n # The projection must specify a name. This will be used be the\n # user to select the projection, i.e. ``subplot(projection='skewx')``.\n name = 'skewx'\n\n def _init_axis(self):\n # Taken from Axes and modified to use our modified X-axis\n self.xaxis = SkewXAxis(self)\n self.spines.top.register_axis(self.xaxis)\n self.spines.bottom.register_axis(self.xaxis)\n self.yaxis = maxis.YAxis(self)\n self.spines.left.register_axis(self.yaxis)\n self.spines.right.register_axis(self.yaxis)\n\n def _gen_axes_spines(self):\n spines = {'top': SkewSpine.linear_spine(self, 'top'),\n 'bottom': mspines.Spine.linear_spine(self, 'bottom'),\n 'left': mspines.Spine.linear_spine(self, 'left'),\n 'right': mspines.Spine.linear_spine(self, 'right')}\n return spines\n\n def _set_lim_and_transforms(self):\n """\n This is called once when the plot is created to set up all the\n transforms for the data, text and grids.\n """\n rot = 30\n\n # Get the standard transform setup from the Axes base class\n super()._set_lim_and_transforms()\n\n # Need to put the skew in the middle, after the scale and limits,\n # but before the transAxes. This way, the skew is done in Axes\n # coordinates thus performing the transform around the proper origin\n # We keep the pre-transAxes transform around for other users, like the\n # spines for finding bounds\n self.transDataToAxes = (self.transScale +\n (self.transLimits +\n transforms.Affine2D().skew_deg(rot, 0)))\n\n # Create the full transform from Data to Pixels\n self.transData = self.transDataToAxes + self.transAxes\n\n # Blended transforms like this need to have the skewing applied using\n # both axes, in axes coords like before.\n self._xaxis_transform = (transforms.blended_transform_factory(\n self.transScale + self.transLimits,\n transforms.IdentityTransform()) +\n transforms.Affine2D().skew_deg(rot, 0)) + self.transAxes\n\n @property\n def lower_xlim(self):\n return self.axes.viewLim.intervalx\n\n @property\n def upper_xlim(self):\n pts = [[0., 1.], [1., 1.]]\n return self.transDataToAxes.inverted().transform(pts)[:, 0]\n\n\n# Now register the projection with matplotlib so the user can select\n# it.\nregister_projection(SkewXAxes)\n\n\n@image_comparison(['skew_axes.png'], remove_text=True)\ndef test_set_line_coll_dash_image():\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1, projection='skewx')\n ax.set_xlim(-50, 50)\n ax.set_ylim(50, -50)\n ax.grid(True)\n\n # An example of a slanted line at constant X\n ax.axvline(0, color='b')\n\n\n@image_comparison(['skew_rects.png'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.009)\ndef test_skew_rectangle():\n\n fix, axes = plt.subplots(5, 5, sharex=True, sharey=True, figsize=(8, 8))\n axes = axes.flat\n\n rotations = list(itertools.product([-3, -1, 0, 1, 3], repeat=2))\n\n axes[0].set_xlim([-3, 3])\n axes[0].set_ylim([-3, 3])\n axes[0].set_aspect('equal', share=True)\n\n for ax, (xrots, yrots) in zip(axes, rotations):\n xdeg, ydeg = 45 * xrots, 45 * yrots\n t = transforms.Affine2D().skew_deg(xdeg, ydeg)\n\n ax.set_title(f'Skew of {xdeg} in X and {ydeg} in Y')\n ax.add_patch(mpatch.Rectangle([-1, -1], 2, 2,\n transform=t + ax.transData,\n alpha=0.5, facecolor='coral'))\n\n plt.subplots_adjust(wspace=0, left=0.01, right=0.99, bottom=0.01, top=0.99)\n | .venv\Lib\site-packages\matplotlib\tests\test_skew.py | test_skew.py | Python | 6,349 | 0.95 | 0.176471 | 0.185185 | awesome-app | 166 | 2024-07-14T09:19:05.879185 | MIT | true | 5229866e641b430dacfa89a0182017a7 |
"""Tests for tinypages build using sphinx extensions."""\n\nimport filecmp\nimport os\nfrom pathlib import Path\nimport shutil\nimport sys\n\nfrom matplotlib.testing import subprocess_run_for_testing\nimport pytest\n\n\npytest.importorskip('sphinx', minversion='4.1.3')\n\n\ndef build_sphinx_html(source_dir, doctree_dir, html_dir, extra_args=None):\n # Build the pages with warnings turned into errors\n extra_args = [] if extra_args is None else extra_args\n cmd = [sys.executable, '-msphinx', '-W', '-b', 'html',\n '-d', str(doctree_dir), str(source_dir), str(html_dir), *extra_args]\n proc = subprocess_run_for_testing(\n cmd, capture_output=True, text=True,\n env={**os.environ, "MPLBACKEND": ""})\n out = proc.stdout\n err = proc.stderr\n\n assert proc.returncode == 0, \\n f"sphinx build failed with stdout:\n{out}\nstderr:\n{err}\n"\n if err:\n pytest.fail(f"sphinx build emitted the following warnings:\n{err}")\n\n assert html_dir.is_dir()\n\n\ndef test_tinypages(tmp_path):\n shutil.copytree(Path(__file__).parent / 'tinypages', tmp_path,\n dirs_exist_ok=True)\n html_dir = tmp_path / '_build' / 'html'\n img_dir = html_dir / '_images'\n doctree_dir = tmp_path / 'doctrees'\n # Build the pages with warnings turned into errors\n cmd = [sys.executable, '-msphinx', '-W', '-b', 'html',\n '-d', str(doctree_dir),\n str(Path(__file__).parent / 'tinypages'), str(html_dir)]\n # On CI, gcov emits warnings (due to agg headers being included with the\n # same name in multiple extension modules -- but we don't care about their\n # coverage anyways); hide them using GCOV_ERROR_FILE.\n proc = subprocess_run_for_testing(\n cmd, capture_output=True, text=True,\n env={**os.environ, "MPLBACKEND": "", "GCOV_ERROR_FILE": os.devnull}\n )\n out = proc.stdout\n err = proc.stderr\n\n # Build the pages with warnings turned into errors\n build_sphinx_html(tmp_path, doctree_dir, html_dir)\n\n def plot_file(num):\n return img_dir / f'some_plots-{num}.png'\n\n def plot_directive_file(num):\n # This is always next to the doctree dir.\n return doctree_dir.parent / 'plot_directive' / f'some_plots-{num}.png'\n\n range_10, range_6, range_4 = (plot_file(i) for i in range(1, 4))\n # Plot 5 is range(6) plot\n assert filecmp.cmp(range_6, plot_file(5))\n # Plot 7 is range(4) plot\n assert filecmp.cmp(range_4, plot_file(7))\n # Plot 11 is range(10) plot\n assert filecmp.cmp(range_10, plot_file(11))\n # Plot 12 uses the old range(10) figure and the new range(6) figure\n assert filecmp.cmp(range_10, plot_file('12_00'))\n assert filecmp.cmp(range_6, plot_file('12_01'))\n # Plot 13 shows close-figs in action\n assert filecmp.cmp(range_4, plot_file(13))\n # Plot 14 has included source\n html_contents = (html_dir / 'some_plots.html').read_text(encoding='utf-8')\n\n assert '# Only a comment' in html_contents\n # check plot defined in external file.\n assert filecmp.cmp(range_4, img_dir / 'range4.png')\n assert filecmp.cmp(range_6, img_dir / 'range6_range6.png')\n # check if figure caption made it into html file\n assert 'This is the caption for plot 15.' in html_contents\n # check if figure caption using :caption: made it into html file (because this plot\n # doesn't use srcset, the caption preserves newlines in the output.)\n assert 'Plot 17 uses the caption option,\nwith multi-line input.' in html_contents\n # check if figure alt text using :alt: made it into html file\n assert 'Plot 17 uses the alt option, with multi-line input.' in html_contents\n # check if figure caption made it into html file\n assert 'This is the caption for plot 18.' in html_contents\n # check if the custom classes made it into the html file\n assert 'plot-directive my-class my-other-class' in html_contents\n # check that the multi-image caption is applied twice\n assert html_contents.count('This caption applies to both plots.') == 2\n # Plot 21 is range(6) plot via an include directive. But because some of\n # the previous plots are repeated, the argument to plot_file() is only 17.\n assert filecmp.cmp(range_6, plot_file(17))\n # plot 22 is from the range6.py file again, but a different function\n assert filecmp.cmp(range_10, img_dir / 'range6_range10.png')\n\n # Modify the included plot\n contents = (tmp_path / 'included_plot_21.rst').read_bytes()\n contents = contents.replace(b'plt.plot(range(6))', b'plt.plot(range(4))')\n (tmp_path / 'included_plot_21.rst').write_bytes(contents)\n # Build the pages again and check that the modified file was updated\n modification_times = [plot_directive_file(i).stat().st_mtime\n for i in (1, 2, 3, 5)]\n build_sphinx_html(tmp_path, doctree_dir, html_dir)\n assert filecmp.cmp(range_4, plot_file(17))\n # Check that the plots in the plot_directive folder weren't changed.\n # (plot_directive_file(1) won't be modified, but it will be copied to html/\n # upon compilation, so plot_file(1) will be modified)\n assert plot_directive_file(1).stat().st_mtime == modification_times[0]\n assert plot_directive_file(2).stat().st_mtime == modification_times[1]\n assert plot_directive_file(3).stat().st_mtime == modification_times[2]\n assert filecmp.cmp(range_10, plot_file(1))\n assert filecmp.cmp(range_6, plot_file(2))\n assert filecmp.cmp(range_4, plot_file(3))\n # Make sure that figures marked with context are re-created (but that the\n # contents are the same)\n assert plot_directive_file(5).stat().st_mtime > modification_times[3]\n assert filecmp.cmp(range_6, plot_file(5))\n\n\ndef test_plot_html_show_source_link(tmp_path):\n parent = Path(__file__).parent\n shutil.copyfile(parent / 'tinypages/conf.py', tmp_path / 'conf.py')\n shutil.copytree(parent / 'tinypages/_static', tmp_path / '_static')\n doctree_dir = tmp_path / 'doctrees'\n (tmp_path / 'index.rst').write_text("""\n.. plot::\n\n plt.plot(range(2))\n""")\n # Make sure source scripts are created by default\n html_dir1 = tmp_path / '_build' / 'html1'\n build_sphinx_html(tmp_path, doctree_dir, html_dir1)\n assert len(list(html_dir1.glob("**/index-1.py"))) == 1\n # Make sure source scripts are NOT created when\n # plot_html_show_source_link` is False\n html_dir2 = tmp_path / '_build' / 'html2'\n build_sphinx_html(tmp_path, doctree_dir, html_dir2,\n extra_args=['-D', 'plot_html_show_source_link=0'])\n assert len(list(html_dir2.glob("**/index-1.py"))) == 0\n\n\n@pytest.mark.parametrize('plot_html_show_source_link', [0, 1])\ndef test_show_source_link_true(tmp_path, plot_html_show_source_link):\n # Test that a source link is generated if :show-source-link: is true,\n # whether or not plot_html_show_source_link is true.\n parent = Path(__file__).parent\n shutil.copyfile(parent / 'tinypages/conf.py', tmp_path / 'conf.py')\n shutil.copytree(parent / 'tinypages/_static', tmp_path / '_static')\n doctree_dir = tmp_path / 'doctrees'\n (tmp_path / 'index.rst').write_text("""\n.. plot::\n :show-source-link: true\n\n plt.plot(range(2))\n""")\n html_dir = tmp_path / '_build' / 'html'\n build_sphinx_html(tmp_path, doctree_dir, html_dir, extra_args=[\n '-D', f'plot_html_show_source_link={plot_html_show_source_link}'])\n assert len(list(html_dir.glob("**/index-1.py"))) == 1\n\n\n@pytest.mark.parametrize('plot_html_show_source_link', [0, 1])\ndef test_show_source_link_false(tmp_path, plot_html_show_source_link):\n # Test that a source link is NOT generated if :show-source-link: is false,\n # whether or not plot_html_show_source_link is true.\n parent = Path(__file__).parent\n shutil.copyfile(parent / 'tinypages/conf.py', tmp_path / 'conf.py')\n shutil.copytree(parent / 'tinypages/_static', tmp_path / '_static')\n doctree_dir = tmp_path / 'doctrees'\n (tmp_path / 'index.rst').write_text("""\n.. plot::\n :show-source-link: false\n\n plt.plot(range(2))\n""")\n html_dir = tmp_path / '_build' / 'html'\n build_sphinx_html(tmp_path, doctree_dir, html_dir, extra_args=[\n '-D', f'plot_html_show_source_link={plot_html_show_source_link}'])\n assert len(list(html_dir.glob("**/index-1.py"))) == 0\n\n\ndef test_srcset_version(tmp_path):\n shutil.copytree(Path(__file__).parent / 'tinypages', tmp_path,\n dirs_exist_ok=True)\n html_dir = tmp_path / '_build' / 'html'\n img_dir = html_dir / '_images'\n doctree_dir = tmp_path / 'doctrees'\n\n build_sphinx_html(tmp_path, doctree_dir, html_dir, extra_args=[\n '-D', 'plot_srcset=2x'])\n\n def plot_file(num, suff=''):\n return img_dir / f'some_plots-{num}{suff}.png'\n\n # check some-plots\n for ind in [1, 2, 3, 5, 7, 11, 13, 15, 17]:\n assert plot_file(ind).exists()\n assert plot_file(ind, suff='.2x').exists()\n\n assert (img_dir / 'nestedpage-index-1.png').exists()\n assert (img_dir / 'nestedpage-index-1.2x.png').exists()\n assert (img_dir / 'nestedpage-index-2.png').exists()\n assert (img_dir / 'nestedpage-index-2.2x.png').exists()\n assert (img_dir / 'nestedpage2-index-1.png').exists()\n assert (img_dir / 'nestedpage2-index-1.2x.png').exists()\n assert (img_dir / 'nestedpage2-index-2.png').exists()\n assert (img_dir / 'nestedpage2-index-2.2x.png').exists()\n\n # Check html for srcset\n\n assert ('srcset="_images/some_plots-1.png, _images/some_plots-1.2x.png 2.00x"'\n in (html_dir / 'some_plots.html').read_text(encoding='utf-8'))\n\n st = ('srcset="../_images/nestedpage-index-1.png, '\n '../_images/nestedpage-index-1.2x.png 2.00x"')\n assert st in (html_dir / 'nestedpage/index.html').read_text(encoding='utf-8')\n\n st = ('srcset="../_images/nestedpage2-index-2.png, '\n '../_images/nestedpage2-index-2.2x.png 2.00x"')\n assert st in (html_dir / 'nestedpage2/index.html').read_text(encoding='utf-8')\n | .venv\Lib\site-packages\matplotlib\tests\test_sphinxext.py | test_sphinxext.py | Python | 9,937 | 0.95 | 0.123348 | 0.208333 | awesome-app | 184 | 2024-01-17T12:11:41.046170 | MIT | true | 00113a3a4f95942be2be398187dc3b74 |
import numpy as np\nimport pytest\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.spines import Spines\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\n\n\ndef test_spine_class():\n """Test Spines and SpinesProxy in isolation."""\n class SpineMock:\n def __init__(self):\n self.val = None\n\n def set(self, **kwargs):\n vars(self).update(kwargs)\n\n def set_val(self, val):\n self.val = val\n\n spines_dict = {\n 'left': SpineMock(),\n 'right': SpineMock(),\n 'top': SpineMock(),\n 'bottom': SpineMock(),\n }\n spines = Spines(**spines_dict)\n\n assert spines['left'] is spines_dict['left']\n assert spines.left is spines_dict['left']\n\n spines[['left', 'right']].set_val('x')\n assert spines.left.val == 'x'\n assert spines.right.val == 'x'\n assert spines.top.val is None\n assert spines.bottom.val is None\n\n spines[:].set_val('y')\n assert all(spine.val == 'y' for spine in spines.values())\n\n spines[:].set(foo='bar')\n assert all(spine.foo == 'bar' for spine in spines.values())\n\n with pytest.raises(AttributeError, match='foo'):\n spines.foo\n with pytest.raises(KeyError, match='foo'):\n spines['foo']\n with pytest.raises(KeyError, match='foo, bar'):\n spines[['left', 'foo', 'right', 'bar']]\n with pytest.raises(ValueError, match='single list'):\n spines['left', 'right']\n with pytest.raises(ValueError, match='Spines does not support slicing'):\n spines['left':'right']\n with pytest.raises(ValueError, match='Spines does not support slicing'):\n spines['top':]\n\n\n@image_comparison(['spines_axes_positions.png'])\ndef test_spines_axes_positions():\n # SF bug 2852168\n fig = plt.figure()\n x = np.linspace(0, 2*np.pi, 100)\n y = 2*np.sin(x)\n ax = fig.add_subplot(1, 1, 1)\n ax.set_title('centered spines')\n ax.plot(x, y)\n ax.spines.right.set_position(('axes', 0.1))\n ax.yaxis.set_ticks_position('right')\n ax.spines.top.set_position(('axes', 0.25))\n ax.xaxis.set_ticks_position('top')\n ax.spines.left.set_color('none')\n ax.spines.bottom.set_color('none')\n\n\n@image_comparison(['spines_data_positions.png'])\ndef test_spines_data_positions():\n fig, ax = plt.subplots()\n ax.spines.left.set_position(('data', -1.5))\n ax.spines.top.set_position(('data', 0.5))\n ax.spines.right.set_position(('data', -0.5))\n ax.spines.bottom.set_position('zero')\n ax.set_xlim([-2, 2])\n ax.set_ylim([-2, 2])\n\n\n@check_figures_equal(extensions=["png"])\ndef test_spine_nonlinear_data_positions(fig_test, fig_ref):\n plt.style.use("default")\n\n ax = fig_test.add_subplot()\n ax.set(xscale="log", xlim=(.1, 1))\n # Use position="data" to visually swap the left and right spines, using\n # linewidth to distinguish them. The calls to tick_params removes labels\n # (for image comparison purposes) and harmonizes tick positions with the\n # reference).\n ax.spines.left.set_position(("data", 1))\n ax.spines.left.set_linewidth(2)\n ax.spines.right.set_position(("data", .1))\n ax.tick_params(axis="y", labelleft=False, direction="in")\n\n ax = fig_ref.add_subplot()\n ax.set(xscale="log", xlim=(.1, 1))\n ax.spines.right.set_linewidth(2)\n ax.tick_params(axis="y", labelleft=False, left=False, right=True)\n\n\n@image_comparison(['spines_capstyle.png'])\ndef test_spines_capstyle():\n # issue 2542\n plt.rc('axes', linewidth=20)\n fig, ax = plt.subplots()\n ax.set_xticks([])\n ax.set_yticks([])\n\n\ndef test_label_without_ticks():\n fig, ax = plt.subplots()\n plt.subplots_adjust(left=0.3, bottom=0.3)\n ax.plot(np.arange(10))\n ax.yaxis.set_ticks_position('left')\n ax.spines.left.set_position(('outward', 30))\n ax.spines.right.set_visible(False)\n ax.set_ylabel('y label')\n ax.xaxis.set_ticks_position('bottom')\n ax.spines.bottom.set_position(('outward', 30))\n ax.spines.top.set_visible(False)\n ax.set_xlabel('x label')\n ax.xaxis.set_ticks([])\n ax.yaxis.set_ticks([])\n plt.draw()\n\n spine = ax.spines.left\n spinebbox = spine.get_transform().transform_path(\n spine.get_path()).get_extents()\n assert ax.yaxis.label.get_position()[0] < spinebbox.xmin, \\n "Y-Axis label not left of the spine"\n\n spine = ax.spines.bottom\n spinebbox = spine.get_transform().transform_path(\n spine.get_path()).get_extents()\n assert ax.xaxis.label.get_position()[1] < spinebbox.ymin, \\n "X-Axis label not below the spine"\n\n\n@image_comparison(['black_axes.png'])\ndef test_spines_black_axes():\n # GitHub #18804\n plt.rcParams["savefig.pad_inches"] = 0\n plt.rcParams["savefig.bbox"] = 'tight'\n fig = plt.figure(0, figsize=(4, 4))\n ax = fig.add_axes((0, 0, 1, 1))\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_facecolor((0, 0, 0))\n | .venv\Lib\site-packages\matplotlib\tests\test_spines.py | test_spines.py | Python | 4,909 | 0.95 | 0.089744 | 0.054264 | awesome-app | 690 | 2024-11-22T19:57:50.165297 | BSD-3-Clause | true | 8903c665af38fbe197eba37924a69866 |
import numpy as np\nfrom numpy.testing import assert_array_almost_equal\nimport pytest\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing.decorators import image_comparison\nimport matplotlib.transforms as mtransforms\n\n\ndef velocity_field():\n Y, X = np.mgrid[-3:3:100j, -3:3:200j]\n U = -1 - X**2 + Y\n V = 1 + X - Y**2\n return X, Y, U, V\n\n\ndef swirl_velocity_field():\n x = np.linspace(-3., 3., 200)\n y = np.linspace(-3., 3., 100)\n X, Y = np.meshgrid(x, y)\n a = 0.1\n U = np.cos(a) * (-Y) - np.sin(a) * X\n V = np.sin(a) * (-Y) + np.cos(a) * X\n return x, y, U, V\n\n\n@image_comparison(['streamplot_startpoints'], remove_text=True, style='mpl20',\n extensions=['png'])\ndef test_startpoints():\n X, Y, U, V = velocity_field()\n start_x, start_y = np.meshgrid(np.linspace(X.min(), X.max(), 5),\n np.linspace(Y.min(), Y.max(), 5))\n start_points = np.column_stack([start_x.ravel(), start_y.ravel()])\n plt.streamplot(X, Y, U, V, start_points=start_points)\n plt.plot(start_x, start_y, 'ok')\n\n\n@image_comparison(['streamplot_colormap.png'], remove_text=True, style='mpl20',\n tol=0.022)\ndef test_colormap():\n X, Y, U, V = velocity_field()\n plt.streamplot(X, Y, U, V, color=U, density=0.6, linewidth=2,\n cmap=plt.cm.autumn)\n plt.colorbar()\n\n\n@image_comparison(['streamplot_linewidth'], remove_text=True, style='mpl20',\n tol=0.004)\ndef test_linewidth():\n X, Y, U, V = velocity_field()\n speed = np.hypot(U, V)\n lw = 5 * speed / speed.max()\n ax = plt.figure().subplots()\n ax.streamplot(X, Y, U, V, density=[0.5, 1], color='k', linewidth=lw)\n\n\n@image_comparison(['streamplot_masks_and_nans.png'],\n remove_text=True, style='mpl20')\ndef test_masks_and_nans():\n X, Y, U, V = velocity_field()\n mask = np.zeros(U.shape, dtype=bool)\n mask[40:60, 80:120] = 1\n U[:20, :40] = np.nan\n U = np.ma.array(U, mask=mask)\n ax = plt.figure().subplots()\n with np.errstate(invalid='ignore'):\n ax.streamplot(X, Y, U, V, color=U, cmap=plt.cm.Blues)\n\n\n@image_comparison(['streamplot_maxlength.png'],\n remove_text=True, style='mpl20', tol=0.302)\ndef test_maxlength():\n x, y, U, V = swirl_velocity_field()\n ax = plt.figure().subplots()\n ax.streamplot(x, y, U, V, maxlength=10., start_points=[[0., 1.5]],\n linewidth=2, density=2)\n assert ax.get_xlim()[-1] == ax.get_ylim()[-1] == 3\n # Compatibility for old test image\n ax.set(xlim=(None, 3.2555988021882305), ylim=(None, 3.078326760195413))\n\n\n@image_comparison(['streamplot_maxlength_no_broken.png'],\n remove_text=True, style='mpl20', tol=0.302)\ndef test_maxlength_no_broken():\n x, y, U, V = swirl_velocity_field()\n ax = plt.figure().subplots()\n ax.streamplot(x, y, U, V, maxlength=10., start_points=[[0., 1.5]],\n linewidth=2, density=2, broken_streamlines=False)\n assert ax.get_xlim()[-1] == ax.get_ylim()[-1] == 3\n # Compatibility for old test image\n ax.set(xlim=(None, 3.2555988021882305), ylim=(None, 3.078326760195413))\n\n\n@image_comparison(['streamplot_direction.png'],\n remove_text=True, style='mpl20', tol=0.073)\ndef test_direction():\n x, y, U, V = swirl_velocity_field()\n plt.streamplot(x, y, U, V, integration_direction='backward',\n maxlength=1.5, start_points=[[1.5, 0.]],\n linewidth=2, density=2)\n\n\ndef test_streamplot_limits():\n ax = plt.axes()\n x = np.linspace(-5, 10, 20)\n y = np.linspace(-2, 4, 10)\n y, x = np.meshgrid(y, x)\n trans = mtransforms.Affine2D().translate(25, 32) + ax.transData\n plt.barbs(x, y, np.sin(x), np.cos(y), transform=trans)\n # The calculated bounds are approximately the bounds of the original data,\n # this is because the entire path is taken into account when updating the\n # datalim.\n assert_array_almost_equal(ax.dataLim.bounds, (20, 30, 15, 6),\n decimal=1)\n\n\ndef test_streamplot_grid():\n u = np.ones((2, 2))\n v = np.zeros((2, 2))\n\n # Test for same rows and columns\n x = np.array([[10, 20], [10, 30]])\n y = np.array([[10, 10], [20, 20]])\n\n with pytest.raises(ValueError, match="The rows of 'x' must be equal"):\n plt.streamplot(x, y, u, v)\n\n x = np.array([[10, 20], [10, 20]])\n y = np.array([[10, 10], [20, 30]])\n\n with pytest.raises(ValueError, match="The columns of 'y' must be equal"):\n plt.streamplot(x, y, u, v)\n\n x = np.array([[10, 20], [10, 20]])\n y = np.array([[10, 10], [20, 20]])\n plt.streamplot(x, y, u, v)\n\n # Test for maximum dimensions\n x = np.array([0, 10])\n y = np.array([[[0, 10]]])\n\n with pytest.raises(ValueError, match="'y' can have at maximum "\n "2 dimensions"):\n plt.streamplot(x, y, u, v)\n\n # Test for equal spacing\n u = np.ones((3, 3))\n v = np.zeros((3, 3))\n x = np.array([0, 10, 20])\n y = np.array([0, 10, 30])\n\n with pytest.raises(ValueError, match="'y' values must be equally spaced"):\n plt.streamplot(x, y, u, v)\n\n # Test for strictly increasing\n x = np.array([0, 20, 40])\n y = np.array([0, 20, 10])\n\n with pytest.raises(ValueError, match="'y' must be strictly increasing"):\n plt.streamplot(x, y, u, v)\n\n\ndef test_streamplot_inputs(): # test no exception occurs.\n # fully-masked\n plt.streamplot(np.arange(3), np.arange(3),\n np.full((3, 3), np.nan), np.full((3, 3), np.nan),\n color=np.random.rand(3, 3))\n # array-likes\n plt.streamplot(range(3), range(3),\n np.random.rand(3, 3), np.random.rand(3, 3))\n | .venv\Lib\site-packages\matplotlib\tests\test_streamplot.py | test_streamplot.py | Python | 5,731 | 0.95 | 0.106509 | 0.08209 | node-utils | 293 | 2024-10-08T02:55:33.423648 | MIT | true | fe53661797c46a9da1666cfe3040c33f |
from contextlib import contextmanager\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\nimport sys\n\nimport numpy as np\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt, style\nfrom matplotlib.style.core import USER_LIBRARY_PATHS, STYLE_EXTENSION\n\n\nPARAM = 'image.cmap'\nVALUE = 'pink'\nDUMMY_SETTINGS = {PARAM: VALUE}\n\n\n@contextmanager\ndef temp_style(style_name, settings=None):\n """Context manager to create a style sheet in a temporary directory."""\n if not settings:\n settings = DUMMY_SETTINGS\n temp_file = f'{style_name}.{STYLE_EXTENSION}'\n try:\n with TemporaryDirectory() as tmpdir:\n # Write style settings to file in the tmpdir.\n Path(tmpdir, temp_file).write_text(\n "\n".join(f"{k}: {v}" for k, v in settings.items()),\n encoding="utf-8")\n # Add tmpdir to style path and reload so we can access this style.\n USER_LIBRARY_PATHS.append(tmpdir)\n style.reload_library()\n yield\n finally:\n style.reload_library()\n\n\ndef test_invalid_rc_warning_includes_filename(caplog):\n SETTINGS = {'foo': 'bar'}\n basename = 'basename'\n with temp_style(basename, SETTINGS):\n # style.reload_library() in temp_style() triggers the warning\n pass\n assert (len(caplog.records) == 1\n and basename in caplog.records[0].getMessage())\n\n\ndef test_available():\n with temp_style('_test_', DUMMY_SETTINGS):\n assert '_test_' in style.available\n\n\ndef test_use():\n mpl.rcParams[PARAM] = 'gray'\n with temp_style('test', DUMMY_SETTINGS):\n with style.context('test'):\n assert mpl.rcParams[PARAM] == VALUE\n\n\ndef test_use_url(tmp_path):\n path = tmp_path / 'file'\n path.write_text('axes.facecolor: adeade', encoding='utf-8')\n with temp_style('test', DUMMY_SETTINGS):\n url = ('file:'\n + ('///' if sys.platform == 'win32' else '')\n + path.resolve().as_posix())\n with style.context(url):\n assert mpl.rcParams['axes.facecolor'] == "#adeade"\n\n\ndef test_single_path(tmp_path):\n mpl.rcParams[PARAM] = 'gray'\n path = tmp_path / f'text.{STYLE_EXTENSION}'\n path.write_text(f'{PARAM} : {VALUE}', encoding='utf-8')\n with style.context(path):\n assert mpl.rcParams[PARAM] == VALUE\n assert mpl.rcParams[PARAM] == 'gray'\n\n\ndef test_context():\n mpl.rcParams[PARAM] = 'gray'\n with temp_style('test', DUMMY_SETTINGS):\n with style.context('test'):\n assert mpl.rcParams[PARAM] == VALUE\n # Check that this value is reset after the exiting the context.\n assert mpl.rcParams[PARAM] == 'gray'\n\n\ndef test_context_with_dict():\n original_value = 'gray'\n other_value = 'blue'\n mpl.rcParams[PARAM] = original_value\n with style.context({PARAM: other_value}):\n assert mpl.rcParams[PARAM] == other_value\n assert mpl.rcParams[PARAM] == original_value\n\n\ndef test_context_with_dict_after_namedstyle():\n # Test dict after style name where dict modifies the same parameter.\n original_value = 'gray'\n other_value = 'blue'\n mpl.rcParams[PARAM] = original_value\n with temp_style('test', DUMMY_SETTINGS):\n with style.context(['test', {PARAM: other_value}]):\n assert mpl.rcParams[PARAM] == other_value\n assert mpl.rcParams[PARAM] == original_value\n\n\ndef test_context_with_dict_before_namedstyle():\n # Test dict before style name where dict modifies the same parameter.\n original_value = 'gray'\n other_value = 'blue'\n mpl.rcParams[PARAM] = original_value\n with temp_style('test', DUMMY_SETTINGS):\n with style.context([{PARAM: other_value}, 'test']):\n assert mpl.rcParams[PARAM] == VALUE\n assert mpl.rcParams[PARAM] == original_value\n\n\ndef test_context_with_union_of_dict_and_namedstyle():\n # Test dict after style name where dict modifies the a different parameter.\n original_value = 'gray'\n other_param = 'text.usetex'\n other_value = True\n d = {other_param: other_value}\n mpl.rcParams[PARAM] = original_value\n mpl.rcParams[other_param] = (not other_value)\n with temp_style('test', DUMMY_SETTINGS):\n with style.context(['test', d]):\n assert mpl.rcParams[PARAM] == VALUE\n assert mpl.rcParams[other_param] == other_value\n assert mpl.rcParams[PARAM] == original_value\n assert mpl.rcParams[other_param] == (not other_value)\n\n\ndef test_context_with_badparam():\n original_value = 'gray'\n other_value = 'blue'\n with style.context({PARAM: other_value}):\n assert mpl.rcParams[PARAM] == other_value\n x = style.context({PARAM: original_value, 'badparam': None})\n with pytest.raises(KeyError):\n with x:\n pass\n assert mpl.rcParams[PARAM] == other_value\n\n\n@pytest.mark.parametrize('equiv_styles',\n [('mpl20', 'default'),\n ('mpl15', 'classic')],\n ids=['mpl20', 'mpl15'])\ndef test_alias(equiv_styles):\n rc_dicts = []\n for sty in equiv_styles:\n with style.context(sty):\n rc_dicts.append(mpl.rcParams.copy())\n\n rc_base = rc_dicts[0]\n for nm, rc in zip(equiv_styles[1:], rc_dicts[1:]):\n assert rc_base == rc\n\n\ndef test_xkcd_no_cm():\n assert mpl.rcParams["path.sketch"] is None\n plt.xkcd()\n assert mpl.rcParams["path.sketch"] == (1, 100, 2)\n np.testing.break_cycles()\n assert mpl.rcParams["path.sketch"] == (1, 100, 2)\n\n\ndef test_xkcd_cm():\n assert mpl.rcParams["path.sketch"] is None\n with plt.xkcd():\n assert mpl.rcParams["path.sketch"] == (1, 100, 2)\n assert mpl.rcParams["path.sketch"] is None\n\n\ndef test_up_to_date_blacklist():\n assert mpl.style.core.STYLE_BLACKLIST <= {*mpl.rcsetup._validators}\n\n\ndef test_style_from_module(tmp_path, monkeypatch):\n monkeypatch.syspath_prepend(tmp_path)\n monkeypatch.chdir(tmp_path)\n pkg_path = tmp_path / "mpl_test_style_pkg"\n pkg_path.mkdir()\n (pkg_path / "test_style.mplstyle").write_text(\n "lines.linewidth: 42", encoding="utf-8")\n pkg_path.with_suffix(".mplstyle").write_text(\n "lines.linewidth: 84", encoding="utf-8")\n mpl.style.use("mpl_test_style_pkg.test_style")\n assert mpl.rcParams["lines.linewidth"] == 42\n mpl.style.use("mpl_test_style_pkg.mplstyle")\n assert mpl.rcParams["lines.linewidth"] == 84\n mpl.style.use("./mpl_test_style_pkg.mplstyle")\n assert mpl.rcParams["lines.linewidth"] == 84\n | .venv\Lib\site-packages\matplotlib\tests\test_style.py | test_style.py | Python | 6,509 | 0.95 | 0.116751 | 0.044304 | react-lib | 189 | 2025-01-21T13:08:47.336635 | BSD-3-Clause | true | 8dfc83f8bd5b58a9be7af6c837839d55 |
import itertools\nimport platform\n\nimport numpy as np\nimport pytest\n\nfrom matplotlib.axes import Axes, SubplotBase\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\n\n\ndef check_shared(axs, x_shared, y_shared):\n """\n x_shared and y_shared are n x n boolean matrices; entry (i, j) indicates\n whether the x (or y) axes of subplots i and j should be shared.\n """\n for (i1, ax1), (i2, ax2), (i3, (name, shared)) in itertools.product(\n enumerate(axs),\n enumerate(axs),\n enumerate(zip("xy", [x_shared, y_shared]))):\n if i2 <= i1:\n continue\n assert axs[0]._shared_axes[name].joined(ax1, ax2) == shared[i1, i2], \\n "axes %i and %i incorrectly %ssharing %s axis" % (\n i1, i2, "not " if shared[i1, i2] else "", name)\n\n\ndef check_ticklabel_visible(axs, x_visible, y_visible):\n """Check that the x and y ticklabel visibility is as specified."""\n for i, (ax, vx, vy) in enumerate(zip(axs, x_visible, y_visible)):\n for l in ax.get_xticklabels() + [ax.xaxis.offsetText]:\n assert l.get_visible() == vx, \\n f"Visibility of x axis #{i} is incorrectly {vx}"\n for l in ax.get_yticklabels() + [ax.yaxis.offsetText]:\n assert l.get_visible() == vy, \\n f"Visibility of y axis #{i} is incorrectly {vy}"\n # axis label "visibility" is toggled by label_outer by resetting the\n # label to empty, but it can also be empty to start with.\n if not vx:\n assert ax.get_xlabel() == ""\n if not vy:\n assert ax.get_ylabel() == ""\n\n\ndef check_tick1_visible(axs, x_visible, y_visible):\n """\n Check that the x and y tick visibility is as specified.\n\n Note: This only checks the tick1line, i.e. bottom / left ticks.\n """\n for ax, visible, in zip(axs, x_visible):\n for tick in ax.xaxis.get_major_ticks():\n assert tick.tick1line.get_visible() == visible\n for ax, y_visible, in zip(axs, y_visible):\n for tick in ax.yaxis.get_major_ticks():\n assert tick.tick1line.get_visible() == visible\n\n\ndef test_shared():\n rdim = (4, 4, 2)\n share = {\n 'all': np.ones(rdim[:2], dtype=bool),\n 'none': np.zeros(rdim[:2], dtype=bool),\n 'row': np.array([\n [False, True, False, False],\n [True, False, False, False],\n [False, False, False, True],\n [False, False, True, False]]),\n 'col': np.array([\n [False, False, True, False],\n [False, False, False, True],\n [True, False, False, False],\n [False, True, False, False]]),\n }\n visible = {\n 'x': {\n 'all': [False, False, True, True],\n 'col': [False, False, True, True],\n 'row': [True] * 4,\n 'none': [True] * 4,\n False: [True] * 4,\n True: [False, False, True, True],\n },\n 'y': {\n 'all': [True, False, True, False],\n 'col': [True] * 4,\n 'row': [True, False, True, False],\n 'none': [True] * 4,\n False: [True] * 4,\n True: [True, False, True, False],\n },\n }\n share[False] = share['none']\n share[True] = share['all']\n\n # test default\n f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2)\n axs = [a1, a2, a3, a4]\n check_shared(axs, share['none'], share['none'])\n plt.close(f)\n\n # test all option combinations\n ops = [False, True, 'all', 'none', 'row', 'col', 0, 1]\n for xo in ops:\n for yo in ops:\n f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2, sharex=xo, sharey=yo)\n axs = [a1, a2, a3, a4]\n check_shared(axs, share[xo], share[yo])\n check_ticklabel_visible(axs, visible['x'][xo], visible['y'][yo])\n plt.close(f)\n\n\n@pytest.mark.parametrize('remove_ticks', [True, False])\ndef test_label_outer(remove_ticks):\n f, axs = plt.subplots(2, 2, sharex=True, sharey=True)\n for ax in axs.flat:\n ax.set(xlabel="foo", ylabel="bar")\n ax.label_outer(remove_inner_ticks=remove_ticks)\n check_ticklabel_visible(\n axs.flat, [False, False, True, True], [True, False, True, False])\n if remove_ticks:\n check_tick1_visible(\n axs.flat, [False, False, True, True], [True, False, True, False])\n else:\n check_tick1_visible(\n axs.flat, [True, True, True, True], [True, True, True, True])\n\n\ndef test_label_outer_span():\n fig = plt.figure()\n gs = fig.add_gridspec(3, 3)\n # +---+---+---+\n # | 1 | |\n # +---+---+---+\n # | | | 3 |\n # + 2 +---+---+\n # | | 4 | |\n # +---+---+---+\n a1 = fig.add_subplot(gs[0, 0:2])\n a2 = fig.add_subplot(gs[1:3, 0])\n a3 = fig.add_subplot(gs[1, 2])\n a4 = fig.add_subplot(gs[2, 1])\n for ax in fig.axes:\n ax.label_outer()\n check_ticklabel_visible(\n fig.axes, [False, True, False, True], [True, True, False, False])\n\n\ndef test_label_outer_non_gridspec():\n ax = plt.axes((0, 0, 1, 1))\n ax.label_outer() # Does nothing.\n check_ticklabel_visible([ax], [True], [True])\n\n\ndef test_shared_and_moved():\n # test if sharey is on, but then tick_left is called that labels don't\n # re-appear. Seaborn does this just to be sure yaxis is on left...\n f, (a1, a2) = plt.subplots(1, 2, sharey=True)\n check_ticklabel_visible([a2], [True], [False])\n a2.yaxis.tick_left()\n check_ticklabel_visible([a2], [True], [False])\n\n f, (a1, a2) = plt.subplots(2, 1, sharex=True)\n check_ticklabel_visible([a1], [False], [True])\n a2.xaxis.tick_bottom()\n check_ticklabel_visible([a1], [False], [True])\n\n\ndef test_exceptions():\n # TODO should this test more options?\n with pytest.raises(ValueError):\n plt.subplots(2, 2, sharex='blah')\n with pytest.raises(ValueError):\n plt.subplots(2, 2, sharey='blah')\n\n\n@image_comparison(['subplots_offset_text.png'],\n tol=0 if platform.machine() == 'x86_64' else 0.028)\ndef test_subplots_offsettext():\n x = np.arange(0, 1e10, 1e9)\n y = np.arange(0, 100, 10)+1e4\n fig, axs = plt.subplots(2, 2, sharex='col', sharey='all')\n axs[0, 0].plot(x, x)\n axs[1, 0].plot(x, x)\n axs[0, 1].plot(y, x)\n axs[1, 1].plot(y, x)\n\n\n@pytest.mark.parametrize("top", [True, False])\n@pytest.mark.parametrize("bottom", [True, False])\n@pytest.mark.parametrize("left", [True, False])\n@pytest.mark.parametrize("right", [True, False])\ndef test_subplots_hide_ticklabels(top, bottom, left, right):\n # Ideally, we would also test offset-text visibility (and remove\n # test_subplots_offsettext), but currently, setting rcParams fails to move\n # the offset texts as well.\n with plt.rc_context({"xtick.labeltop": top, "xtick.labelbottom": bottom,\n "ytick.labelleft": left, "ytick.labelright": right}):\n axs = plt.figure().subplots(3, 3, sharex=True, sharey=True)\n for (i, j), ax in np.ndenumerate(axs):\n xtop = ax.xaxis._major_tick_kw["label2On"]\n xbottom = ax.xaxis._major_tick_kw["label1On"]\n yleft = ax.yaxis._major_tick_kw["label1On"]\n yright = ax.yaxis._major_tick_kw["label2On"]\n assert xtop == (top and i == 0)\n assert xbottom == (bottom and i == 2)\n assert yleft == (left and j == 0)\n assert yright == (right and j == 2)\n\n\n@pytest.mark.parametrize("xlabel_position", ["bottom", "top"])\n@pytest.mark.parametrize("ylabel_position", ["left", "right"])\ndef test_subplots_hide_axislabels(xlabel_position, ylabel_position):\n axs = plt.figure().subplots(3, 3, sharex=True, sharey=True)\n for (i, j), ax in np.ndenumerate(axs):\n ax.set(xlabel="foo", ylabel="bar")\n ax.xaxis.set_label_position(xlabel_position)\n ax.yaxis.set_label_position(ylabel_position)\n ax.label_outer()\n assert bool(ax.get_xlabel()) == (\n xlabel_position == "bottom" and i == 2\n or xlabel_position == "top" and i == 0)\n assert bool(ax.get_ylabel()) == (\n ylabel_position == "left" and j == 0\n or ylabel_position == "right" and j == 2)\n\n\ndef test_get_gridspec():\n # ahem, pretty trivial, but...\n fig, ax = plt.subplots()\n assert ax.get_subplotspec().get_gridspec() == ax.get_gridspec()\n\n\ndef test_dont_mutate_kwargs():\n subplot_kw = {'sharex': 'all'}\n gridspec_kw = {'width_ratios': [1, 2]}\n fig, ax = plt.subplots(1, 2, subplot_kw=subplot_kw,\n gridspec_kw=gridspec_kw)\n assert subplot_kw == {'sharex': 'all'}\n assert gridspec_kw == {'width_ratios': [1, 2]}\n\n\n@pytest.mark.parametrize("width_ratios", [None, [1, 3, 2]])\n@pytest.mark.parametrize("height_ratios", [None, [1, 2]])\n@check_figures_equal(extensions=['png'])\ndef test_width_and_height_ratios(fig_test, fig_ref,\n height_ratios, width_ratios):\n fig_test.subplots(2, 3, height_ratios=height_ratios,\n width_ratios=width_ratios)\n fig_ref.subplots(2, 3, gridspec_kw={\n 'height_ratios': height_ratios,\n 'width_ratios': width_ratios})\n\n\n@pytest.mark.parametrize("width_ratios", [None, [1, 3, 2]])\n@pytest.mark.parametrize("height_ratios", [None, [1, 2]])\n@check_figures_equal(extensions=['png'])\ndef test_width_and_height_ratios_mosaic(fig_test, fig_ref,\n height_ratios, width_ratios):\n mosaic_spec = [['A', 'B', 'B'], ['A', 'C', 'D']]\n fig_test.subplot_mosaic(mosaic_spec, height_ratios=height_ratios,\n width_ratios=width_ratios)\n fig_ref.subplot_mosaic(mosaic_spec, gridspec_kw={\n 'height_ratios': height_ratios,\n 'width_ratios': width_ratios})\n\n\n@pytest.mark.parametrize('method,args', [\n ('subplots', (2, 3)),\n ('subplot_mosaic', ('abc;def', ))\n ]\n)\ndef test_ratio_overlapping_kws(method, args):\n with pytest.raises(ValueError, match='height_ratios'):\n getattr(plt, method)(*args, height_ratios=[1, 2],\n gridspec_kw={'height_ratios': [1, 2]})\n with pytest.raises(ValueError, match='width_ratios'):\n getattr(plt, method)(*args, width_ratios=[1, 2, 3],\n gridspec_kw={'width_ratios': [1, 2, 3]})\n\n\ndef test_old_subplot_compat():\n fig = plt.figure()\n assert isinstance(fig.add_subplot(), SubplotBase)\n assert not isinstance(fig.add_axes(rect=[0, 0, 1, 1]), SubplotBase)\n with pytest.raises(TypeError):\n Axes(fig, [0, 0, 1, 1], rect=[0, 0, 1, 1])\n | .venv\Lib\site-packages\matplotlib\tests\test_subplots.py | test_subplots.py | Python | 10,771 | 0.95 | 0.139373 | 0.073469 | python-kit | 778 | 2024-10-25T15:29:38.215901 | Apache-2.0 | true | 2cdffd4267c01579223ca26b353e26f6 |
import datetime\nfrom unittest.mock import Mock\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.path import Path\nfrom matplotlib.table import CustomCell, Table\nfrom matplotlib.testing.decorators import image_comparison, check_figures_equal\nfrom matplotlib.transforms import Bbox\nimport matplotlib.units as munits\n\n\ndef test_non_square():\n # Check that creating a non-square table works\n cellcolors = ['b', 'r']\n plt.table(cellColours=cellcolors)\n\n\n@image_comparison(['table_zorder.png'], remove_text=True)\ndef test_zorder():\n data = [[66386, 174296],\n [58230, 381139]]\n\n colLabels = ('Freeze', 'Wind')\n rowLabels = ['%d year' % x for x in (100, 50)]\n\n cellText = []\n yoff = np.zeros(len(colLabels))\n for row in reversed(data):\n yoff += row\n cellText.append(['%1.1f' % (x/1000.0) for x in yoff])\n\n t = np.linspace(0, 2*np.pi, 100)\n plt.plot(t, np.cos(t), lw=4, zorder=2)\n\n plt.table(cellText=cellText,\n rowLabels=rowLabels,\n colLabels=colLabels,\n loc='center',\n zorder=-2,\n )\n\n plt.table(cellText=cellText,\n rowLabels=rowLabels,\n colLabels=colLabels,\n loc='upper center',\n zorder=4,\n )\n plt.yticks([])\n\n\n@image_comparison(['table_labels.png'])\ndef test_label_colours():\n dim = 3\n\n c = np.linspace(0, 1, dim)\n colours = plt.cm.RdYlGn(c)\n cellText = [['1'] * dim] * dim\n\n fig = plt.figure()\n\n ax1 = fig.add_subplot(4, 1, 1)\n ax1.axis('off')\n ax1.table(cellText=cellText,\n rowColours=colours,\n loc='best')\n\n ax2 = fig.add_subplot(4, 1, 2)\n ax2.axis('off')\n ax2.table(cellText=cellText,\n rowColours=colours,\n rowLabels=['Header'] * dim,\n loc='best')\n\n ax3 = fig.add_subplot(4, 1, 3)\n ax3.axis('off')\n ax3.table(cellText=cellText,\n colColours=colours,\n loc='best')\n\n ax4 = fig.add_subplot(4, 1, 4)\n ax4.axis('off')\n ax4.table(cellText=cellText,\n colColours=colours,\n colLabels=['Header'] * dim,\n loc='best')\n\n\n@image_comparison(['table_cell_manipulation.png'], style='mpl20')\ndef test_diff_cell_table(text_placeholders):\n cells = ('horizontal', 'vertical', 'open', 'closed', 'T', 'R', 'B', 'L')\n cellText = [['1'] * len(cells)] * 2\n colWidths = [0.1] * len(cells)\n\n _, axs = plt.subplots(nrows=len(cells), figsize=(4, len(cells)+1), layout='tight')\n for ax, cell in zip(axs, cells):\n ax.table(\n colWidths=colWidths,\n cellText=cellText,\n loc='center',\n edges=cell,\n )\n ax.axis('off')\n\n\ndef test_customcell():\n types = ('horizontal', 'vertical', 'open', 'closed', 'T', 'R', 'B', 'L')\n codes = (\n (Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO, Path.MOVETO),\n (Path.MOVETO, Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO),\n (Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.MOVETO),\n (Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY),\n (Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.LINETO, Path.MOVETO),\n (Path.MOVETO, Path.MOVETO, Path.LINETO, Path.MOVETO, Path.MOVETO),\n (Path.MOVETO, Path.LINETO, Path.MOVETO, Path.MOVETO, Path.MOVETO),\n (Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.LINETO),\n )\n\n for t, c in zip(types, codes):\n cell = CustomCell((0, 0), visible_edges=t, width=1, height=1)\n code = tuple(s for _, s in cell.get_path().iter_segments())\n assert c == code\n\n\n@image_comparison(['table_auto_column.png'])\ndef test_auto_column():\n fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1)\n\n # iterable list input\n ax1.axis('off')\n tb1 = ax1.table(\n cellText=[['Fit Text', 2],\n ['very long long text, Longer text than default', 1]],\n rowLabels=["A", "B"],\n colLabels=["Col1", "Col2"],\n loc="center")\n tb1.auto_set_font_size(False)\n tb1.set_fontsize(12)\n tb1.auto_set_column_width([-1, 0, 1])\n\n # iterable tuple input\n ax2.axis('off')\n tb2 = ax2.table(\n cellText=[['Fit Text', 2],\n ['very long long text, Longer text than default', 1]],\n rowLabels=["A", "B"],\n colLabels=["Col1", "Col2"],\n loc="center")\n tb2.auto_set_font_size(False)\n tb2.set_fontsize(12)\n tb2.auto_set_column_width((-1, 0, 1))\n\n # 3 single inputs\n ax3.axis('off')\n tb3 = ax3.table(\n cellText=[['Fit Text', 2],\n ['very long long text, Longer text than default', 1]],\n rowLabels=["A", "B"],\n colLabels=["Col1", "Col2"],\n loc="center")\n tb3.auto_set_font_size(False)\n tb3.set_fontsize(12)\n tb3.auto_set_column_width(-1)\n tb3.auto_set_column_width(0)\n tb3.auto_set_column_width(1)\n\n # 4 this used to test non-integer iterable input, which did nothing, but only\n # remains to avoid re-generating the test image.\n ax4.axis('off')\n tb4 = ax4.table(\n cellText=[['Fit Text', 2],\n ['very long long text, Longer text than default', 1]],\n rowLabels=["A", "B"],\n colLabels=["Col1", "Col2"],\n loc="center")\n tb4.auto_set_font_size(False)\n tb4.set_fontsize(12)\n\n\ndef test_table_cells():\n fig, ax = plt.subplots()\n table = Table(ax)\n\n cell = table.add_cell(1, 2, 1, 1)\n assert isinstance(cell, CustomCell)\n assert cell is table[1, 2]\n\n cell2 = CustomCell((0, 0), 1, 2, visible_edges=None)\n table[2, 1] = cell2\n assert table[2, 1] is cell2\n\n # make sure getitem support has not broken\n # properties and setp\n table.properties()\n plt.setp(table)\n\n\n@check_figures_equal(extensions=["png"])\ndef test_table_bbox(fig_test, fig_ref):\n data = [[2, 3],\n [4, 5]]\n\n col_labels = ('Foo', 'Bar')\n row_labels = ('Ada', 'Bob')\n\n cell_text = [[f"{x}" for x in row] for row in data]\n\n ax_list = fig_test.subplots()\n ax_list.table(cellText=cell_text,\n rowLabels=row_labels,\n colLabels=col_labels,\n loc='center',\n bbox=[0.1, 0.2, 0.8, 0.6]\n )\n\n ax_bbox = fig_ref.subplots()\n ax_bbox.table(cellText=cell_text,\n rowLabels=row_labels,\n colLabels=col_labels,\n loc='center',\n bbox=Bbox.from_extents(0.1, 0.2, 0.9, 0.8)\n )\n\n\n@check_figures_equal(extensions=['png'])\ndef test_table_unit(fig_test, fig_ref):\n # test that table doesn't participate in unit machinery, instead uses repr/str\n\n class FakeUnit:\n def __init__(self, thing):\n pass\n def __repr__(self):\n return "Hello"\n\n fake_convertor = munits.ConversionInterface()\n # v, u, a = value, unit, axis\n fake_convertor.convert = Mock(side_effect=lambda v, u, a: 0)\n # not used, here for completeness\n fake_convertor.default_units = Mock(side_effect=lambda v, a: None)\n fake_convertor.axisinfo = Mock(side_effect=lambda u, a: munits.AxisInfo())\n\n munits.registry[FakeUnit] = fake_convertor\n\n data = [[FakeUnit("yellow"), FakeUnit(42)],\n [FakeUnit(datetime.datetime(1968, 8, 1)), FakeUnit(True)]]\n\n fig_test.subplots().table(data)\n fig_ref.subplots().table([["Hello", "Hello"], ["Hello", "Hello"]])\n fig_test.canvas.draw()\n fake_convertor.convert.assert_not_called()\n\n munits.registry.pop(FakeUnit)\n assert not munits.registry.get_converter(FakeUnit)\n\n\ndef test_table_dataframe(pd):\n # Test if Pandas Data Frame can be passed in cellText\n\n data = {\n 'Letter': ['A', 'B', 'C'],\n 'Number': [100, 200, 300]\n }\n\n df = pd.DataFrame(data)\n fig, ax = plt.subplots()\n table = ax.table(df, loc='center')\n\n for r, (index, row) in enumerate(df.iterrows()):\n for c, col in enumerate(df.columns if r == 0 else row.values):\n assert table[r if r == 0 else r+1, c].get_text().get_text() == str(col)\n\n\ndef test_table_fontsize():\n # Test that the passed fontsize propagates to cells\n tableData = [['a', 1], ['b', 2]]\n fig, ax = plt.subplots()\n test_fontsize = 20\n t = ax.table(cellText=tableData, loc='top', fontsize=test_fontsize)\n cell_fontsize = t[(0, 0)].get_fontsize()\n assert cell_fontsize == test_fontsize, f"Actual:{test_fontsize},got:{cell_fontsize}"\n cell_fontsize = t[(1, 1)].get_fontsize()\n assert cell_fontsize == test_fontsize, f"Actual:{test_fontsize},got:{cell_fontsize}"\n | .venv\Lib\site-packages\matplotlib\tests\test_table.py | test_table.py | Python | 8,659 | 0.95 | 0.09894 | 0.057522 | vue-tools | 835 | 2023-08-09T03:45:59.893594 | MIT | true | f320160d5ff8959afeb0160ae6634ebc |
import warnings\n\nimport pytest\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing.decorators import check_figures_equal\n\n\n@pytest.mark.xfail(\n strict=True, reason="testing that warnings fail tests"\n)\ndef test_warn_to_fail():\n warnings.warn("This should fail the test")\n\n\n@pytest.mark.parametrize("a", [1])\n@check_figures_equal(extensions=["png"])\n@pytest.mark.parametrize("b", [1])\ndef test_parametrize_with_check_figure_equal(a, fig_ref, b, fig_test):\n assert a == b\n\n\ndef test_wrap_failure():\n with pytest.raises(ValueError, match="^The decorated function"):\n @check_figures_equal()\n def should_fail(test, ref):\n pass\n\n\n@pytest.mark.xfail(raises=RuntimeError, strict=True,\n reason='Test for check_figures_equal test creating '\n 'new figures')\n@check_figures_equal()\ndef test_check_figures_equal_extra_fig(fig_test, fig_ref):\n plt.figure()\n\n\n@check_figures_equal()\ndef test_check_figures_equal_closed_fig(fig_test, fig_ref):\n fig = plt.figure()\n plt.close(fig)\n | .venv\Lib\site-packages\matplotlib\tests\test_testing.py | test_testing.py | Python | 1,057 | 0.85 | 0.195122 | 0 | awesome-app | 287 | 2023-07-26T07:58:45.555791 | MIT | true | 6ca12d10aaf482279f4371d1fd3598c4 |
import os\nfrom pathlib import Path\nimport re\nimport sys\n\nimport pytest\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing import subprocess_run_for_testing\nfrom matplotlib.testing._markers import needs_usetex\nfrom matplotlib.texmanager import TexManager\n\n\ndef test_fontconfig_preamble():\n """Test that the preamble is included in the source."""\n plt.rcParams['text.usetex'] = True\n\n src1 = TexManager()._get_tex_source("", fontsize=12)\n plt.rcParams['text.latex.preamble'] = '\\usepackage{txfonts}'\n src2 = TexManager()._get_tex_source("", fontsize=12)\n\n assert src1 != src2\n\n\n@pytest.mark.parametrize(\n "rc, preamble, family", [\n ({"font.family": "sans-serif", "font.sans-serif": "helvetica"},\n r"\usepackage{helvet}", r"\sffamily"),\n ({"font.family": "serif", "font.serif": "palatino"},\n r"\usepackage{mathpazo}", r"\rmfamily"),\n ({"font.family": "cursive", "font.cursive": "zapf chancery"},\n r"\usepackage{chancery}", r"\rmfamily"),\n ({"font.family": "monospace", "font.monospace": "courier"},\n r"\usepackage{courier}", r"\ttfamily"),\n ({"font.family": "helvetica"}, r"\usepackage{helvet}", r"\sffamily"),\n ({"font.family": "palatino"}, r"\usepackage{mathpazo}", r"\rmfamily"),\n ({"font.family": "zapf chancery"},\n r"\usepackage{chancery}", r"\rmfamily"),\n ({"font.family": "courier"}, r"\usepackage{courier}", r"\ttfamily")\n ])\ndef test_font_selection(rc, preamble, family):\n plt.rcParams.update(rc)\n tm = TexManager()\n src = Path(tm.make_tex("hello, world", fontsize=12)).read_text()\n assert preamble in src\n assert [*re.findall(r"\\\w+family", src)] == [family]\n\n\n@needs_usetex\ndef test_unicode_characters():\n # Smoke test to see that Unicode characters does not cause issues\n # See #23019\n plt.rcParams['text.usetex'] = True\n fig, ax = plt.subplots()\n ax.set_ylabel('\\textit{Velocity (\N{DEGREE SIGN}/sec)}')\n ax.set_xlabel('\N{VULGAR FRACTION ONE QUARTER}Öøæ')\n fig.canvas.draw()\n\n # But not all characters.\n # Should raise RuntimeError, not UnicodeDecodeError\n with pytest.raises(RuntimeError):\n ax.set_title('\N{SNOWMAN}')\n fig.canvas.draw()\n\n\n@needs_usetex\ndef test_openin_any_paranoid():\n completed = subprocess_run_for_testing(\n [sys.executable, "-c",\n 'import matplotlib.pyplot as plt;'\n 'plt.rcParams.update({"text.usetex": True});'\n 'plt.title("paranoid");'\n 'plt.show(block=False);'],\n env={**os.environ, 'openin_any': 'p'}, check=True, capture_output=True)\n assert completed.stderr == ""\n | .venv\Lib\site-packages\matplotlib\tests\test_texmanager.py | test_texmanager.py | Python | 2,647 | 0.95 | 0.053333 | 0.064516 | awesome-app | 711 | 2023-10-04T16:34:39.699822 | BSD-3-Clause | true | 411740a34151e4d196ada8941edf9aad |
from datetime import datetime\nimport io\nimport warnings\n\nimport numpy as np\nfrom numpy.testing import assert_almost_equal\nfrom packaging.version import parse as parse_version\nimport pyparsing\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib.backend_bases import MouseEvent\nfrom matplotlib.backends.backend_agg import RendererAgg\nfrom matplotlib.figure import Figure\nfrom matplotlib.font_manager import FontProperties\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nimport matplotlib.transforms as mtransforms\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\nfrom matplotlib.testing._markers import needs_usetex\nfrom matplotlib.text import Text, Annotation, OffsetFrom\n\npyparsing_version = parse_version(pyparsing.__version__)\n\n\n@image_comparison(['font_styles'])\ndef test_font_styles():\n\n def find_matplotlib_font(**kw):\n prop = FontProperties(**kw)\n path = findfont(prop, directory=mpl.get_data_path())\n return FontProperties(fname=path)\n\n from matplotlib.font_manager import FontProperties, findfont\n warnings.filterwarnings(\n 'ignore',\n r"findfont: Font family \[u?'Foo'\] not found. Falling back to .",\n UserWarning,\n module='matplotlib.font_manager')\n\n fig, ax = plt.subplots()\n\n normal_font = find_matplotlib_font(\n family="sans-serif",\n style="normal",\n variant="normal",\n size=14)\n a = ax.annotate(\n "Normal Font",\n (0.1, 0.1),\n xycoords='axes fraction',\n fontproperties=normal_font)\n assert a.get_fontname() == 'DejaVu Sans'\n assert a.get_fontstyle() == 'normal'\n assert a.get_fontvariant() == 'normal'\n assert a.get_weight() == 'normal'\n assert a.get_stretch() == 'normal'\n\n bold_font = find_matplotlib_font(\n family="Foo",\n style="normal",\n variant="normal",\n weight="bold",\n stretch=500,\n size=14)\n ax.annotate(\n "Bold Font",\n (0.1, 0.2),\n xycoords='axes fraction',\n fontproperties=bold_font)\n\n bold_italic_font = find_matplotlib_font(\n family="sans serif",\n style="italic",\n variant="normal",\n weight=750,\n stretch=500,\n size=14)\n ax.annotate(\n "Bold Italic Font",\n (0.1, 0.3),\n xycoords='axes fraction',\n fontproperties=bold_italic_font)\n\n light_font = find_matplotlib_font(\n family="sans-serif",\n style="normal",\n variant="normal",\n weight=200,\n stretch=500,\n size=14)\n ax.annotate(\n "Light Font",\n (0.1, 0.4),\n xycoords='axes fraction',\n fontproperties=light_font)\n\n condensed_font = find_matplotlib_font(\n family="sans-serif",\n style="normal",\n variant="normal",\n weight=500,\n stretch=100,\n size=14)\n ax.annotate(\n "Condensed Font",\n (0.1, 0.5),\n xycoords='axes fraction',\n fontproperties=condensed_font)\n\n ax.set_xticks([])\n ax.set_yticks([])\n\n\n@image_comparison(['multiline'])\ndef test_multiline():\n plt.figure()\n ax = plt.subplot(1, 1, 1)\n ax.set_title("multiline\ntext alignment")\n\n plt.text(\n 0.2, 0.5, "TpTpTp\n$M$\nTpTpTp", size=20, ha="center", va="top")\n\n plt.text(\n 0.5, 0.5, "TpTpTp\n$M^{M^{M^{M}}}$\nTpTpTp", size=20,\n ha="center", va="top")\n\n plt.text(\n 0.8, 0.5, "TpTpTp\n$M_{q_{q_{q}}}$\nTpTpTp", size=20,\n ha="center", va="top")\n\n plt.xlim(0, 1)\n plt.ylim(0, 0.8)\n\n ax.set_xticks([])\n ax.set_yticks([])\n\n\n@image_comparison(['multiline2'], style='mpl20')\ndef test_multiline2():\n # Remove this line when this test image is regenerated.\n plt.rcParams['text.kerning_factor'] = 6\n\n fig, ax = plt.subplots()\n\n ax.set_xlim([0, 1.4])\n ax.set_ylim([0, 2])\n ax.axhline(0.5, color='C2', linewidth=0.3)\n sts = ['Line', '2 Lineg\n 2 Lg', '$\\sum_i x $', 'hi $\\sum_i x $\ntest',\n 'test\n $\\sum_i x $', '$\\sum_i x $\n $\\sum_i x $']\n renderer = fig.canvas.get_renderer()\n\n def draw_box(ax, tt):\n r = mpatches.Rectangle((0, 0), 1, 1, clip_on=False,\n transform=ax.transAxes)\n r.set_bounds(\n tt.get_window_extent(renderer)\n .transformed(ax.transAxes.inverted())\n .bounds)\n ax.add_patch(r)\n\n horal = 'left'\n for nn, st in enumerate(sts):\n tt = ax.text(0.2 * nn + 0.1, 0.5, st, horizontalalignment=horal,\n verticalalignment='bottom')\n draw_box(ax, tt)\n ax.text(1.2, 0.5, 'Bottom align', color='C2')\n\n ax.axhline(1.3, color='C2', linewidth=0.3)\n for nn, st in enumerate(sts):\n tt = ax.text(0.2 * nn + 0.1, 1.3, st, horizontalalignment=horal,\n verticalalignment='top')\n draw_box(ax, tt)\n ax.text(1.2, 1.3, 'Top align', color='C2')\n\n ax.axhline(1.8, color='C2', linewidth=0.3)\n for nn, st in enumerate(sts):\n tt = ax.text(0.2 * nn + 0.1, 1.8, st, horizontalalignment=horal,\n verticalalignment='baseline')\n draw_box(ax, tt)\n ax.text(1.2, 1.8, 'Baseline align', color='C2')\n\n ax.axhline(0.1, color='C2', linewidth=0.3)\n for nn, st in enumerate(sts):\n tt = ax.text(0.2 * nn + 0.1, 0.1, st, horizontalalignment=horal,\n verticalalignment='bottom', rotation=20)\n draw_box(ax, tt)\n ax.text(1.2, 0.1, 'Bot align, rot20', color='C2')\n\n\n@image_comparison(['antialiased.png'], style='mpl20')\ndef test_antialiasing():\n mpl.rcParams['text.antialiased'] = False # Passed arguments should override.\n\n fig = plt.figure(figsize=(5.25, 0.75))\n fig.text(0.3, 0.75, "antialiased", horizontalalignment='center',\n verticalalignment='center', antialiased=True)\n fig.text(0.3, 0.25, r"$\sqrt{x}$", horizontalalignment='center',\n verticalalignment='center', antialiased=True)\n\n mpl.rcParams['text.antialiased'] = True # Passed arguments should override.\n fig.text(0.7, 0.75, "not antialiased", horizontalalignment='center',\n verticalalignment='center', antialiased=False)\n fig.text(0.7, 0.25, r"$\sqrt{x}$", horizontalalignment='center',\n verticalalignment='center', antialiased=False)\n\n mpl.rcParams['text.antialiased'] = False # Should not affect existing text.\n\n\ndef test_afm_kerning():\n fn = mpl.font_manager.findfont("Helvetica", fontext="afm")\n with open(fn, 'rb') as fh:\n afm = mpl._afm.AFM(fh)\n assert afm.string_width_height('VAVAVAVAVAVA') == (7174.0, 718)\n\n\n@image_comparison(['text_contains.png'])\ndef test_contains():\n fig = plt.figure()\n ax = plt.axes()\n\n mevent = MouseEvent('button_press_event', fig.canvas, 0.5, 0.5, 1, None)\n\n xs = np.linspace(0.25, 0.75, 30)\n ys = np.linspace(0.25, 0.75, 30)\n xs, ys = np.meshgrid(xs, ys)\n\n txt = plt.text(\n 0.5, 0.4, 'hello world', ha='center', fontsize=30, rotation=30)\n # uncomment to draw the text's bounding box\n # txt.set_bbox(dict(edgecolor='black', facecolor='none'))\n\n # draw the text. This is important, as the contains method can only work\n # when a renderer exists.\n fig.canvas.draw()\n\n for x, y in zip(xs.flat, ys.flat):\n mevent.x, mevent.y = plt.gca().transAxes.transform([x, y])\n contains, _ = txt.contains(mevent)\n color = 'yellow' if contains else 'red'\n\n # capture the viewLim, plot a point, and reset the viewLim\n vl = ax.viewLim.frozen()\n ax.plot(x, y, 'o', color=color)\n ax.viewLim.set(vl)\n\n\ndef test_annotation_contains():\n # Check that Annotation.contains looks at the bboxes of the text and the\n # arrow separately, not at the joint bbox.\n fig, ax = plt.subplots()\n ann = ax.annotate(\n "hello", xy=(.4, .4), xytext=(.6, .6), arrowprops={"arrowstyle": "->"})\n fig.canvas.draw() # Needed for the same reason as in test_contains.\n event = MouseEvent(\n "button_press_event", fig.canvas, *ax.transData.transform((.5, .6)))\n assert ann.contains(event) == (False, {})\n\n\n@pytest.mark.parametrize('err, xycoords, match', (\n (TypeError, print, "xycoords callable must return a BboxBase or Transform, not a"),\n (TypeError, [0, 0], r"'xycoords' must be an instance of str, tuple"),\n (ValueError, "foo", "'foo' is not a valid coordinate"),\n (ValueError, "foo bar", "'foo bar' is not a valid coordinate"),\n (ValueError, "offset foo", "xycoords cannot be an offset coordinate"),\n (ValueError, "axes foo", "'foo' is not a recognized unit"),\n))\ndef test_annotate_errors(err, xycoords, match):\n fig, ax = plt.subplots()\n with pytest.raises(err, match=match):\n ax.annotate('xy', (0, 0), xytext=(0.5, 0.5), xycoords=xycoords)\n fig.canvas.draw()\n\n\n@image_comparison(['titles'])\ndef test_titles():\n # left and right side titles\n plt.figure()\n ax = plt.subplot(1, 1, 1)\n ax.set_title("left title", loc="left")\n ax.set_title("right title", loc="right")\n ax.set_xticks([])\n ax.set_yticks([])\n\n\n@image_comparison(['text_alignment'], style='mpl20')\ndef test_alignment():\n plt.figure()\n ax = plt.subplot(1, 1, 1)\n\n x = 0.1\n for rotation in (0, 30):\n for alignment in ('top', 'bottom', 'baseline', 'center'):\n ax.text(\n x, 0.5, alignment + " Tj", va=alignment, rotation=rotation,\n bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))\n ax.text(\n x, 1.0, r'$\sum_{i=0}^{j}$', va=alignment, rotation=rotation)\n x += 0.1\n\n ax.plot([0, 1], [0.5, 0.5])\n ax.plot([0, 1], [1.0, 1.0])\n\n ax.set_xlim(0, 1)\n ax.set_ylim(0, 1.5)\n ax.set_xticks([])\n ax.set_yticks([])\n\n\n@image_comparison(['axes_titles.png'])\ndef test_axes_titles():\n # Related to issue #3327\n plt.figure()\n ax = plt.subplot(1, 1, 1)\n ax.set_title('center', loc='center', fontsize=20, fontweight=700)\n ax.set_title('left', loc='left', fontsize=12, fontweight=400)\n ax.set_title('right', loc='right', fontsize=12, fontweight=400)\n\n\ndef test_set_position():\n fig, ax = plt.subplots()\n\n # test set_position\n ann = ax.annotate(\n 'test', (0, 0), xytext=(0, 0), textcoords='figure pixels')\n fig.canvas.draw()\n\n init_pos = ann.get_window_extent(fig.canvas.renderer)\n shift_val = 15\n ann.set_position((shift_val, shift_val))\n fig.canvas.draw()\n post_pos = ann.get_window_extent(fig.canvas.renderer)\n\n for a, b in zip(init_pos.min, post_pos.min):\n assert a + shift_val == b\n\n # test xyann\n ann = ax.annotate(\n 'test', (0, 0), xytext=(0, 0), textcoords='figure pixels')\n fig.canvas.draw()\n\n init_pos = ann.get_window_extent(fig.canvas.renderer)\n shift_val = 15\n ann.xyann = (shift_val, shift_val)\n fig.canvas.draw()\n post_pos = ann.get_window_extent(fig.canvas.renderer)\n\n for a, b in zip(init_pos.min, post_pos.min):\n assert a + shift_val == b\n\n\ndef test_char_index_at():\n fig = plt.figure()\n text = fig.text(0.1, 0.9, "")\n\n text.set_text("i")\n bbox = text.get_window_extent()\n size_i = bbox.x1 - bbox.x0\n\n text.set_text("m")\n bbox = text.get_window_extent()\n size_m = bbox.x1 - bbox.x0\n\n text.set_text("iiiimmmm")\n bbox = text.get_window_extent()\n origin = bbox.x0\n\n assert text._char_index_at(origin - size_i) == 0 # left of first char\n assert text._char_index_at(origin) == 0\n assert text._char_index_at(origin + 0.499*size_i) == 0\n assert text._char_index_at(origin + 0.501*size_i) == 1\n assert text._char_index_at(origin + size_i*3) == 3\n assert text._char_index_at(origin + size_i*4 + size_m*3) == 7\n assert text._char_index_at(origin + size_i*4 + size_m*4) == 8\n assert text._char_index_at(origin + size_i*4 + size_m*10) == 8\n\n\n@pytest.mark.parametrize('text', ['', 'O'], ids=['empty', 'non-empty'])\ndef test_non_default_dpi(text):\n fig, ax = plt.subplots()\n\n t1 = ax.text(0.5, 0.5, text, ha='left', va='bottom')\n fig.canvas.draw()\n dpi = fig.dpi\n\n bbox1 = t1.get_window_extent()\n bbox2 = t1.get_window_extent(dpi=dpi * 10)\n np.testing.assert_allclose(bbox2.get_points(), bbox1.get_points() * 10,\n rtol=5e-2)\n # Text.get_window_extent should not permanently change dpi.\n assert fig.dpi == dpi\n\n\ndef test_get_rotation_string():\n assert Text(rotation='horizontal').get_rotation() == 0.\n assert Text(rotation='vertical').get_rotation() == 90.\n\n\ndef test_get_rotation_float():\n for i in [15., 16.70, 77.4]:\n assert Text(rotation=i).get_rotation() == i\n\n\ndef test_get_rotation_int():\n for i in [67, 16, 41]:\n assert Text(rotation=i).get_rotation() == float(i)\n\n\ndef test_get_rotation_raises():\n with pytest.raises(ValueError):\n Text(rotation='hozirontal')\n\n\ndef test_get_rotation_none():\n assert Text(rotation=None).get_rotation() == 0.0\n\n\ndef test_get_rotation_mod360():\n for i, j in zip([360., 377., 720+177.2], [0., 17., 177.2]):\n assert_almost_equal(Text(rotation=i).get_rotation(), j)\n\n\n@pytest.mark.parametrize("ha", ["center", "right", "left"])\n@pytest.mark.parametrize("va", ["center", "top", "bottom",\n "baseline", "center_baseline"])\ndef test_null_rotation_with_rotation_mode(ha, va):\n fig, ax = plt.subplots()\n kw = dict(rotation=0, va=va, ha=ha)\n t0 = ax.text(.5, .5, 'test', rotation_mode='anchor', **kw)\n t1 = ax.text(.5, .5, 'test', rotation_mode='default', **kw)\n fig.canvas.draw()\n assert_almost_equal(t0.get_window_extent(fig.canvas.renderer).get_points(),\n t1.get_window_extent(fig.canvas.renderer).get_points())\n\n\n@image_comparison(['text_bboxclip'])\ndef test_bbox_clipping():\n plt.text(0.9, 0.2, 'Is bbox clipped?', backgroundcolor='r', clip_on=True)\n t = plt.text(0.9, 0.5, 'Is fancy bbox clipped?', clip_on=True)\n t.set_bbox({"boxstyle": "round, pad=0.1"})\n\n\n@image_comparison(['annotation_negative_ax_coords.png'])\ndef test_annotation_negative_ax_coords():\n fig, ax = plt.subplots()\n\n ax.annotate('+ pts',\n xytext=[30, 20], textcoords='axes points',\n xy=[30, 20], xycoords='axes points', fontsize=32)\n ax.annotate('- pts',\n xytext=[30, -20], textcoords='axes points',\n xy=[30, -20], xycoords='axes points', fontsize=32,\n va='top')\n ax.annotate('+ frac',\n xytext=[0.75, 0.05], textcoords='axes fraction',\n xy=[0.75, 0.05], xycoords='axes fraction', fontsize=32)\n ax.annotate('- frac',\n xytext=[0.75, -0.05], textcoords='axes fraction',\n xy=[0.75, -0.05], xycoords='axes fraction', fontsize=32,\n va='top')\n\n ax.annotate('+ pixels',\n xytext=[160, 25], textcoords='axes pixels',\n xy=[160, 25], xycoords='axes pixels', fontsize=32)\n ax.annotate('- pixels',\n xytext=[160, -25], textcoords='axes pixels',\n xy=[160, -25], xycoords='axes pixels', fontsize=32,\n va='top')\n\n\n@image_comparison(['annotation_negative_fig_coords.png'])\ndef test_annotation_negative_fig_coords():\n fig, ax = plt.subplots()\n\n ax.annotate('+ pts',\n xytext=[10, 120], textcoords='figure points',\n xy=[10, 120], xycoords='figure points', fontsize=32)\n ax.annotate('- pts',\n xytext=[-10, 180], textcoords='figure points',\n xy=[-10, 180], xycoords='figure points', fontsize=32,\n va='top')\n ax.annotate('+ frac',\n xytext=[0.05, 0.55], textcoords='figure fraction',\n xy=[0.05, 0.55], xycoords='figure fraction', fontsize=32)\n ax.annotate('- frac',\n xytext=[-0.05, 0.5], textcoords='figure fraction',\n xy=[-0.05, 0.5], xycoords='figure fraction', fontsize=32,\n va='top')\n\n ax.annotate('+ pixels',\n xytext=[50, 50], textcoords='figure pixels',\n xy=[50, 50], xycoords='figure pixels', fontsize=32)\n ax.annotate('- pixels',\n xytext=[-50, 100], textcoords='figure pixels',\n xy=[-50, 100], xycoords='figure pixels', fontsize=32,\n va='top')\n\n\ndef test_text_stale():\n fig, (ax1, ax2) = plt.subplots(1, 2)\n plt.draw_all()\n assert not ax1.stale\n assert not ax2.stale\n assert not fig.stale\n\n txt1 = ax1.text(.5, .5, 'aardvark')\n assert ax1.stale\n assert txt1.stale\n assert fig.stale\n\n ann1 = ax2.annotate('aardvark', xy=[.5, .5])\n assert ax2.stale\n assert ann1.stale\n assert fig.stale\n\n plt.draw_all()\n assert not ax1.stale\n assert not ax2.stale\n assert not fig.stale\n\n\n@image_comparison(['agg_text_clip.png'])\ndef test_agg_text_clip():\n np.random.seed(1)\n fig, (ax1, ax2) = plt.subplots(2)\n for x, y in np.random.rand(10, 2):\n ax1.text(x, y, "foo", clip_on=True)\n ax2.text(x, y, "foo")\n\n\ndef test_text_size_binding():\n mpl.rcParams['font.size'] = 10\n fp = mpl.font_manager.FontProperties(size='large')\n sz1 = fp.get_size_in_points()\n mpl.rcParams['font.size'] = 100\n\n assert sz1 == fp.get_size_in_points()\n\n\n@image_comparison(['font_scaling.pdf'])\ndef test_font_scaling():\n mpl.rcParams['pdf.fonttype'] = 42\n fig, ax = plt.subplots(figsize=(6.4, 12.4))\n ax.xaxis.set_major_locator(plt.NullLocator())\n ax.yaxis.set_major_locator(plt.NullLocator())\n ax.set_ylim(-10, 600)\n\n for i, fs in enumerate(range(4, 43, 2)):\n ax.text(0.1, i*30, f"{fs} pt font size", fontsize=fs)\n\n\n@pytest.mark.parametrize('spacing1, spacing2', [(0.4, 2), (2, 0.4), (2, 2)])\ndef test_two_2line_texts(spacing1, spacing2):\n text_string = 'line1\nline2'\n fig = plt.figure()\n renderer = fig.canvas.get_renderer()\n\n text1 = fig.text(0.25, 0.5, text_string, linespacing=spacing1)\n text2 = fig.text(0.25, 0.5, text_string, linespacing=spacing2)\n fig.canvas.draw()\n\n box1 = text1.get_window_extent(renderer=renderer)\n box2 = text2.get_window_extent(renderer=renderer)\n\n # line spacing only affects height\n assert box1.width == box2.width\n if spacing1 == spacing2:\n assert box1.height == box2.height\n else:\n assert box1.height != box2.height\n\n\ndef test_validate_linespacing():\n with pytest.raises(TypeError):\n plt.text(.25, .5, "foo", linespacing="abc")\n\n\ndef test_nonfinite_pos():\n fig, ax = plt.subplots()\n ax.text(0, np.nan, 'nan')\n ax.text(np.inf, 0, 'inf')\n fig.canvas.draw()\n\n\ndef test_hinting_factor_backends():\n plt.rcParams['text.hinting_factor'] = 1\n fig = plt.figure()\n t = fig.text(0.5, 0.5, 'some text')\n\n fig.savefig(io.BytesIO(), format='svg')\n expected = t.get_window_extent().intervalx\n\n fig.savefig(io.BytesIO(), format='png')\n # Backends should apply hinting_factor consistently (within 10%).\n np.testing.assert_allclose(t.get_window_extent().intervalx, expected,\n rtol=0.1)\n\n\n@needs_usetex\ndef test_usetex_is_copied():\n # Indirectly tests that update_from (which is used to copy tick label\n # properties) copies usetex state.\n fig = plt.figure()\n plt.rcParams["text.usetex"] = False\n ax1 = fig.add_subplot(121)\n plt.rcParams["text.usetex"] = True\n ax2 = fig.add_subplot(122)\n fig.canvas.draw()\n for ax, usetex in [(ax1, False), (ax2, True)]:\n for t in ax.xaxis.majorTicks:\n assert t.label1.get_usetex() == usetex\n\n\n@needs_usetex\ndef test_single_artist_usetex():\n # Check that a single artist marked with usetex does not get passed through\n # the mathtext parser at all (for the Agg backend) (the mathtext parser\n # currently fails to parse \frac12, requiring \frac{1}{2} instead).\n fig = plt.figure()\n fig.text(.5, .5, r"$\frac12$", usetex=True)\n fig.canvas.draw()\n\n\n@pytest.mark.parametrize("fmt", ["png", "pdf", "svg"])\ndef test_single_artist_usenotex(fmt):\n # Check that a single artist can be marked as not-usetex even though the\n # rcParam is on ("2_2_2" fails if passed to TeX). This currently skips\n # postscript output as the ps renderer doesn't support mixing usetex and\n # non-usetex.\n plt.rcParams["text.usetex"] = True\n fig = plt.figure()\n fig.text(.5, .5, "2_2_2", usetex=False)\n fig.savefig(io.BytesIO(), format=fmt)\n\n\n@image_comparison(['text_as_path_opacity.svg'])\ndef test_text_as_path_opacity():\n plt.figure()\n plt.gca().set_axis_off()\n plt.text(0.25, 0.25, 'c', color=(0, 0, 0, 0.5))\n plt.text(0.25, 0.5, 'a', alpha=0.5)\n plt.text(0.25, 0.75, 'x', alpha=0.5, color=(0, 0, 0, 1))\n\n\n@image_comparison(['text_as_text_opacity.svg'])\ndef test_text_as_text_opacity():\n mpl.rcParams['svg.fonttype'] = 'none'\n plt.figure()\n plt.gca().set_axis_off()\n plt.text(0.25, 0.25, '50% using `color`', color=(0, 0, 0, 0.5))\n plt.text(0.25, 0.5, '50% using `alpha`', alpha=0.5)\n plt.text(0.25, 0.75, '50% using `alpha` and 100% `color`', alpha=0.5,\n color=(0, 0, 0, 1))\n\n\ndef test_text_repr():\n # smoketest to make sure text repr doesn't error for category\n plt.plot(['A', 'B'], [1, 2])\n repr(plt.text(['A'], 0.5, 'Boo'))\n\n\ndef test_annotation_update():\n fig, ax = plt.subplots(1, 1)\n an = ax.annotate('annotation', xy=(0.5, 0.5))\n extent1 = an.get_window_extent(fig.canvas.get_renderer())\n fig.tight_layout()\n extent2 = an.get_window_extent(fig.canvas.get_renderer())\n\n assert not np.allclose(extent1.get_points(), extent2.get_points(),\n rtol=1e-6)\n\n\n@check_figures_equal(extensions=["png"])\ndef test_annotation_units(fig_test, fig_ref):\n ax = fig_test.add_subplot()\n ax.plot(datetime.now(), 1, "o") # Implicitly set axes extents.\n ax.annotate("x", (datetime.now(), 0.5), xycoords=("data", "axes fraction"),\n # This used to crash before.\n xytext=(0, 0), textcoords="offset points")\n ax = fig_ref.add_subplot()\n ax.plot(datetime.now(), 1, "o")\n ax.annotate("x", (datetime.now(), 0.5), xycoords=("data", "axes fraction"))\n\n\n@image_comparison(['large_subscript_title.png'], style='mpl20')\ndef test_large_subscript_title():\n # Remove this line when this test image is regenerated.\n plt.rcParams['text.kerning_factor'] = 6\n plt.rcParams['axes.titley'] = None\n\n fig, axs = plt.subplots(1, 2, figsize=(9, 2.5), constrained_layout=True)\n ax = axs[0]\n ax.set_title(r'$\sum_{i} x_i$')\n ax.set_title('New way', loc='left')\n ax.set_xticklabels([])\n\n ax = axs[1]\n ax.set_title(r'$\sum_{i} x_i$', y=1.01)\n ax.set_title('Old Way', loc='left')\n ax.set_xticklabels([])\n\n\n@pytest.mark.parametrize(\n "x, rotation, halign",\n [(0.7, 0, 'left'),\n (0.5, 95, 'left'),\n (0.3, 0, 'right'),\n (0.3, 185, 'left')])\ndef test_wrap(x, rotation, halign):\n fig = plt.figure(figsize=(18, 18))\n gs = GridSpec(nrows=3, ncols=3, figure=fig)\n subfig = fig.add_subfigure(gs[1, 1])\n # we only use the central subfigure, which does not align with any\n # figure boundary, to ensure only subfigure boundaries are relevant\n s = 'This is a very long text that should be wrapped multiple times.'\n text = subfig.text(x, 0.7, s, wrap=True, rotation=rotation, ha=halign)\n fig.canvas.draw()\n assert text._get_wrapped_text() == ('This is a very long\n'\n 'text that should be\n'\n 'wrapped multiple\n'\n 'times.')\n\n\ndef test_mathwrap():\n fig = plt.figure(figsize=(6, 4))\n s = r'This is a very $\overline{\mathrm{long}}$ line of Mathtext.'\n text = fig.text(0, 0.5, s, size=40, wrap=True)\n fig.canvas.draw()\n assert text._get_wrapped_text() == ('This is a very $\\overline{\\mathrm{long}}$\n'\n 'line of Mathtext.')\n\n\ndef test_get_window_extent_wrapped():\n # Test that a long title that wraps to two lines has the same vertical\n # extent as an explicit two line title.\n\n fig1 = plt.figure(figsize=(3, 3))\n fig1.suptitle("suptitle that is clearly too long in this case", wrap=True)\n window_extent_test = fig1._suptitle.get_window_extent()\n\n fig2 = plt.figure(figsize=(3, 3))\n fig2.suptitle("suptitle that is clearly\ntoo long in this case")\n window_extent_ref = fig2._suptitle.get_window_extent()\n\n assert window_extent_test.y0 == window_extent_ref.y0\n assert window_extent_test.y1 == window_extent_ref.y1\n\n\ndef test_long_word_wrap():\n fig = plt.figure(figsize=(6, 4))\n text = fig.text(9.5, 8, 'Alonglineoftexttowrap', wrap=True)\n fig.canvas.draw()\n assert text._get_wrapped_text() == 'Alonglineoftexttowrap'\n\n\ndef test_wrap_no_wrap():\n fig = plt.figure(figsize=(6, 4))\n text = fig.text(0, 0, 'non wrapped text', wrap=True)\n fig.canvas.draw()\n assert text._get_wrapped_text() == 'non wrapped text'\n\n\n@check_figures_equal(extensions=["png"])\ndef test_buffer_size(fig_test, fig_ref):\n # On old versions of the Agg renderer, large non-ascii single-character\n # strings (here, "€") would be rendered clipped because the rendering\n # buffer would be set by the physical size of the smaller "a" character.\n ax = fig_test.add_subplot()\n ax.set_yticks([0, 1])\n ax.set_yticklabels(["€", "a"])\n ax.yaxis.majorTicks[1].label1.set_color("w")\n ax = fig_ref.add_subplot()\n ax.set_yticks([0, 1])\n ax.set_yticklabels(["€", ""])\n\n\ndef test_fontproperties_kwarg_precedence():\n """Test that kwargs take precedence over fontproperties defaults."""\n plt.figure()\n text1 = plt.xlabel("value", fontproperties='Times New Roman', size=40.0)\n text2 = plt.ylabel("counts", size=40.0, fontproperties='Times New Roman')\n assert text1.get_size() == 40.0\n assert text2.get_size() == 40.0\n\n\ndef test_transform_rotates_text():\n ax = plt.gca()\n transform = mtransforms.Affine2D().rotate_deg(30)\n text = ax.text(0, 0, 'test', transform=transform,\n transform_rotates_text=True)\n result = text.get_rotation()\n assert_almost_equal(result, 30)\n\n\ndef test_update_mutate_input():\n inp = dict(fontproperties=FontProperties(weight="bold"),\n bbox=None)\n cache = dict(inp)\n t = Text()\n t.update(inp)\n assert inp['fontproperties'] == cache['fontproperties']\n assert inp['bbox'] == cache['bbox']\n\n\n@pytest.mark.parametrize('rotation', ['invalid string', [90]])\ndef test_invalid_rotation_values(rotation):\n with pytest.raises(\n ValueError,\n match=("rotation must be 'vertical', 'horizontal' or a number")):\n Text(0, 0, 'foo', rotation=rotation)\n\n\ndef test_invalid_color():\n with pytest.raises(ValueError):\n plt.figtext(.5, .5, "foo", c="foobar")\n\n\n@image_comparison(['text_pdf_kerning.pdf'], style='mpl20')\ndef test_pdf_kerning():\n plt.figure()\n plt.figtext(0.1, 0.5, "ATATATATATATATATATA", size=30)\n\n\ndef test_unsupported_script(recwarn):\n fig = plt.figure()\n t = fig.text(.5, .5, "\N{BENGALI DIGIT ZERO}")\n fig.canvas.draw()\n assert all(isinstance(warn.message, UserWarning) for warn in recwarn)\n assert (\n [warn.message.args for warn in recwarn] ==\n [(r"Glyph 2534 (\N{BENGALI DIGIT ZERO}) missing from font(s) "\n + f"{t.get_fontname()}.",),\n (r"Matplotlib currently does not support Bengali natively.",)])\n\n\n# See gh-26152 for more information on this xfail\n@pytest.mark.xfail(pyparsing_version.release == (3, 1, 0),\n reason="Error messages are incorrect with pyparsing 3.1.0")\ndef test_parse_math():\n fig, ax = plt.subplots()\n ax.text(0, 0, r"$ \wrong{math} $", parse_math=False)\n fig.canvas.draw()\n\n ax.text(0, 0, r"$ \wrong{math} $", parse_math=True)\n with pytest.raises(ValueError, match='Unknown symbol'):\n fig.canvas.draw()\n\n\n# See gh-26152 for more information on this xfail\n@pytest.mark.xfail(pyparsing_version.release == (3, 1, 0),\n reason="Error messages are incorrect with pyparsing 3.1.0")\ndef test_parse_math_rcparams():\n # Default is True\n fig, ax = plt.subplots()\n ax.text(0, 0, r"$ \wrong{math} $")\n with pytest.raises(ValueError, match='Unknown symbol'):\n fig.canvas.draw()\n\n # Setting rcParams to False\n with mpl.rc_context({'text.parse_math': False}):\n fig, ax = plt.subplots()\n ax.text(0, 0, r"$ \wrong{math} $")\n fig.canvas.draw()\n\n\n@image_comparison(['text_pdf_font42_kerning.pdf'], style='mpl20')\ndef test_pdf_font42_kerning():\n plt.rcParams['pdf.fonttype'] = 42\n plt.figure()\n plt.figtext(0.1, 0.5, "ATAVATAVATAVATAVATA", size=30)\n\n\n@image_comparison(['text_pdf_chars_beyond_bmp.pdf'], style='mpl20')\ndef test_pdf_chars_beyond_bmp():\n plt.rcParams['pdf.fonttype'] = 42\n plt.rcParams['mathtext.fontset'] = 'stixsans'\n plt.figure()\n plt.figtext(0.1, 0.5, "Mass $m$ \U00010308", size=30)\n\n\n@needs_usetex\ndef test_metrics_cache():\n mpl.text._get_text_metrics_with_cache_impl.cache_clear()\n\n fig = plt.figure()\n fig.text(.3, .5, "foo\nbar")\n fig.text(.3, .5, "foo\nbar", usetex=True)\n fig.text(.5, .5, "foo\nbar", usetex=True)\n fig.canvas.draw()\n renderer = fig._get_renderer()\n ys = {} # mapping of strings to where they were drawn in y with draw_tex.\n\n def call(*args, **kwargs):\n renderer, x, y, s, *_ = args\n ys.setdefault(s, set()).add(y)\n\n renderer.draw_tex = call\n fig.canvas.draw()\n assert [*ys] == ["foo", "bar"]\n # Check that both TeX strings were drawn with the same y-position for both\n # single-line substrings. Previously, there used to be an incorrect cache\n # collision with the non-TeX string (drawn first here) whose metrics would\n # get incorrectly reused by the first TeX string.\n assert len(ys["foo"]) == len(ys["bar"]) == 1\n\n info = mpl.text._get_text_metrics_with_cache_impl.cache_info()\n # Every string gets a miss for the first layouting (extents), then a hit\n # when drawing, but "foo\nbar" gets two hits as it's drawn twice.\n assert info.hits > info.misses\n\n\ndef test_annotate_offset_fontsize():\n # Test that offset_fontsize parameter works and uses accurate values\n fig, ax = plt.subplots()\n text_coords = ['offset points', 'offset fontsize']\n # 10 points should be equal to 1 fontsize unit at fontsize=10\n xy_text = [(10, 10), (1, 1)]\n anns = [ax.annotate('test', xy=(0.5, 0.5),\n xytext=xy_text[i],\n fontsize='10',\n xycoords='data',\n textcoords=text_coords[i]) for i in range(2)]\n points_coords, fontsize_coords = (ann.get_window_extent() for ann in anns)\n fig.canvas.draw()\n assert str(points_coords) == str(fontsize_coords)\n\n\ndef test_get_set_antialiased():\n txt = Text(.5, .5, "foo\nbar")\n assert txt._antialiased == mpl.rcParams['text.antialiased']\n assert txt.get_antialiased() == mpl.rcParams['text.antialiased']\n\n txt.set_antialiased(True)\n assert txt._antialiased is True\n assert txt.get_antialiased() == txt._antialiased\n\n txt.set_antialiased(False)\n assert txt._antialiased is False\n assert txt.get_antialiased() == txt._antialiased\n\n\ndef test_annotation_antialiased():\n annot = Annotation("foo\nbar", (.5, .5), antialiased=True)\n assert annot._antialiased is True\n assert annot.get_antialiased() == annot._antialiased\n\n annot2 = Annotation("foo\nbar", (.5, .5), antialiased=False)\n assert annot2._antialiased is False\n assert annot2.get_antialiased() == annot2._antialiased\n\n annot3 = Annotation("foo\nbar", (.5, .5), antialiased=False)\n annot3.set_antialiased(True)\n assert annot3.get_antialiased() is True\n assert annot3._antialiased is True\n\n annot4 = Annotation("foo\nbar", (.5, .5))\n assert annot4._antialiased == mpl.rcParams['text.antialiased']\n\n\n@check_figures_equal(extensions=["png"])\ndef test_annotate_and_offsetfrom_copy_input(fig_test, fig_ref):\n # Both approaches place the text (10, 0) pixels away from the center of the line.\n ax = fig_test.add_subplot()\n l, = ax.plot([0, 2], [0, 2])\n of_xy = np.array([.5, .5])\n ax.annotate("foo", textcoords=OffsetFrom(l, of_xy), xytext=(10, 0),\n xy=(0, 0)) # xy is unused.\n of_xy[:] = 1\n ax = fig_ref.add_subplot()\n l, = ax.plot([0, 2], [0, 2])\n an_xy = np.array([.5, .5])\n ax.annotate("foo", xy=an_xy, xycoords=l, xytext=(10, 0), textcoords="offset points")\n an_xy[:] = 2\n\n\n@check_figures_equal()\ndef test_text_antialiased_off_default_vs_manual(fig_test, fig_ref):\n fig_test.text(0.5, 0.5, '6 inches x 2 inches',\n antialiased=False)\n\n mpl.rcParams['text.antialiased'] = False\n fig_ref.text(0.5, 0.5, '6 inches x 2 inches')\n\n\n@check_figures_equal()\ndef test_text_antialiased_on_default_vs_manual(fig_test, fig_ref):\n fig_test.text(0.5, 0.5, '6 inches x 2 inches', antialiased=True)\n\n mpl.rcParams['text.antialiased'] = True\n fig_ref.text(0.5, 0.5, '6 inches x 2 inches')\n\n\ndef test_text_annotation_get_window_extent():\n figure = Figure(dpi=100)\n renderer = RendererAgg(200, 200, 100)\n\n # Only text annotation\n annotation = Annotation('test', xy=(0, 0), xycoords='figure pixels')\n annotation.set_figure(figure)\n\n text = Text(text='test', x=0, y=0)\n text.set_figure(figure)\n\n bbox = annotation.get_window_extent(renderer=renderer)\n\n text_bbox = text.get_window_extent(renderer=renderer)\n assert bbox.width == text_bbox.width\n assert bbox.height == text_bbox.height\n\n _, _, d = renderer.get_text_width_height_descent(\n 'text', annotation._fontproperties, ismath=False)\n _, _, lp_d = renderer.get_text_width_height_descent(\n 'lp', annotation._fontproperties, ismath=False)\n below_line = max(d, lp_d)\n\n # These numbers are specific to the current implementation of Text\n points = bbox.get_points()\n assert points[0, 0] == 0.0\n assert points[1, 0] == text_bbox.width\n assert points[0, 1] == -below_line\n assert points[1, 1] == text_bbox.height - below_line\n\n\ndef test_text_with_arrow_annotation_get_window_extent():\n headwidth = 21\n fig, ax = plt.subplots(dpi=100)\n txt = ax.text(s='test', x=0, y=0)\n ann = ax.annotate(\n 'test',\n xy=(0.0, 50.0),\n xytext=(50.0, 50.0), xycoords='figure pixels',\n arrowprops={\n 'facecolor': 'black', 'width': 2,\n 'headwidth': headwidth, 'shrink': 0.0})\n\n plt.draw()\n renderer = fig.canvas.renderer\n # bounding box of text\n text_bbox = txt.get_window_extent(renderer=renderer)\n # bounding box of annotation (text + arrow)\n bbox = ann.get_window_extent(renderer=renderer)\n # bounding box of arrow\n arrow_bbox = ann.arrow_patch.get_window_extent(renderer)\n # bounding box of annotation text\n ann_txt_bbox = Text.get_window_extent(ann)\n\n # make sure annotation width is 50 px wider than\n # just the text\n assert bbox.width == text_bbox.width + 50.0\n # make sure the annotation text bounding box is same size\n # as the bounding box of the same string as a Text object\n assert ann_txt_bbox.height == text_bbox.height\n assert ann_txt_bbox.width == text_bbox.width\n # compute the expected bounding box of arrow + text\n expected_bbox = mtransforms.Bbox.union([ann_txt_bbox, arrow_bbox])\n assert_almost_equal(bbox.height, expected_bbox.height)\n\n\ndef test_arrow_annotation_get_window_extent():\n dpi = 100\n dots_per_point = dpi / 72\n figure = Figure(dpi=dpi)\n figure.set_figwidth(2.0)\n figure.set_figheight(2.0)\n renderer = RendererAgg(200, 200, 100)\n\n # Text annotation with arrow; arrow dimensions are in points\n annotation = Annotation(\n '', xy=(0.0, 50.0), xytext=(50.0, 50.0), xycoords='figure pixels',\n arrowprops={\n 'facecolor': 'black', 'width': 8, 'headwidth': 10, 'shrink': 0.0})\n annotation.set_figure(figure)\n annotation.draw(renderer)\n\n bbox = annotation.get_window_extent()\n points = bbox.get_points()\n\n assert bbox.width == 50.0\n assert_almost_equal(bbox.height, 10.0 * dots_per_point)\n assert points[0, 0] == 0.0\n assert points[0, 1] == 50.0 - 5 * dots_per_point\n\n\ndef test_empty_annotation_get_window_extent():\n figure = Figure(dpi=100)\n figure.set_figwidth(2.0)\n figure.set_figheight(2.0)\n renderer = RendererAgg(200, 200, 100)\n\n # Text annotation with arrow\n annotation = Annotation(\n '', xy=(0.0, 50.0), xytext=(0.0, 50.0), xycoords='figure pixels')\n annotation.set_figure(figure)\n annotation.draw(renderer)\n\n bbox = annotation.get_window_extent()\n points = bbox.get_points()\n\n assert points[0, 0] == 0.0\n assert points[1, 0] == 0.0\n assert points[1, 1] == 50.0\n assert points[0, 1] == 50.0\n\n\n@image_comparison(baseline_images=['basictext_wrap'],\n extensions=['png'])\ndef test_basic_wrap():\n fig = plt.figure()\n plt.axis([0, 10, 0, 10])\n t = "This is a really long string that I'd rather have wrapped so that" \\n " it doesn't go outside of the figure, but if it's long enough it" \\n " will go off the top or bottom!"\n plt.text(4, 1, t, ha='left', rotation=15, wrap=True)\n plt.text(6, 5, t, ha='left', rotation=15, wrap=True)\n plt.text(5, 5, t, ha='right', rotation=-15, wrap=True)\n plt.text(5, 10, t, fontsize=18, style='oblique', ha='center',\n va='top', wrap=True)\n plt.text(3, 4, t, family='serif', style='italic', ha='right', wrap=True)\n plt.text(-1, 0, t, ha='left', rotation=-15, wrap=True)\n\n\n@image_comparison(baseline_images=['fonttext_wrap'],\n extensions=['png'])\ndef test_font_wrap():\n fig = plt.figure()\n plt.axis([0, 10, 0, 10])\n t = "This is a really long string that I'd rather have wrapped so that" \\n " it doesn't go outside of the figure, but if it's long enough it" \\n " will go off the top or bottom!"\n plt.text(4, -1, t, fontsize=18, family='serif', ha='left', rotation=15,\n wrap=True)\n plt.text(6, 5, t, family='sans serif', ha='left', rotation=15, wrap=True)\n plt.text(5, 10, t, weight='heavy', ha='center', va='top', wrap=True)\n plt.text(3, 4, t, family='monospace', ha='right', wrap=True)\n plt.text(-1, 0, t, fontsize=14, style='italic', ha='left', rotation=-15,\n wrap=True)\n | .venv\Lib\site-packages\matplotlib\tests\test_text.py | test_text.py | Python | 38,473 | 0.95 | 0.093228 | 0.066667 | awesome-app | 935 | 2025-04-19T13:03:51.042043 | MIT | true | 95410cbd9e1d16fc9504e2b787a84281 |
import copy\n\nfrom matplotlib.textpath import TextPath\n\n\ndef test_copy():\n tp = TextPath((0, 0), ".")\n assert copy.deepcopy(tp).vertices is not tp.vertices\n assert (copy.deepcopy(tp).vertices == tp.vertices).all()\n assert copy.copy(tp).vertices is tp.vertices\n | .venv\Lib\site-packages\matplotlib\tests\test_textpath.py | test_textpath.py | Python | 271 | 0.85 | 0.1 | 0 | python-kit | 760 | 2024-08-12T04:05:31.369808 | MIT | true | 37f9aa69d931029ad4cdd72f769690e8 |
from contextlib import nullcontext\nimport itertools\nimport locale\nimport logging\nimport re\nfrom packaging.version import parse as parse_version\n\nimport numpy as np\nfrom numpy.testing import assert_almost_equal, assert_array_equal\nimport pytest\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\n\n\nclass TestMaxNLocator:\n basic_data = [\n (20, 100, np.array([20., 40., 60., 80., 100.])),\n (0.001, 0.0001, np.array([0., 0.0002, 0.0004, 0.0006, 0.0008, 0.001])),\n (-1e15, 1e15, np.array([-1.0e+15, -5.0e+14, 0e+00, 5e+14, 1.0e+15])),\n (0, 0.85e-50, np.arange(6) * 2e-51),\n (-0.85e-50, 0, np.arange(-5, 1) * 2e-51),\n ]\n\n integer_data = [\n (-0.1, 1.1, None, np.array([-1, 0, 1, 2])),\n (-0.1, 0.95, None, np.array([-0.25, 0, 0.25, 0.5, 0.75, 1.0])),\n (1, 55, [1, 1.5, 5, 6, 10], np.array([0, 15, 30, 45, 60])),\n ]\n\n @pytest.mark.parametrize('vmin, vmax, expected', basic_data)\n def test_basic(self, vmin, vmax, expected):\n loc = mticker.MaxNLocator(nbins=5)\n assert_almost_equal(loc.tick_values(vmin, vmax), expected)\n\n @pytest.mark.parametrize('vmin, vmax, steps, expected', integer_data)\n def test_integer(self, vmin, vmax, steps, expected):\n loc = mticker.MaxNLocator(nbins=5, integer=True, steps=steps)\n assert_almost_equal(loc.tick_values(vmin, vmax), expected)\n\n @pytest.mark.parametrize('kwargs, errortype, match', [\n ({'foo': 0}, TypeError,\n re.escape("set_params() got an unexpected keyword argument 'foo'")),\n ({'steps': [2, 1]}, ValueError, "steps argument must be an increasing"),\n ({'steps': 2}, ValueError, "steps argument must be an increasing"),\n ({'steps': [2, 11]}, ValueError, "steps argument must be an increasing"),\n ])\n def test_errors(self, kwargs, errortype, match):\n with pytest.raises(errortype, match=match):\n mticker.MaxNLocator(**kwargs)\n\n @pytest.mark.parametrize('steps, result', [\n ([1, 2, 10], [1, 2, 10]),\n ([2, 10], [1, 2, 10]),\n ([1, 2], [1, 2, 10]),\n ([2], [1, 2, 10]),\n ])\n def test_padding(self, steps, result):\n loc = mticker.MaxNLocator(steps=steps)\n assert (loc._steps == result).all()\n\n\nclass TestLinearLocator:\n def test_basic(self):\n loc = mticker.LinearLocator(numticks=3)\n test_value = np.array([-0.8, -0.3, 0.2])\n assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value)\n\n def test_zero_numticks(self):\n loc = mticker.LinearLocator(numticks=0)\n loc.tick_values(-0.8, 0.2) == []\n\n def test_set_params(self):\n """\n Create linear locator with presets={}, numticks=2 and change it to\n something else. See if change was successful. Should not exception.\n """\n loc = mticker.LinearLocator(numticks=2)\n loc.set_params(numticks=8, presets={(0, 1): []})\n assert loc.numticks == 8\n assert loc.presets == {(0, 1): []}\n\n def test_presets(self):\n loc = mticker.LinearLocator(presets={(1, 2): [1, 1.25, 1.75],\n (0, 2): [0.5, 1.5]})\n assert loc.tick_values(1, 2) == [1, 1.25, 1.75]\n assert loc.tick_values(2, 1) == [1, 1.25, 1.75]\n assert loc.tick_values(0, 2) == [0.5, 1.5]\n assert loc.tick_values(0.0, 2.0) == [0.5, 1.5]\n assert (loc.tick_values(0, 1) == np.linspace(0, 1, 11)).all()\n\n\nclass TestMultipleLocator:\n def test_basic(self):\n loc = mticker.MultipleLocator(base=3.147)\n test_value = np.array([-9.441, -6.294, -3.147, 0., 3.147, 6.294,\n 9.441, 12.588])\n assert_almost_equal(loc.tick_values(-7, 10), test_value)\n\n def test_basic_with_offset(self):\n loc = mticker.MultipleLocator(base=3.147, offset=1.2)\n test_value = np.array([-8.241, -5.094, -1.947, 1.2, 4.347, 7.494,\n 10.641])\n assert_almost_equal(loc.tick_values(-7, 10), test_value)\n\n def test_view_limits(self):\n """\n Test basic behavior of view limits.\n """\n with mpl.rc_context({'axes.autolimit_mode': 'data'}):\n loc = mticker.MultipleLocator(base=3.147)\n assert_almost_equal(loc.view_limits(-5, 5), (-5, 5))\n\n def test_view_limits_round_numbers(self):\n """\n Test that everything works properly with 'round_numbers' for auto\n limit.\n """\n with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}):\n loc = mticker.MultipleLocator(base=3.147)\n assert_almost_equal(loc.view_limits(-4, 4), (-6.294, 6.294))\n\n def test_view_limits_round_numbers_with_offset(self):\n """\n Test that everything works properly with 'round_numbers' for auto\n limit.\n """\n with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}):\n loc = mticker.MultipleLocator(base=3.147, offset=1.3)\n assert_almost_equal(loc.view_limits(-4, 4), (-4.994, 4.447))\n\n def test_view_limits_single_bin(self):\n """\n Test that 'round_numbers' works properly with a single bin.\n """\n with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}):\n loc = mticker.MaxNLocator(nbins=1)\n assert_almost_equal(loc.view_limits(-2.3, 2.3), (-4, 4))\n\n def test_set_params(self):\n """\n Create multiple locator with 0.7 base, and change it to something else.\n See if change was successful.\n """\n mult = mticker.MultipleLocator(base=0.7)\n mult.set_params(base=1.7)\n assert mult._edge.step == 1.7\n mult.set_params(offset=3)\n assert mult._offset == 3\n\n\nclass TestAutoMinorLocator:\n def test_basic(self):\n fig, ax = plt.subplots()\n ax.set_xlim(0, 1.39)\n ax.minorticks_on()\n test_value = np.array([0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45,\n 0.5, 0.55, 0.65, 0.7, 0.75, 0.85, 0.9,\n 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35])\n assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value)\n\n # NB: the following values are assuming that *xlim* is [0, 5]\n params = [\n (0, 0), # no major tick => no minor tick either\n (1, 0) # a single major tick => no minor tick\n ]\n\n def test_first_and_last_minorticks(self):\n """\n Test that first and last minor tick appear as expected.\n """\n # This test is related to issue #22331\n fig, ax = plt.subplots()\n ax.set_xlim(-1.9, 1.9)\n ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())\n test_value = np.array([-1.9, -1.8, -1.7, -1.6, -1.4, -1.3, -1.2, -1.1,\n -0.9, -0.8, -0.7, -0.6, -0.4, -0.3, -0.2, -0.1,\n 0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9, 1.1,\n 1.2, 1.3, 1.4, 1.6, 1.7, 1.8, 1.9])\n assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value)\n\n ax.set_xlim(-5, 5)\n test_value = np.array([-5.0, -4.5, -3.5, -3.0, -2.5, -1.5, -1.0, -0.5,\n 0.5, 1.0, 1.5, 2.5, 3.0, 3.5, 4.5, 5.0])\n assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value)\n\n @pytest.mark.parametrize('nb_majorticks, expected_nb_minorticks', params)\n def test_low_number_of_majorticks(\n self, nb_majorticks, expected_nb_minorticks):\n # This test is related to issue #8804\n fig, ax = plt.subplots()\n xlims = (0, 5) # easier to test the different code paths\n ax.set_xlim(*xlims)\n ax.set_xticks(np.linspace(xlims[0], xlims[1], nb_majorticks))\n ax.minorticks_on()\n ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())\n assert len(ax.xaxis.get_minorticklocs()) == expected_nb_minorticks\n\n majorstep_minordivisions = [(1, 5),\n (2, 4),\n (2.5, 5),\n (5, 5),\n (10, 5)]\n\n # This test is meant to verify the parameterization for\n # test_number_of_minor_ticks\n def test_using_all_default_major_steps(self):\n with mpl.rc_context({'_internal.classic_mode': False}):\n majorsteps = [x[0] for x in self.majorstep_minordivisions]\n np.testing.assert_allclose(majorsteps,\n mticker.AutoLocator()._steps)\n\n @pytest.mark.parametrize('major_step, expected_nb_minordivisions',\n majorstep_minordivisions)\n def test_number_of_minor_ticks(\n self, major_step, expected_nb_minordivisions):\n fig, ax = plt.subplots()\n xlims = (0, major_step)\n ax.set_xlim(*xlims)\n ax.set_xticks(xlims)\n ax.minorticks_on()\n ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())\n nb_minor_divisions = len(ax.xaxis.get_minorticklocs()) + 1\n assert nb_minor_divisions == expected_nb_minordivisions\n\n limits = [(0, 1.39), (0, 0.139),\n (0, 0.11e-19), (0, 0.112e-12),\n (-2.0e-07, -3.3e-08), (1.20e-06, 1.42e-06),\n (-1.34e-06, -1.44e-06), (-8.76e-07, -1.51e-06)]\n\n reference = [\n [0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7,\n 0.75, 0.85, 0.9, 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35],\n [0.005, 0.01, 0.015, 0.025, 0.03, 0.035, 0.045, 0.05, 0.055, 0.065,\n 0.07, 0.075, 0.085, 0.09, 0.095, 0.105, 0.11, 0.115, 0.125, 0.13,\n 0.135],\n [5.00e-22, 1.00e-21, 1.50e-21, 2.50e-21, 3.00e-21, 3.50e-21, 4.50e-21,\n 5.00e-21, 5.50e-21, 6.50e-21, 7.00e-21, 7.50e-21, 8.50e-21, 9.00e-21,\n 9.50e-21, 1.05e-20, 1.10e-20],\n [5.00e-15, 1.00e-14, 1.50e-14, 2.50e-14, 3.00e-14, 3.50e-14, 4.50e-14,\n 5.00e-14, 5.50e-14, 6.50e-14, 7.00e-14, 7.50e-14, 8.50e-14, 9.00e-14,\n 9.50e-14, 1.05e-13, 1.10e-13],\n [-1.95e-07, -1.90e-07, -1.85e-07, -1.75e-07, -1.70e-07, -1.65e-07,\n -1.55e-07, -1.50e-07, -1.45e-07, -1.35e-07, -1.30e-07, -1.25e-07,\n -1.15e-07, -1.10e-07, -1.05e-07, -9.50e-08, -9.00e-08, -8.50e-08,\n -7.50e-08, -7.00e-08, -6.50e-08, -5.50e-08, -5.00e-08, -4.50e-08,\n -3.50e-08],\n [1.21e-06, 1.22e-06, 1.23e-06, 1.24e-06, 1.26e-06, 1.27e-06, 1.28e-06,\n 1.29e-06, 1.31e-06, 1.32e-06, 1.33e-06, 1.34e-06, 1.36e-06, 1.37e-06,\n 1.38e-06, 1.39e-06, 1.41e-06, 1.42e-06],\n [-1.435e-06, -1.430e-06, -1.425e-06, -1.415e-06, -1.410e-06,\n -1.405e-06, -1.395e-06, -1.390e-06, -1.385e-06, -1.375e-06,\n -1.370e-06, -1.365e-06, -1.355e-06, -1.350e-06, -1.345e-06],\n [-1.48e-06, -1.46e-06, -1.44e-06, -1.42e-06, -1.38e-06, -1.36e-06,\n -1.34e-06, -1.32e-06, -1.28e-06, -1.26e-06, -1.24e-06, -1.22e-06,\n -1.18e-06, -1.16e-06, -1.14e-06, -1.12e-06, -1.08e-06, -1.06e-06,\n -1.04e-06, -1.02e-06, -9.80e-07, -9.60e-07, -9.40e-07, -9.20e-07,\n -8.80e-07]]\n\n additional_data = list(zip(limits, reference))\n\n @pytest.mark.parametrize('lim, ref', additional_data)\n def test_additional(self, lim, ref):\n fig, ax = plt.subplots()\n\n ax.minorticks_on()\n ax.grid(True, 'minor', 'y', linewidth=1)\n ax.grid(True, 'major', color='k', linewidth=1)\n ax.set_ylim(lim)\n\n assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref)\n\n @pytest.mark.parametrize('use_rcparam', [False, True])\n @pytest.mark.parametrize(\n 'lim, ref', [\n ((0, 1.39),\n [0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7,\n 0.75, 0.85, 0.9, 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35]),\n ((0, 0.139),\n [0.005, 0.01, 0.015, 0.025, 0.03, 0.035, 0.045, 0.05, 0.055,\n 0.065, 0.07, 0.075, 0.085, 0.09, 0.095, 0.105, 0.11, 0.115,\n 0.125, 0.13, 0.135]),\n ])\n def test_number_of_minor_ticks_auto(self, lim, ref, use_rcparam):\n if use_rcparam:\n context = {'xtick.minor.ndivs': 'auto', 'ytick.minor.ndivs': 'auto'}\n kwargs = {}\n else:\n context = {}\n kwargs = {'n': 'auto'}\n\n with mpl.rc_context(context):\n fig, ax = plt.subplots()\n ax.set_xlim(*lim)\n ax.set_ylim(*lim)\n ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))\n ax.yaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))\n assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), ref)\n assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref)\n\n @pytest.mark.parametrize('use_rcparam', [False, True])\n @pytest.mark.parametrize(\n 'n, lim, ref', [\n (2, (0, 4), [0.5, 1.5, 2.5, 3.5]),\n (4, (0, 2), [0.25, 0.5, 0.75, 1.25, 1.5, 1.75]),\n (10, (0, 1), [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]),\n ])\n def test_number_of_minor_ticks_int(self, n, lim, ref, use_rcparam):\n if use_rcparam:\n context = {'xtick.minor.ndivs': n, 'ytick.minor.ndivs': n}\n kwargs = {}\n else:\n context = {}\n kwargs = {'n': n}\n\n with mpl.rc_context(context):\n fig, ax = plt.subplots()\n ax.set_xlim(*lim)\n ax.set_ylim(*lim)\n ax.xaxis.set_major_locator(mticker.MultipleLocator(1))\n ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))\n ax.yaxis.set_major_locator(mticker.MultipleLocator(1))\n ax.yaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))\n assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), ref)\n assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref)\n\n\nclass TestLogLocator:\n def test_basic(self):\n loc = mticker.LogLocator(numticks=5)\n with pytest.raises(ValueError):\n loc.tick_values(0, 1000)\n\n test_value = np.array([1.00000000e-05, 1.00000000e-03, 1.00000000e-01,\n 1.00000000e+01, 1.00000000e+03, 1.00000000e+05,\n 1.00000000e+07, 1.000000000e+09])\n assert_almost_equal(loc.tick_values(0.001, 1.1e5), test_value)\n\n loc = mticker.LogLocator(base=2)\n test_value = np.array([0.5, 1., 2., 4., 8., 16., 32., 64., 128., 256.])\n assert_almost_equal(loc.tick_values(1, 100), test_value)\n\n def test_polar_axes(self):\n """\n Polar Axes have a different ticking logic.\n """\n fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})\n ax.set_yscale('log')\n ax.set_ylim(1, 100)\n assert_array_equal(ax.get_yticks(), [10, 100, 1000])\n\n def test_switch_to_autolocator(self):\n loc = mticker.LogLocator(subs="all")\n assert_array_equal(loc.tick_values(0.45, 0.55),\n [0.44, 0.46, 0.48, 0.5, 0.52, 0.54, 0.56])\n # check that we *skip* 1.0, and 10, because this is a minor locator\n loc = mticker.LogLocator(subs=np.arange(2, 10))\n assert 1.0 not in loc.tick_values(0.9, 20.)\n assert 10.0 not in loc.tick_values(0.9, 20.)\n\n def test_set_params(self):\n """\n Create log locator with default value, base=10.0, subs=[1.0],\n numticks=15 and change it to something else.\n See if change was successful. Should not raise exception.\n """\n loc = mticker.LogLocator()\n loc.set_params(numticks=7, subs=[2.0], base=4)\n assert loc.numticks == 7\n assert loc._base == 4\n assert list(loc._subs) == [2.0]\n\n def test_tick_values_correct(self):\n ll = mticker.LogLocator(subs=(1, 2, 5))\n test_value = np.array([1.e-01, 2.e-01, 5.e-01, 1.e+00, 2.e+00, 5.e+00,\n 1.e+01, 2.e+01, 5.e+01, 1.e+02, 2.e+02, 5.e+02,\n 1.e+03, 2.e+03, 5.e+03, 1.e+04, 2.e+04, 5.e+04,\n 1.e+05, 2.e+05, 5.e+05, 1.e+06, 2.e+06, 5.e+06,\n 1.e+07, 2.e+07, 5.e+07, 1.e+08, 2.e+08, 5.e+08])\n assert_almost_equal(ll.tick_values(1, 1e7), test_value)\n\n def test_tick_values_not_empty(self):\n mpl.rcParams['_internal.classic_mode'] = False\n ll = mticker.LogLocator(subs=(1, 2, 5))\n test_value = np.array([1.e-01, 2.e-01, 5.e-01, 1.e+00, 2.e+00, 5.e+00,\n 1.e+01, 2.e+01, 5.e+01, 1.e+02, 2.e+02, 5.e+02,\n 1.e+03, 2.e+03, 5.e+03, 1.e+04, 2.e+04, 5.e+04,\n 1.e+05, 2.e+05, 5.e+05, 1.e+06, 2.e+06, 5.e+06,\n 1.e+07, 2.e+07, 5.e+07, 1.e+08, 2.e+08, 5.e+08,\n 1.e+09, 2.e+09, 5.e+09])\n assert_almost_equal(ll.tick_values(1, 1e8), test_value)\n\n def test_multiple_shared_axes(self):\n rng = np.random.default_rng(19680801)\n dummy_data = [rng.normal(size=100), [], []]\n fig, axes = plt.subplots(len(dummy_data), sharex=True, sharey=True)\n\n for ax, data in zip(axes.flatten(), dummy_data):\n ax.hist(data, bins=10)\n ax.set_yscale('log', nonpositive='clip')\n\n for ax in axes.flatten():\n assert all(ax.get_yticks() == axes[0].get_yticks())\n assert ax.get_ylim() == axes[0].get_ylim()\n\n\nclass TestNullLocator:\n def test_set_params(self):\n """\n Create null locator, and attempt to call set_params() on it.\n Should not exception, and should raise a warning.\n """\n loc = mticker.NullLocator()\n with pytest.warns(UserWarning):\n loc.set_params()\n\n\nclass _LogitHelper:\n @staticmethod\n def isclose(x, y):\n return (np.isclose(-np.log(1/x-1), -np.log(1/y-1))\n if 0 < x < 1 and 0 < y < 1 else False)\n\n @staticmethod\n def assert_almost_equal(x, y):\n ax = np.array(x)\n ay = np.array(y)\n assert np.all(ax > 0) and np.all(ax < 1)\n assert np.all(ay > 0) and np.all(ay < 1)\n lx = -np.log(1/ax-1)\n ly = -np.log(1/ay-1)\n assert_almost_equal(lx, ly)\n\n\nclass TestLogitLocator:\n ref_basic_limits = [\n (5e-2, 1 - 5e-2),\n (5e-3, 1 - 5e-3),\n (5e-4, 1 - 5e-4),\n (5e-5, 1 - 5e-5),\n (5e-6, 1 - 5e-6),\n (5e-7, 1 - 5e-7),\n (5e-8, 1 - 5e-8),\n (5e-9, 1 - 5e-9),\n ]\n\n ref_basic_major_ticks = [\n 1 / (10 ** np.arange(1, 3)),\n 1 / (10 ** np.arange(1, 4)),\n 1 / (10 ** np.arange(1, 5)),\n 1 / (10 ** np.arange(1, 6)),\n 1 / (10 ** np.arange(1, 7)),\n 1 / (10 ** np.arange(1, 8)),\n 1 / (10 ** np.arange(1, 9)),\n 1 / (10 ** np.arange(1, 10)),\n ]\n\n ref_maxn_limits = [(0.4, 0.6), (5e-2, 2e-1), (1 - 2e-1, 1 - 5e-2)]\n\n @pytest.mark.parametrize(\n "lims, expected_low_ticks",\n zip(ref_basic_limits, ref_basic_major_ticks),\n )\n def test_basic_major(self, lims, expected_low_ticks):\n """\n Create logit locator with huge number of major, and tests ticks.\n """\n expected_ticks = sorted(\n [*expected_low_ticks, 0.5, *(1 - expected_low_ticks)]\n )\n loc = mticker.LogitLocator(nbins=100)\n _LogitHelper.assert_almost_equal(\n loc.tick_values(*lims),\n expected_ticks\n )\n\n @pytest.mark.parametrize("lims", ref_maxn_limits)\n def test_maxn_major(self, lims):\n """\n When the axis is zoomed, the locator must have the same behavior as\n MaxNLocator.\n """\n loc = mticker.LogitLocator(nbins=100)\n maxn_loc = mticker.MaxNLocator(nbins=100, steps=[1, 2, 5, 10])\n for nbins in (4, 8, 16):\n loc.set_params(nbins=nbins)\n maxn_loc.set_params(nbins=nbins)\n ticks = loc.tick_values(*lims)\n maxn_ticks = maxn_loc.tick_values(*lims)\n assert ticks.shape == maxn_ticks.shape\n assert (ticks == maxn_ticks).all()\n\n @pytest.mark.parametrize("lims", ref_basic_limits + ref_maxn_limits)\n def test_nbins_major(self, lims):\n """\n Assert logit locator for respecting nbins param.\n """\n\n basic_needed = int(-np.floor(np.log10(lims[0]))) * 2 + 1\n loc = mticker.LogitLocator(nbins=100)\n for nbins in range(basic_needed, 2, -1):\n loc.set_params(nbins=nbins)\n assert len(loc.tick_values(*lims)) <= nbins + 2\n\n @pytest.mark.parametrize(\n "lims, expected_low_ticks",\n zip(ref_basic_limits, ref_basic_major_ticks),\n )\n def test_minor(self, lims, expected_low_ticks):\n """\n In large scale, test the presence of minor,\n and assert no minor when major are subsampled.\n """\n\n expected_ticks = sorted(\n [*expected_low_ticks, 0.5, *(1 - expected_low_ticks)]\n )\n basic_needed = len(expected_ticks)\n loc = mticker.LogitLocator(nbins=100)\n minor_loc = mticker.LogitLocator(nbins=100, minor=True)\n for nbins in range(basic_needed, 2, -1):\n loc.set_params(nbins=nbins)\n minor_loc.set_params(nbins=nbins)\n major_ticks = loc.tick_values(*lims)\n minor_ticks = minor_loc.tick_values(*lims)\n if len(major_ticks) >= len(expected_ticks):\n # no subsample, we must have a lot of minors ticks\n assert (len(major_ticks) - 1) * 5 < len(minor_ticks)\n else:\n # subsample\n _LogitHelper.assert_almost_equal(\n sorted([*major_ticks, *minor_ticks]), expected_ticks)\n\n def test_minor_attr(self):\n loc = mticker.LogitLocator(nbins=100)\n assert not loc.minor\n loc.minor = True\n assert loc.minor\n loc.set_params(minor=False)\n assert not loc.minor\n\n acceptable_vmin_vmax = [\n *(2.5 ** np.arange(-3, 0)),\n *(1 - 2.5 ** np.arange(-3, 0)),\n ]\n\n @pytest.mark.parametrize(\n "lims",\n [\n (a, b)\n for (a, b) in itertools.product(acceptable_vmin_vmax, repeat=2)\n if a != b\n ],\n )\n def test_nonsingular_ok(self, lims):\n """\n Create logit locator, and test the nonsingular method for acceptable\n value\n """\n loc = mticker.LogitLocator()\n lims2 = loc.nonsingular(*lims)\n assert sorted(lims) == sorted(lims2)\n\n @pytest.mark.parametrize("okval", acceptable_vmin_vmax)\n def test_nonsingular_nok(self, okval):\n """\n Create logit locator, and test the nonsingular method for non\n acceptable value\n """\n loc = mticker.LogitLocator()\n vmin, vmax = (-1, okval)\n vmin2, vmax2 = loc.nonsingular(vmin, vmax)\n assert vmax2 == vmax\n assert 0 < vmin2 < vmax2\n vmin, vmax = (okval, 2)\n vmin2, vmax2 = loc.nonsingular(vmin, vmax)\n assert vmin2 == vmin\n assert vmin2 < vmax2 < 1\n\n\nclass TestFixedLocator:\n def test_set_params(self):\n """\n Create fixed locator with 5 nbins, and change it to something else.\n See if change was successful.\n Should not exception.\n """\n fixed = mticker.FixedLocator(range(0, 24), nbins=5)\n fixed.set_params(nbins=7)\n assert fixed.nbins == 7\n\n\nclass TestIndexLocator:\n def test_set_params(self):\n """\n Create index locator with 3 base, 4 offset. and change it to something\n else. See if change was successful.\n Should not exception.\n """\n index = mticker.IndexLocator(base=3, offset=4)\n index.set_params(base=7, offset=7)\n assert index._base == 7\n assert index.offset == 7\n\n\nclass TestSymmetricalLogLocator:\n def test_set_params(self):\n """\n Create symmetrical log locator with default subs =[1.0] numticks = 15,\n and change it to something else.\n See if change was successful.\n Should not exception.\n """\n sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)\n sym.set_params(subs=[2.0], numticks=8)\n assert sym._subs == [2.0]\n assert sym.numticks == 8\n\n @pytest.mark.parametrize(\n 'vmin, vmax, expected',\n [\n (0, 1, [0, 1]),\n (-1, 1, [-1, 0, 1]),\n ],\n )\n def test_values(self, vmin, vmax, expected):\n # https://github.com/matplotlib/matplotlib/issues/25945\n sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)\n ticks = sym.tick_values(vmin=vmin, vmax=vmax)\n assert_array_equal(ticks, expected)\n\n def test_subs(self):\n sym = mticker.SymmetricalLogLocator(base=10, linthresh=1, subs=[2.0, 4.0])\n sym.create_dummy_axis()\n sym.axis.set_view_interval(-10, 10)\n assert_array_equal(sym(), [-20, -40, -2, -4, 0, 2, 4, 20, 40])\n\n def test_extending(self):\n sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)\n sym.create_dummy_axis()\n sym.axis.set_view_interval(8, 9)\n assert (sym() == [1.0]).all()\n sym.axis.set_view_interval(8, 12)\n assert (sym() == [1.0, 10.0]).all()\n assert sym.view_limits(10, 10) == (1, 100)\n assert sym.view_limits(-10, -10) == (-100, -1)\n assert sym.view_limits(0, 0) == (-0.001, 0.001)\n\n\nclass TestAsinhLocator:\n def test_init(self):\n lctr = mticker.AsinhLocator(linear_width=2.718, numticks=19)\n assert lctr.linear_width == 2.718\n assert lctr.numticks == 19\n assert lctr.base == 10\n\n def test_set_params(self):\n lctr = mticker.AsinhLocator(linear_width=5,\n numticks=17, symthresh=0.125,\n base=4, subs=(2.5, 3.25))\n assert lctr.numticks == 17\n assert lctr.symthresh == 0.125\n assert lctr.base == 4\n assert lctr.subs == (2.5, 3.25)\n\n lctr.set_params(numticks=23)\n assert lctr.numticks == 23\n lctr.set_params(None)\n assert lctr.numticks == 23\n\n lctr.set_params(symthresh=0.5)\n assert lctr.symthresh == 0.5\n lctr.set_params(symthresh=None)\n assert lctr.symthresh == 0.5\n\n lctr.set_params(base=7)\n assert lctr.base == 7\n lctr.set_params(base=None)\n assert lctr.base == 7\n\n lctr.set_params(subs=(2, 4.125))\n assert lctr.subs == (2, 4.125)\n lctr.set_params(subs=None)\n assert lctr.subs == (2, 4.125)\n lctr.set_params(subs=[])\n assert lctr.subs is None\n\n def test_linear_values(self):\n lctr = mticker.AsinhLocator(linear_width=100, numticks=11, base=0)\n\n assert_almost_equal(lctr.tick_values(-1, 1),\n np.arange(-1, 1.01, 0.2))\n assert_almost_equal(lctr.tick_values(-0.1, 0.1),\n np.arange(-0.1, 0.101, 0.02))\n assert_almost_equal(lctr.tick_values(-0.01, 0.01),\n np.arange(-0.01, 0.0101, 0.002))\n\n def test_wide_values(self):\n lctr = mticker.AsinhLocator(linear_width=0.1, numticks=11, base=0)\n\n assert_almost_equal(lctr.tick_values(-100, 100),\n [-100, -20, -5, -1, -0.2,\n 0, 0.2, 1, 5, 20, 100])\n assert_almost_equal(lctr.tick_values(-1000, 1000),\n [-1000, -100, -20, -3, -0.4,\n 0, 0.4, 3, 20, 100, 1000])\n\n def test_near_zero(self):\n """Check that manually injected zero will supersede nearby tick"""\n lctr = mticker.AsinhLocator(linear_width=100, numticks=3, base=0)\n\n assert_almost_equal(lctr.tick_values(-1.1, 0.9), [-1.0, 0.0, 0.9])\n\n def test_fallback(self):\n lctr = mticker.AsinhLocator(1.0, numticks=11)\n\n assert_almost_equal(lctr.tick_values(101, 102),\n np.arange(101, 102.01, 0.1))\n\n def test_symmetrizing(self):\n lctr = mticker.AsinhLocator(linear_width=1, numticks=3,\n symthresh=0.25, base=0)\n lctr.create_dummy_axis()\n\n lctr.axis.set_view_interval(-1, 2)\n assert_almost_equal(lctr(), [-1, 0, 2])\n\n lctr.axis.set_view_interval(-1, 0.9)\n assert_almost_equal(lctr(), [-1, 0, 1])\n\n lctr.axis.set_view_interval(-0.85, 1.05)\n assert_almost_equal(lctr(), [-1, 0, 1])\n\n lctr.axis.set_view_interval(1, 1.1)\n assert_almost_equal(lctr(), [1, 1.05, 1.1])\n\n def test_base_rounding(self):\n lctr10 = mticker.AsinhLocator(linear_width=1, numticks=8,\n base=10, subs=(1, 3, 5))\n assert_almost_equal(lctr10.tick_values(-110, 110),\n [-500, -300, -100, -50, -30, -10, -5, -3, -1,\n -0.5, -0.3, -0.1, 0, 0.1, 0.3, 0.5,\n 1, 3, 5, 10, 30, 50, 100, 300, 500])\n\n lctr5 = mticker.AsinhLocator(linear_width=1, numticks=20, base=5)\n assert_almost_equal(lctr5.tick_values(-1050, 1050),\n [-625, -125, -25, -5, -1, -0.2, 0,\n 0.2, 1, 5, 25, 125, 625])\n\n\nclass TestScalarFormatter:\n offset_data = [\n (123, 189, 0),\n (-189, -123, 0),\n (12341, 12349, 12340),\n (-12349, -12341, -12340),\n (99999.5, 100010.5, 100000),\n (-100010.5, -99999.5, -100000),\n (99990.5, 100000.5, 100000),\n (-100000.5, -99990.5, -100000),\n (1233999, 1234001, 1234000),\n (-1234001, -1233999, -1234000),\n (1, 1, 1),\n (123, 123, 0),\n # Test cases courtesy of @WeatherGod\n (.4538, .4578, .45),\n (3789.12, 3783.1, 3780),\n (45124.3, 45831.75, 45000),\n (0.000721, 0.0007243, 0.00072),\n (12592.82, 12591.43, 12590),\n (9., 12., 0),\n (900., 1200., 0),\n (1900., 1200., 0),\n (0.99, 1.01, 1),\n (9.99, 10.01, 10),\n (99.99, 100.01, 100),\n (5.99, 6.01, 6),\n (15.99, 16.01, 16),\n (-0.452, 0.492, 0),\n (-0.492, 0.492, 0),\n (12331.4, 12350.5, 12300),\n (-12335.3, 12335.3, 0),\n ]\n\n use_offset_data = [True, False]\n\n useMathText_data = [True, False]\n\n # (sci_type, scilimits, lim, orderOfMag, fewticks)\n scilimits_data = [\n (False, (0, 0), (10.0, 20.0), 0, False),\n (True, (-2, 2), (-10, 20), 0, False),\n (True, (-2, 2), (-20, 10), 0, False),\n (True, (-2, 2), (-110, 120), 2, False),\n (True, (-2, 2), (-120, 110), 2, False),\n (True, (-2, 2), (-.001, 0.002), -3, False),\n (True, (-7, 7), (0.18e10, 0.83e10), 9, True),\n (True, (0, 0), (-1e5, 1e5), 5, False),\n (True, (6, 6), (-1e5, 1e5), 6, False),\n ]\n\n cursor_data = [\n [0., "0.000"],\n [0.0123, "0.012"],\n [0.123, "0.123"],\n [1.23, "1.230"],\n [12.3, "12.300"],\n ]\n\n format_data = [\n (.1, "1e-1"),\n (.11, "1.1e-1"),\n (1e8, "1e8"),\n (1.1e8, "1.1e8"),\n ]\n\n @pytest.mark.parametrize('unicode_minus, result',\n [(True, "\N{MINUS SIGN}1"), (False, "-1")])\n def test_unicode_minus(self, unicode_minus, result):\n mpl.rcParams['axes.unicode_minus'] = unicode_minus\n assert (\n plt.gca().xaxis.get_major_formatter().format_data_short(-1).strip()\n == result)\n\n @pytest.mark.parametrize('left, right, offset', offset_data)\n def test_offset_value(self, left, right, offset):\n fig, ax = plt.subplots()\n formatter = ax.xaxis.get_major_formatter()\n\n with (pytest.warns(UserWarning, match='Attempting to set identical')\n if left == right else nullcontext()):\n ax.set_xlim(left, right)\n ax.xaxis._update_ticks()\n assert formatter.offset == offset\n\n with (pytest.warns(UserWarning, match='Attempting to set identical')\n if left == right else nullcontext()):\n ax.set_xlim(right, left)\n ax.xaxis._update_ticks()\n assert formatter.offset == offset\n\n @pytest.mark.parametrize('use_offset', use_offset_data)\n def test_use_offset(self, use_offset):\n with mpl.rc_context({'axes.formatter.useoffset': use_offset}):\n tmp_form = mticker.ScalarFormatter()\n assert use_offset == tmp_form.get_useOffset()\n assert tmp_form.offset == 0\n\n @pytest.mark.parametrize('use_math_text', useMathText_data)\n def test_useMathText(self, use_math_text):\n with mpl.rc_context({'axes.formatter.use_mathtext': use_math_text}):\n tmp_form = mticker.ScalarFormatter()\n assert use_math_text == tmp_form.get_useMathText()\n\n def test_set_use_offset_float(self):\n tmp_form = mticker.ScalarFormatter()\n tmp_form.set_useOffset(0.5)\n assert not tmp_form.get_useOffset()\n assert tmp_form.offset == 0.5\n\n def test_use_locale(self):\n conv = locale.localeconv()\n sep = conv['thousands_sep']\n if not sep or conv['grouping'][-1:] in ([], [locale.CHAR_MAX]):\n pytest.skip('Locale does not apply grouping') # pragma: no cover\n\n with mpl.rc_context({'axes.formatter.use_locale': True}):\n tmp_form = mticker.ScalarFormatter()\n assert tmp_form.get_useLocale()\n\n tmp_form.create_dummy_axis()\n tmp_form.axis.set_data_interval(0, 10)\n tmp_form.set_locs([1, 2, 3])\n assert sep in tmp_form(1e9)\n\n @pytest.mark.parametrize(\n 'sci_type, scilimits, lim, orderOfMag, fewticks', scilimits_data)\n def test_scilimits(self, sci_type, scilimits, lim, orderOfMag, fewticks):\n tmp_form = mticker.ScalarFormatter()\n tmp_form.set_scientific(sci_type)\n tmp_form.set_powerlimits(scilimits)\n fig, ax = plt.subplots()\n ax.yaxis.set_major_formatter(tmp_form)\n ax.set_ylim(*lim)\n if fewticks:\n ax.yaxis.set_major_locator(mticker.MaxNLocator(4))\n\n tmp_form.set_locs(ax.yaxis.get_majorticklocs())\n assert orderOfMag == tmp_form.orderOfMagnitude\n\n @pytest.mark.parametrize('value, expected', format_data)\n def test_format_data(self, value, expected):\n mpl.rcParams['axes.unicode_minus'] = False\n sf = mticker.ScalarFormatter()\n assert sf.format_data(value) == expected\n\n @pytest.mark.parametrize('data, expected', cursor_data)\n def test_cursor_precision(self, data, expected):\n fig, ax = plt.subplots()\n ax.set_xlim(-1, 1) # Pointing precision of 0.001.\n fmt = ax.xaxis.get_major_formatter().format_data_short\n assert fmt(data) == expected\n\n @pytest.mark.parametrize('data, expected', cursor_data)\n def test_cursor_dummy_axis(self, data, expected):\n # Issue #17624\n sf = mticker.ScalarFormatter()\n sf.create_dummy_axis()\n sf.axis.set_view_interval(0, 10)\n fmt = sf.format_data_short\n assert fmt(data) == expected\n assert sf.axis.get_tick_space() == 9\n assert sf.axis.get_minpos() == 0\n\n def test_mathtext_ticks(self):\n mpl.rcParams.update({\n 'font.family': 'serif',\n 'font.serif': 'cmr10',\n 'axes.formatter.use_mathtext': False\n })\n\n if parse_version(pytest.__version__).major < 8:\n with pytest.warns(UserWarning, match='cmr10 font should ideally'):\n fig, ax = plt.subplots()\n ax.set_xticks([-1, 0, 1])\n fig.canvas.draw()\n else:\n with (pytest.warns(UserWarning, match="Glyph 8722"),\n pytest.warns(UserWarning, match='cmr10 font should ideally')):\n fig, ax = plt.subplots()\n ax.set_xticks([-1, 0, 1])\n fig.canvas.draw()\n\n def test_cmr10_substitutions(self, caplog):\n mpl.rcParams.update({\n 'font.family': 'cmr10',\n 'mathtext.fontset': 'cm',\n 'axes.formatter.use_mathtext': True,\n })\n\n # Test that it does not log a warning about missing glyphs.\n with caplog.at_level(logging.WARNING, logger='matplotlib.mathtext'):\n fig, ax = plt.subplots()\n ax.plot([-0.03, 0.05], [40, 0.05])\n ax.set_yscale('log')\n yticks = [0.02, 0.3, 4, 50]\n formatter = mticker.LogFormatterSciNotation()\n ax.set_yticks(yticks, map(formatter, yticks))\n fig.canvas.draw()\n assert not caplog.text\n\n def test_empty_locs(self):\n sf = mticker.ScalarFormatter()\n sf.set_locs([])\n assert sf(0.5) == ''\n\n\nclass TestLogFormatterExponent:\n param_data = [\n (True, 4, np.arange(-3, 4.0), np.arange(-3, 4.0),\n ['-3', '-2', '-1', '0', '1', '2', '3']),\n # With labelOnlyBase=False, non-integer powers should be nicely\n # formatted.\n (False, 10, np.array([0.1, 0.00001, np.pi, 0.2, -0.2, -0.00001]),\n range(6), ['0.1', '1e-05', '3.14', '0.2', '-0.2', '-1e-05']),\n (False, 50, np.array([3, 5, 12, 42], dtype=float), range(6),\n ['3', '5', '12', '42']),\n ]\n\n base_data = [2.0, 5.0, 10.0, np.pi, np.e]\n\n @pytest.mark.parametrize(\n 'labelOnlyBase, exponent, locs, positions, expected', param_data)\n @pytest.mark.parametrize('base', base_data)\n def test_basic(self, labelOnlyBase, base, exponent, locs, positions,\n expected):\n formatter = mticker.LogFormatterExponent(base=base,\n labelOnlyBase=labelOnlyBase)\n formatter.create_dummy_axis()\n formatter.axis.set_view_interval(1, base**exponent)\n vals = base**locs\n labels = [formatter(x, pos) for (x, pos) in zip(vals, positions)]\n expected = [label.replace('-', '\N{Minus Sign}') for label in expected]\n assert labels == expected\n\n def test_blank(self):\n # Should be a blank string for non-integer powers if labelOnlyBase=True\n formatter = mticker.LogFormatterExponent(base=10, labelOnlyBase=True)\n formatter.create_dummy_axis()\n formatter.axis.set_view_interval(1, 10)\n assert formatter(10**0.1) == ''\n\n\nclass TestLogFormatterMathtext:\n fmt = mticker.LogFormatterMathtext()\n test_data = [\n (0, 1, '$\\mathdefault{10^{0}}$'),\n (0, 1e-2, '$\\mathdefault{10^{-2}}$'),\n (0, 1e2, '$\\mathdefault{10^{2}}$'),\n (3, 1, '$\\mathdefault{1}$'),\n (3, 1e-2, '$\\mathdefault{0.01}$'),\n (3, 1e2, '$\\mathdefault{100}$'),\n (3, 1e-3, '$\\mathdefault{10^{-3}}$'),\n (3, 1e3, '$\\mathdefault{10^{3}}$'),\n ]\n\n @pytest.mark.parametrize('min_exponent, value, expected', test_data)\n def test_min_exponent(self, min_exponent, value, expected):\n with mpl.rc_context({'axes.formatter.min_exponent': min_exponent}):\n assert self.fmt(value) == expected\n\n\nclass TestLogFormatterSciNotation:\n test_data = [\n (2, 0.03125, '$\\mathdefault{2^{-5}}$'),\n (2, 1, '$\\mathdefault{2^{0}}$'),\n (2, 32, '$\\mathdefault{2^{5}}$'),\n (2, 0.0375, '$\\mathdefault{1.2\\times2^{-5}}$'),\n (2, 1.2, '$\\mathdefault{1.2\\times2^{0}}$'),\n (2, 38.4, '$\\mathdefault{1.2\\times2^{5}}$'),\n (10, -1, '$\\mathdefault{-10^{0}}$'),\n (10, 1e-05, '$\\mathdefault{10^{-5}}$'),\n (10, 1, '$\\mathdefault{10^{0}}$'),\n (10, 100000, '$\\mathdefault{10^{5}}$'),\n (10, 2e-05, '$\\mathdefault{2\\times10^{-5}}$'),\n (10, 2, '$\\mathdefault{2\\times10^{0}}$'),\n (10, 200000, '$\\mathdefault{2\\times10^{5}}$'),\n (10, 5e-05, '$\\mathdefault{5\\times10^{-5}}$'),\n (10, 5, '$\\mathdefault{5\\times10^{0}}$'),\n (10, 500000, '$\\mathdefault{5\\times10^{5}}$'),\n ]\n\n @mpl.style.context('default')\n @pytest.mark.parametrize('base, value, expected', test_data)\n def test_basic(self, base, value, expected):\n formatter = mticker.LogFormatterSciNotation(base=base)\n with mpl.rc_context({'text.usetex': False}):\n assert formatter(value) == expected\n\n\nclass TestLogFormatter:\n pprint_data = [\n (3.141592654e-05, 0.001, '3.142e-5'),\n (0.0003141592654, 0.001, '3.142e-4'),\n (0.003141592654, 0.001, '3.142e-3'),\n (0.03141592654, 0.001, '3.142e-2'),\n (0.3141592654, 0.001, '3.142e-1'),\n (3.141592654, 0.001, '3.142'),\n (31.41592654, 0.001, '3.142e1'),\n (314.1592654, 0.001, '3.142e2'),\n (3141.592654, 0.001, '3.142e3'),\n (31415.92654, 0.001, '3.142e4'),\n (314159.2654, 0.001, '3.142e5'),\n (1e-05, 0.001, '1e-5'),\n (0.0001, 0.001, '1e-4'),\n (0.001, 0.001, '1e-3'),\n (0.01, 0.001, '1e-2'),\n (0.1, 0.001, '1e-1'),\n (1, 0.001, '1'),\n (10, 0.001, '10'),\n (100, 0.001, '100'),\n (1000, 0.001, '1000'),\n (10000, 0.001, '1e4'),\n (100000, 0.001, '1e5'),\n (3.141592654e-05, 0.015, '0'),\n (0.0003141592654, 0.015, '0'),\n (0.003141592654, 0.015, '0.003'),\n (0.03141592654, 0.015, '0.031'),\n (0.3141592654, 0.015, '0.314'),\n (3.141592654, 0.015, '3.142'),\n (31.41592654, 0.015, '31.416'),\n (314.1592654, 0.015, '314.159'),\n (3141.592654, 0.015, '3141.593'),\n (31415.92654, 0.015, '31415.927'),\n (314159.2654, 0.015, '314159.265'),\n (1e-05, 0.015, '0'),\n (0.0001, 0.015, '0'),\n (0.001, 0.015, '0.001'),\n (0.01, 0.015, '0.01'),\n (0.1, 0.015, '0.1'),\n (1, 0.015, '1'),\n (10, 0.015, '10'),\n (100, 0.015, '100'),\n (1000, 0.015, '1000'),\n (10000, 0.015, '10000'),\n (100000, 0.015, '100000'),\n (3.141592654e-05, 0.5, '0'),\n (0.0003141592654, 0.5, '0'),\n (0.003141592654, 0.5, '0.003'),\n (0.03141592654, 0.5, '0.031'),\n (0.3141592654, 0.5, '0.314'),\n (3.141592654, 0.5, '3.142'),\n (31.41592654, 0.5, '31.416'),\n (314.1592654, 0.5, '314.159'),\n (3141.592654, 0.5, '3141.593'),\n (31415.92654, 0.5, '31415.927'),\n (314159.2654, 0.5, '314159.265'),\n (1e-05, 0.5, '0'),\n (0.0001, 0.5, '0'),\n (0.001, 0.5, '0.001'),\n (0.01, 0.5, '0.01'),\n (0.1, 0.5, '0.1'),\n (1, 0.5, '1'),\n (10, 0.5, '10'),\n (100, 0.5, '100'),\n (1000, 0.5, '1000'),\n (10000, 0.5, '10000'),\n (100000, 0.5, '100000'),\n (3.141592654e-05, 5, '0'),\n (0.0003141592654, 5, '0'),\n (0.003141592654, 5, '0'),\n (0.03141592654, 5, '0.03'),\n (0.3141592654, 5, '0.31'),\n (3.141592654, 5, '3.14'),\n (31.41592654, 5, '31.42'),\n (314.1592654, 5, '314.16'),\n (3141.592654, 5, '3141.59'),\n (31415.92654, 5, '31415.93'),\n (314159.2654, 5, '314159.27'),\n (1e-05, 5, '0'),\n (0.0001, 5, '0'),\n (0.001, 5, '0'),\n (0.01, 5, '0.01'),\n (0.1, 5, '0.1'),\n (1, 5, '1'),\n (10, 5, '10'),\n (100, 5, '100'),\n (1000, 5, '1000'),\n (10000, 5, '10000'),\n (100000, 5, '100000'),\n (3.141592654e-05, 100, '0'),\n (0.0003141592654, 100, '0'),\n (0.003141592654, 100, '0'),\n (0.03141592654, 100, '0'),\n (0.3141592654, 100, '0.3'),\n (3.141592654, 100, '3.1'),\n (31.41592654, 100, '31.4'),\n (314.1592654, 100, '314.2'),\n (3141.592654, 100, '3141.6'),\n (31415.92654, 100, '31415.9'),\n (314159.2654, 100, '314159.3'),\n (1e-05, 100, '0'),\n (0.0001, 100, '0'),\n (0.001, 100, '0'),\n (0.01, 100, '0'),\n (0.1, 100, '0.1'),\n (1, 100, '1'),\n (10, 100, '10'),\n (100, 100, '100'),\n (1000, 100, '1000'),\n (10000, 100, '10000'),\n (100000, 100, '100000'),\n (3.141592654e-05, 1000000.0, '3.1e-5'),\n (0.0003141592654, 1000000.0, '3.1e-4'),\n (0.003141592654, 1000000.0, '3.1e-3'),\n (0.03141592654, 1000000.0, '3.1e-2'),\n (0.3141592654, 1000000.0, '3.1e-1'),\n (3.141592654, 1000000.0, '3.1'),\n (31.41592654, 1000000.0, '3.1e1'),\n (314.1592654, 1000000.0, '3.1e2'),\n (3141.592654, 1000000.0, '3.1e3'),\n (31415.92654, 1000000.0, '3.1e4'),\n (314159.2654, 1000000.0, '3.1e5'),\n (1e-05, 1000000.0, '1e-5'),\n (0.0001, 1000000.0, '1e-4'),\n (0.001, 1000000.0, '1e-3'),\n (0.01, 1000000.0, '1e-2'),\n (0.1, 1000000.0, '1e-1'),\n (1, 1000000.0, '1'),\n (10, 1000000.0, '10'),\n (100, 1000000.0, '100'),\n (1000, 1000000.0, '1000'),\n (10000, 1000000.0, '1e4'),\n (100000, 1000000.0, '1e5'),\n ]\n\n @pytest.mark.parametrize('value, domain, expected', pprint_data)\n def test_pprint(self, value, domain, expected):\n fmt = mticker.LogFormatter()\n label = fmt._pprint_val(value, domain)\n assert label == expected\n\n @pytest.mark.parametrize('value, long, short', [\n (0.0, "0", "0"),\n (0, "0", "0"),\n (-1.0, "-10^0", "-1"),\n (2e-10, "2x10^-10", "2e-10"),\n (1e10, "10^10", "1e+10"),\n ])\n def test_format_data(self, value, long, short):\n fig, ax = plt.subplots()\n ax.set_xscale('log')\n fmt = ax.xaxis.get_major_formatter()\n assert fmt.format_data(value) == long\n assert fmt.format_data_short(value) == short\n\n def _sub_labels(self, axis, subs=()):\n """Test whether locator marks subs to be labeled."""\n fmt = axis.get_minor_formatter()\n minor_tlocs = axis.get_minorticklocs()\n fmt.set_locs(minor_tlocs)\n coefs = minor_tlocs / 10**(np.floor(np.log10(minor_tlocs)))\n label_expected = [round(c) in subs for c in coefs]\n label_test = [fmt(x) != '' for x in minor_tlocs]\n assert label_test == label_expected\n\n @mpl.style.context('default')\n def test_sublabel(self):\n # test label locator\n fig, ax = plt.subplots()\n ax.set_xscale('log')\n ax.xaxis.set_major_locator(mticker.LogLocator(base=10, subs=[]))\n ax.xaxis.set_minor_locator(mticker.LogLocator(base=10,\n subs=np.arange(2, 10)))\n ax.xaxis.set_major_formatter(mticker.LogFormatter(labelOnlyBase=True))\n ax.xaxis.set_minor_formatter(mticker.LogFormatter(labelOnlyBase=False))\n # axis range above 3 decades, only bases are labeled\n ax.set_xlim(1, 1e4)\n fmt = ax.xaxis.get_major_formatter()\n fmt.set_locs(ax.xaxis.get_majorticklocs())\n show_major_labels = [fmt(x) != ''\n for x in ax.xaxis.get_majorticklocs()]\n assert np.all(show_major_labels)\n self._sub_labels(ax.xaxis, subs=[])\n\n # For the next two, if the numdec threshold in LogFormatter.set_locs\n # were 3, then the label sub would be 3 for 2-3 decades and (2, 5)\n # for 1-2 decades. With a threshold of 1, subs are not labeled.\n # axis range at 2 to 3 decades\n ax.set_xlim(1, 800)\n self._sub_labels(ax.xaxis, subs=[])\n\n # axis range at 1 to 2 decades\n ax.set_xlim(1, 80)\n self._sub_labels(ax.xaxis, subs=[])\n\n # axis range at 0.4 to 1 decades, label subs 2, 3, 4, 6\n ax.set_xlim(1, 8)\n self._sub_labels(ax.xaxis, subs=[2, 3, 4, 6])\n\n # axis range at 0 to 0.4 decades, label all\n ax.set_xlim(0.5, 0.9)\n self._sub_labels(ax.xaxis, subs=np.arange(2, 10, dtype=int))\n\n @pytest.mark.parametrize('val', [1, 10, 100, 1000])\n def test_LogFormatter_call(self, val):\n # test _num_to_string method used in __call__\n temp_lf = mticker.LogFormatter()\n temp_lf.create_dummy_axis()\n temp_lf.axis.set_view_interval(1, 10)\n assert temp_lf(val) == str(val)\n\n @pytest.mark.parametrize('val', [1e-323, 2e-323, 10e-323, 11e-323])\n def test_LogFormatter_call_tiny(self, val):\n # test coeff computation in __call__\n temp_lf = mticker.LogFormatter()\n temp_lf.create_dummy_axis()\n temp_lf.axis.set_view_interval(1, 10)\n temp_lf(val)\n\n\nclass TestLogitFormatter:\n @staticmethod\n def logit_deformatter(string):\n r"""\n Parser to convert string as r'$\mathdefault{1.41\cdot10^{-4}}$' in\n float 1.41e-4, as '0.5' or as r'$\mathdefault{\frac{1}{2}}$' in float\n 0.5,\n """\n match = re.match(\n r"[^\d]*"\n r"(?P<comp>1-)?"\n r"(?P<mant>\d*\.?\d*)?"\n r"(?:\\cdot)?"\n r"(?:10\^\{(?P<expo>-?\d*)})?"\n r"[^\d]*$",\n string,\n )\n if match:\n comp = match["comp"] is not None\n mantissa = float(match["mant"]) if match["mant"] else 1\n expo = int(match["expo"]) if match["expo"] is not None else 0\n value = mantissa * 10 ** expo\n if match["mant"] or match["expo"] is not None:\n if comp:\n return 1 - value\n return value\n match = re.match(\n r"[^\d]*\\frac\{(?P<num>\d+)\}\{(?P<deno>\d+)\}[^\d]*$", string\n )\n if match:\n num, deno = float(match["num"]), float(match["deno"])\n return num / deno\n raise ValueError("Not formatted by LogitFormatter")\n\n @pytest.mark.parametrize(\n "fx, x",\n [\n (r"STUFF0.41OTHERSTUFF", 0.41),\n (r"STUFF1.41\cdot10^{-2}OTHERSTUFF", 1.41e-2),\n (r"STUFF1-0.41OTHERSTUFF", 1 - 0.41),\n (r"STUFF1-1.41\cdot10^{-2}OTHERSTUFF", 1 - 1.41e-2),\n (r"STUFF", None),\n (r"STUFF12.4e-3OTHERSTUFF", None),\n ],\n )\n def test_logit_deformater(self, fx, x):\n if x is None:\n with pytest.raises(ValueError):\n TestLogitFormatter.logit_deformatter(fx)\n else:\n y = TestLogitFormatter.logit_deformatter(fx)\n assert _LogitHelper.isclose(x, y)\n\n decade_test = sorted(\n [10 ** (-i) for i in range(1, 10)]\n + [1 - 10 ** (-i) for i in range(1, 10)]\n + [1 / 2]\n )\n\n @pytest.mark.parametrize("x", decade_test)\n def test_basic(self, x):\n """\n Test the formatted value correspond to the value for ideal ticks in\n logit space.\n """\n formatter = mticker.LogitFormatter(use_overline=False)\n formatter.set_locs(self.decade_test)\n s = formatter(x)\n x2 = TestLogitFormatter.logit_deformatter(s)\n assert _LogitHelper.isclose(x, x2)\n\n @pytest.mark.parametrize("x", (-1, -0.5, -0.1, 1.1, 1.5, 2))\n def test_invalid(self, x):\n """\n Test that invalid value are formatted with empty string without\n raising exception.\n """\n formatter = mticker.LogitFormatter(use_overline=False)\n formatter.set_locs(self.decade_test)\n s = formatter(x)\n assert s == ""\n\n @pytest.mark.parametrize("x", 1 / (1 + np.exp(-np.linspace(-7, 7, 10))))\n def test_variablelength(self, x):\n """\n The format length should change depending on the neighbor labels.\n """\n formatter = mticker.LogitFormatter(use_overline=False)\n for N in (10, 20, 50, 100, 200, 1000, 2000, 5000, 10000):\n if x + 1 / N < 1:\n formatter.set_locs([x - 1 / N, x, x + 1 / N])\n sx = formatter(x)\n sx1 = formatter(x + 1 / N)\n d = (\n TestLogitFormatter.logit_deformatter(sx1)\n - TestLogitFormatter.logit_deformatter(sx)\n )\n assert 0 < d < 2 / N\n\n lims_minor_major = [\n (True, (5e-8, 1 - 5e-8), ((25, False), (75, False))),\n (True, (5e-5, 1 - 5e-5), ((25, False), (75, True))),\n (True, (5e-2, 1 - 5e-2), ((25, True), (75, True))),\n (False, (0.75, 0.76, 0.77), ((7, True), (25, True), (75, True))),\n ]\n\n @pytest.mark.parametrize("method, lims, cases", lims_minor_major)\n def test_minor_vs_major(self, method, lims, cases):\n """\n Test minor/major displays.\n """\n\n if method:\n min_loc = mticker.LogitLocator(minor=True)\n ticks = min_loc.tick_values(*lims)\n else:\n ticks = np.array(lims)\n min_form = mticker.LogitFormatter(minor=True)\n for threshold, has_minor in cases:\n min_form.set_minor_threshold(threshold)\n formatted = min_form.format_ticks(ticks)\n labelled = [f for f in formatted if len(f) > 0]\n if has_minor:\n assert len(labelled) > 0, (threshold, has_minor)\n else:\n assert len(labelled) == 0, (threshold, has_minor)\n\n def test_minor_number(self):\n """\n Test the parameter minor_number\n """\n min_loc = mticker.LogitLocator(minor=True)\n min_form = mticker.LogitFormatter(minor=True)\n ticks = min_loc.tick_values(5e-2, 1 - 5e-2)\n for minor_number in (2, 4, 8, 16):\n min_form.set_minor_number(minor_number)\n formatted = min_form.format_ticks(ticks)\n labelled = [f for f in formatted if len(f) > 0]\n assert len(labelled) == minor_number\n\n def test_use_overline(self):\n """\n Test the parameter use_overline\n """\n x = 1 - 1e-2\n fx1 = r"$\mathdefault{1-10^{-2}}$"\n fx2 = r"$\mathdefault{\overline{10^{-2}}}$"\n form = mticker.LogitFormatter(use_overline=False)\n assert form(x) == fx1\n form.use_overline(True)\n assert form(x) == fx2\n form.use_overline(False)\n assert form(x) == fx1\n\n def test_one_half(self):\n """\n Test the parameter one_half\n """\n form = mticker.LogitFormatter()\n assert r"\frac{1}{2}" in form(1/2)\n form.set_one_half("1/2")\n assert "1/2" in form(1/2)\n form.set_one_half("one half")\n assert "one half" in form(1/2)\n\n @pytest.mark.parametrize("N", (100, 253, 754))\n def test_format_data_short(self, N):\n locs = np.linspace(0, 1, N)[1:-1]\n form = mticker.LogitFormatter()\n for x in locs:\n fx = form.format_data_short(x)\n if fx.startswith("1-"):\n x2 = 1 - float(fx[2:])\n else:\n x2 = float(fx)\n assert abs(x - x2) < 1 / N\n\n\nclass TestFormatStrFormatter:\n def test_basic(self):\n # test % style formatter\n tmp_form = mticker.FormatStrFormatter('%05d')\n assert '00002' == tmp_form(2)\n\n\nclass TestStrMethodFormatter:\n test_data = [\n ('{x:05d}', (2,), False, '00002'),\n ('{x:05d}', (2,), True, '00002'),\n ('{x:05d}', (-2,), False, '-0002'),\n ('{x:05d}', (-2,), True, '\N{MINUS SIGN}0002'),\n ('{x:03d}-{pos:02d}', (2, 1), False, '002-01'),\n ('{x:03d}-{pos:02d}', (2, 1), True, '002-01'),\n ('{x:03d}-{pos:02d}', (-2, 1), False, '-02-01'),\n ('{x:03d}-{pos:02d}', (-2, 1), True, '\N{MINUS SIGN}02-01'),\n ]\n\n @pytest.mark.parametrize('format, input, unicode_minus, expected', test_data)\n def test_basic(self, format, input, unicode_minus, expected):\n with mpl.rc_context({"axes.unicode_minus": unicode_minus}):\n fmt = mticker.StrMethodFormatter(format)\n assert fmt(*input) == expected\n\n\nclass TestEngFormatter:\n # (unicode_minus, input, expected) where ''expected'' corresponds to the\n # outputs respectively returned when (places=None, places=0, places=2)\n # unicode_minus is a boolean value for the rcParam['axes.unicode_minus']\n raw_format_data = [\n (False, -1234.56789, ('-1.23457 k', '-1 k', '-1.23 k')),\n (True, -1234.56789, ('\N{MINUS SIGN}1.23457 k', '\N{MINUS SIGN}1 k',\n '\N{MINUS SIGN}1.23 k')),\n (False, -1.23456789, ('-1.23457', '-1', '-1.23')),\n (True, -1.23456789, ('\N{MINUS SIGN}1.23457', '\N{MINUS SIGN}1',\n '\N{MINUS SIGN}1.23')),\n (False, -0.123456789, ('-123.457 m', '-123 m', '-123.46 m')),\n (True, -0.123456789, ('\N{MINUS SIGN}123.457 m', '\N{MINUS SIGN}123 m',\n '\N{MINUS SIGN}123.46 m')),\n (False, -0.00123456789, ('-1.23457 m', '-1 m', '-1.23 m')),\n (True, -0.00123456789, ('\N{MINUS SIGN}1.23457 m', '\N{MINUS SIGN}1 m',\n '\N{MINUS SIGN}1.23 m')),\n (True, -0.0, ('0', '0', '0.00')),\n (True, -0, ('0', '0', '0.00')),\n (True, 0, ('0', '0', '0.00')),\n (True, 1.23456789e-6, ('1.23457 µ', '1 µ', '1.23 µ')),\n (True, 0.123456789, ('123.457 m', '123 m', '123.46 m')),\n (True, 0.1, ('100 m', '100 m', '100.00 m')),\n (True, 1, ('1', '1', '1.00')),\n (True, 1.23456789, ('1.23457', '1', '1.23')),\n # places=0: corner-case rounding\n (True, 999.9, ('999.9', '1 k', '999.90')),\n # corner-case rounding for all\n (True, 999.9999, ('1 k', '1 k', '1.00 k')),\n # negative corner-case\n (False, -999.9999, ('-1 k', '-1 k', '-1.00 k')),\n (True, -999.9999, ('\N{MINUS SIGN}1 k', '\N{MINUS SIGN}1 k',\n '\N{MINUS SIGN}1.00 k')),\n (True, 1000, ('1 k', '1 k', '1.00 k')),\n (True, 1001, ('1.001 k', '1 k', '1.00 k')),\n (True, 100001, ('100.001 k', '100 k', '100.00 k')),\n (True, 987654.321, ('987.654 k', '988 k', '987.65 k')),\n # OoR value (> 1000 Q)\n (True, 1.23e33, ('1230 Q', '1230 Q', '1230.00 Q'))\n ]\n\n @pytest.mark.parametrize('unicode_minus, input, expected', raw_format_data)\n def test_params(self, unicode_minus, input, expected):\n """\n Test the formatting of EngFormatter for various values of the 'places'\n argument, in several cases:\n\n 0. without a unit symbol but with a (default) space separator;\n 1. with both a unit symbol and a (default) space separator;\n 2. with both a unit symbol and some non default separators;\n 3. without a unit symbol but with some non default separators.\n\n Note that cases 2. and 3. are looped over several separator strings.\n """\n\n plt.rcParams['axes.unicode_minus'] = unicode_minus\n UNIT = 's' # seconds\n DIGITS = '0123456789' # %timeit showed 10-20% faster search than set\n\n # Case 0: unit='' (default) and sep=' ' (default).\n # 'expected' already corresponds to this reference case.\n exp_outputs = expected\n formatters = (\n mticker.EngFormatter(), # places=None (default)\n mticker.EngFormatter(places=0),\n mticker.EngFormatter(places=2)\n )\n for _formatter, _exp_output in zip(formatters, exp_outputs):\n assert _formatter(input) == _exp_output\n\n # Case 1: unit=UNIT and sep=' ' (default).\n # Append a unit symbol to the reference case.\n # Beware of the values in [1, 1000), where there is no prefix!\n exp_outputs = (_s + " " + UNIT if _s[-1] in DIGITS # case w/o prefix\n else _s + UNIT for _s in expected)\n formatters = (\n mticker.EngFormatter(unit=UNIT), # places=None (default)\n mticker.EngFormatter(unit=UNIT, places=0),\n mticker.EngFormatter(unit=UNIT, places=2)\n )\n for _formatter, _exp_output in zip(formatters, exp_outputs):\n assert _formatter(input) == _exp_output\n\n # Test several non default separators: no separator, a narrow\n # no-break space (Unicode character) and an extravagant string.\n for _sep in ("", "\N{NARROW NO-BREAK SPACE}", "@_@"):\n # Case 2: unit=UNIT and sep=_sep.\n # Replace the default space separator from the reference case\n # with the tested one `_sep` and append a unit symbol to it.\n exp_outputs = (_s + _sep + UNIT if _s[-1] in DIGITS # no prefix\n else _s.replace(" ", _sep) + UNIT\n for _s in expected)\n formatters = (\n mticker.EngFormatter(unit=UNIT, sep=_sep), # places=None\n mticker.EngFormatter(unit=UNIT, places=0, sep=_sep),\n mticker.EngFormatter(unit=UNIT, places=2, sep=_sep)\n )\n for _formatter, _exp_output in zip(formatters, exp_outputs):\n assert _formatter(input) == _exp_output\n\n # Case 3: unit='' (default) and sep=_sep.\n # Replace the default space separator from the reference case\n # with the tested one `_sep`. Reference case is already unitless.\n exp_outputs = (_s.replace(" ", _sep) for _s in expected)\n formatters = (\n mticker.EngFormatter(sep=_sep), # places=None (default)\n mticker.EngFormatter(places=0, sep=_sep),\n mticker.EngFormatter(places=2, sep=_sep)\n )\n for _formatter, _exp_output in zip(formatters, exp_outputs):\n assert _formatter(input) == _exp_output\n\n\ndef test_engformatter_usetex_useMathText():\n fig, ax = plt.subplots()\n ax.plot([0, 500, 1000], [0, 500, 1000])\n ax.set_xticks([0, 500, 1000])\n for formatter in (mticker.EngFormatter(usetex=True),\n mticker.EngFormatter(useMathText=True)):\n ax.xaxis.set_major_formatter(formatter)\n fig.canvas.draw()\n x_tick_label_text = [labl.get_text() for labl in ax.get_xticklabels()]\n # Checking if the dollar `$` signs have been inserted around numbers\n # in tick labels.\n assert x_tick_label_text == ['$0$', '$500$', '$1$ k']\n\n\n@pytest.mark.parametrize(\n 'data_offset, noise, oom_center_desired, oom_noise_desired', [\n (271_490_000_000.0, 10, 9, 0),\n (27_149_000_000_000.0, 10_000_000, 12, 6),\n (27.149, 0.01, 0, -3),\n (2_714.9, 0.01, 3, -3),\n (271_490.0, 0.001, 3, -3),\n (271.49, 0.001, 0, -3),\n # The following sets of parameters demonstrates that when\n # oom(data_offset)-1 and oom(noise)-2 equal a standard 3*N oom, we get\n # that oom_noise_desired < oom(noise)\n (27_149_000_000.0, 100, 9, +3),\n (27.149, 1e-07, 0, -6),\n (271.49, 0.0001, 0, -3),\n (27.149, 0.0001, 0, -3),\n # Tests where oom(data_offset) <= oom(noise), those are probably\n # covered by the part where formatter.offset != 0\n (27_149.0, 10_000, 0, 3),\n (27.149, 10_000, 0, 3),\n (27.149, 1_000, 0, 3),\n (27.149, 100, 0, 0),\n (27.149, 10, 0, 0),\n ]\n)\ndef test_engformatter_offset_oom(\n data_offset,\n noise,\n oom_center_desired,\n oom_noise_desired\n):\n UNIT = "eV"\n fig, ax = plt.subplots()\n ydata = data_offset + np.arange(-5, 7, dtype=float)*noise\n ax.plot(ydata)\n formatter = mticker.EngFormatter(useOffset=True, unit=UNIT)\n # So that offset strings will always have the same size\n formatter.ENG_PREFIXES[0] = "_"\n ax.yaxis.set_major_formatter(formatter)\n fig.canvas.draw()\n offset_got = formatter.get_offset()\n ticks_got = [labl.get_text() for labl in ax.get_yticklabels()]\n # Predicting whether offset should be 0 or not is essentially testing\n # ScalarFormatter._compute_offset . This function is pretty complex and it\n # would be nice to test it, but this is out of scope for this test which\n # only makes sure that offset text and the ticks gets the correct unit\n # prefixes and the ticks.\n if formatter.offset:\n prefix_noise_got = offset_got[2]\n prefix_noise_desired = formatter.ENG_PREFIXES[oom_noise_desired]\n prefix_center_got = offset_got[-1-len(UNIT)]\n prefix_center_desired = formatter.ENG_PREFIXES[oom_center_desired]\n assert prefix_noise_desired == prefix_noise_got\n assert prefix_center_desired == prefix_center_got\n # Make sure the ticks didn't get the UNIT\n for tick in ticks_got:\n assert UNIT not in tick\n else:\n assert oom_center_desired == 0\n assert offset_got == ""\n # Make sure the ticks contain now the prefixes\n for tick in ticks_got:\n # 0 is zero on all orders of magnitudes, no matter what is\n # oom_noise_desired\n prefix_idx = 0 if tick[0] == "0" else oom_noise_desired\n assert tick.endswith(formatter.ENG_PREFIXES[prefix_idx] + UNIT)\n\n\nclass TestPercentFormatter:\n percent_data = [\n # Check explicitly set decimals over different intervals and values\n (100, 0, '%', 120, 100, '120%'),\n (100, 0, '%', 100, 90, '100%'),\n (100, 0, '%', 90, 50, '90%'),\n (100, 0, '%', -1.7, 40, '-2%'),\n (100, 1, '%', 90.0, 100, '90.0%'),\n (100, 1, '%', 80.1, 90, '80.1%'),\n (100, 1, '%', 70.23, 50, '70.2%'),\n # 60.554 instead of 60.55: see https://bugs.python.org/issue5118\n (100, 1, '%', -60.554, 40, '-60.6%'),\n # Check auto decimals over different intervals and values\n (100, None, '%', 95, 1, '95.00%'),\n (1.0, None, '%', 3, 6, '300%'),\n (17.0, None, '%', 1, 8.5, '6%'),\n (17.0, None, '%', 1, 8.4, '5.9%'),\n (5, None, '%', -100, 0.000001, '-2000.00000%'),\n # Check percent symbol\n (1.0, 2, None, 1.2, 100, '120.00'),\n (75, 3, '', 50, 100, '66.667'),\n (42, None, '^^Foobar$$', 21, 12, '50.0^^Foobar$$'),\n ]\n\n percent_ids = [\n # Check explicitly set decimals over different intervals and values\n 'decimals=0, x>100%',\n 'decimals=0, x=100%',\n 'decimals=0, x<100%',\n 'decimals=0, x<0%',\n 'decimals=1, x>100%',\n 'decimals=1, x=100%',\n 'decimals=1, x<100%',\n 'decimals=1, x<0%',\n # Check auto decimals over different intervals and values\n 'autodecimal, x<100%, display_range=1',\n 'autodecimal, x>100%, display_range=6 (custom xmax test)',\n 'autodecimal, x<100%, display_range=8.5 (autodecimal test 1)',\n 'autodecimal, x<100%, display_range=8.4 (autodecimal test 2)',\n 'autodecimal, x<-100%, display_range=1e-6 (tiny display range)',\n # Check percent symbol\n 'None as percent symbol',\n 'Empty percent symbol',\n 'Custom percent symbol',\n ]\n\n latex_data = [\n (False, False, r'50\{t}%'),\n (False, True, r'50\\\{t\}\%'),\n (True, False, r'50\{t}%'),\n (True, True, r'50\{t}%'),\n ]\n\n @pytest.mark.parametrize(\n 'xmax, decimals, symbol, x, display_range, expected',\n percent_data, ids=percent_ids)\n def test_basic(self, xmax, decimals, symbol,\n x, display_range, expected):\n formatter = mticker.PercentFormatter(xmax, decimals, symbol)\n with mpl.rc_context(rc={'text.usetex': False}):\n assert formatter.format_pct(x, display_range) == expected\n\n @pytest.mark.parametrize('is_latex, usetex, expected', latex_data)\n def test_latex(self, is_latex, usetex, expected):\n fmt = mticker.PercentFormatter(symbol='\\{t}%', is_latex=is_latex)\n with mpl.rc_context(rc={'text.usetex': usetex}):\n assert fmt.format_pct(50, 100) == expected\n\n\ndef _impl_locale_comma():\n try:\n locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')\n except locale.Error:\n print('SKIP: Locale de_DE.UTF-8 is not supported on this machine')\n return\n ticks = mticker.ScalarFormatter(useMathText=True, useLocale=True)\n fmt = '$\\mathdefault{%1.1f}$'\n x = ticks._format_maybe_minus_and_locale(fmt, 0.5)\n assert x == '$\\mathdefault{0{,}5}$'\n # Do not change , in the format string\n fmt = ',$\\mathdefault{,%1.1f},$'\n x = ticks._format_maybe_minus_and_locale(fmt, 0.5)\n assert x == ',$\\mathdefault{,0{,}5},$'\n # Make sure no brackets are added if not using math text\n ticks = mticker.ScalarFormatter(useMathText=False, useLocale=True)\n fmt = '%1.1f'\n x = ticks._format_maybe_minus_and_locale(fmt, 0.5)\n assert x == '0,5'\n\n\ndef test_locale_comma():\n # On some systems/pytest versions, `pytest.skip` in an exception handler\n # does not skip, but is treated as an exception, so directly running this\n # test can incorrectly fail instead of skip.\n # Instead, run this test in a subprocess, which avoids the problem, and the\n # need to fix the locale after.\n proc = mpl.testing.subprocess_run_helper(_impl_locale_comma, timeout=60,\n extra_env={'MPLBACKEND': 'Agg'})\n skip_msg = next((line[len('SKIP:'):].strip()\n for line in proc.stdout.splitlines()\n if line.startswith('SKIP:')),\n '')\n if skip_msg:\n pytest.skip(skip_msg)\n\n\ndef test_majformatter_type():\n fig, ax = plt.subplots()\n with pytest.raises(TypeError):\n ax.xaxis.set_major_formatter(mticker.LogLocator())\n\n\ndef test_minformatter_type():\n fig, ax = plt.subplots()\n with pytest.raises(TypeError):\n ax.xaxis.set_minor_formatter(mticker.LogLocator())\n\n\ndef test_majlocator_type():\n fig, ax = plt.subplots()\n with pytest.raises(TypeError):\n ax.xaxis.set_major_locator(mticker.LogFormatter())\n\n\ndef test_minlocator_type():\n fig, ax = plt.subplots()\n with pytest.raises(TypeError):\n ax.xaxis.set_minor_locator(mticker.LogFormatter())\n\n\ndef test_minorticks_rc():\n fig = plt.figure()\n\n def minorticksubplot(xminor, yminor, i):\n rc = {'xtick.minor.visible': xminor,\n 'ytick.minor.visible': yminor}\n with plt.rc_context(rc=rc):\n ax = fig.add_subplot(2, 2, i)\n\n assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor\n assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor\n\n minorticksubplot(False, False, 1)\n minorticksubplot(True, False, 2)\n minorticksubplot(False, True, 3)\n minorticksubplot(True, True, 4)\n\n\ndef test_minorticks_toggle():\n """\n Test toggling minor ticks\n\n Test `.Axis.minorticks_on()` and `.Axis.minorticks_off()`. Testing is\n limited to a subset of built-in scales - `'linear'`, `'log'`, `'asinh'`\n and `'logit'`. `symlog` scale does not seem to have a working minor\n locator and is omitted. In future, this test should cover all scales in\n `matplotlib.scale.get_scale_names()`.\n """\n fig = plt.figure()\n def minortickstoggle(xminor, yminor, scale, i):\n ax = fig.add_subplot(2, 2, i)\n ax.set_xscale(scale)\n ax.set_yscale(scale)\n if not xminor and not yminor:\n ax.minorticks_off()\n if xminor and not yminor:\n ax.xaxis.minorticks_on()\n ax.yaxis.minorticks_off()\n if not xminor and yminor:\n ax.xaxis.minorticks_off()\n ax.yaxis.minorticks_on()\n if xminor and yminor:\n ax.minorticks_on()\n\n assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor\n assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor\n\n scales = ['linear', 'log', 'asinh', 'logit']\n for scale in scales:\n minortickstoggle(False, False, scale, 1)\n minortickstoggle(True, False, scale, 2)\n minortickstoggle(False, True, scale, 3)\n minortickstoggle(True, True, scale, 4)\n fig.clear()\n\n plt.close(fig)\n\n\n@pytest.mark.parametrize('remove_overlapping_locs, expected_num',\n ((True, 6),\n (None, 6), # this tests the default\n (False, 9)))\ndef test_remove_overlap(remove_overlapping_locs, expected_num):\n t = np.arange("2018-11-03", "2018-11-06", dtype="datetime64")\n x = np.ones(len(t))\n\n fig, ax = plt.subplots()\n ax.plot(t, x)\n\n ax.xaxis.set_major_locator(mpl.dates.DayLocator())\n ax.xaxis.set_major_formatter(mpl.dates.DateFormatter('\n%a'))\n\n ax.xaxis.set_minor_locator(mpl.dates.HourLocator((0, 6, 12, 18)))\n ax.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%H:%M'))\n # force there to be extra ticks\n ax.xaxis.get_minor_ticks(15)\n if remove_overlapping_locs is not None:\n ax.xaxis.remove_overlapping_locs = remove_overlapping_locs\n\n # check that getter/setter exists\n current = ax.xaxis.remove_overlapping_locs\n assert (current == ax.xaxis.get_remove_overlapping_locs())\n plt.setp(ax.xaxis, remove_overlapping_locs=current)\n new = ax.xaxis.remove_overlapping_locs\n assert (new == ax.xaxis.remove_overlapping_locs)\n\n # check that the accessors filter correctly\n # this is the method that does the actual filtering\n assert len(ax.xaxis.get_minorticklocs()) == expected_num\n # these three are derivative\n assert len(ax.xaxis.get_minor_ticks()) == expected_num\n assert len(ax.xaxis.get_minorticklabels()) == expected_num\n assert len(ax.xaxis.get_minorticklines()) == expected_num*2\n\n\n@pytest.mark.parametrize('sub', [\n ['hi', 'aardvark'],\n np.zeros((2, 2))])\ndef test_bad_locator_subs(sub):\n ll = mticker.LogLocator()\n with pytest.raises(ValueError):\n ll.set_params(subs=sub)\n\n\n@pytest.mark.parametrize('numticks', [1, 2, 3, 9])\n@mpl.style.context('default')\ndef test_small_range_loglocator(numticks):\n ll = mticker.LogLocator()\n ll.set_params(numticks=numticks)\n for top in [5, 7, 9, 11, 15, 50, 100, 1000]:\n ticks = ll.tick_values(.5, top)\n assert (np.diff(np.log10(ll.tick_values(6, 150))) == 1).all()\n\n\ndef test_NullFormatter():\n formatter = mticker.NullFormatter()\n assert formatter(1.0) == ''\n assert formatter.format_data(1.0) == ''\n assert formatter.format_data_short(1.0) == ''\n\n\n@pytest.mark.parametrize('formatter', (\n mticker.FuncFormatter(lambda a: f'val: {a}'),\n mticker.FixedFormatter(('foo', 'bar'))))\ndef test_set_offset_string(formatter):\n assert formatter.get_offset() == ''\n formatter.set_offset_string('mpl')\n assert formatter.get_offset() == 'mpl'\n\n\ndef test_minorticks_on_multi_fig():\n """\n Turning on minor gridlines in a multi-Axes Figure\n that contains more than one boxplot and shares the x-axis\n should not raise an exception.\n """\n fig, ax = plt.subplots()\n\n ax.boxplot(np.arange(10), positions=[0])\n ax.boxplot(np.arange(10), positions=[0])\n ax.boxplot(np.arange(10), positions=[1])\n\n ax.grid(which="major")\n ax.grid(which="minor")\n ax.minorticks_on()\n fig.draw_without_rendering()\n\n assert ax.get_xgridlines()\n assert isinstance(ax.xaxis.get_minor_locator(), mpl.ticker.AutoMinorLocator)\n | .venv\Lib\site-packages\matplotlib\tests\test_ticker.py | test_ticker.py | Python | 74,759 | 0.75 | 0.117586 | 0.050469 | node-utils | 76 | 2024-11-12T08:02:39.673543 | Apache-2.0 | true | dcef099cab963044b9f0045c5969fcec |
import warnings\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib.testing.decorators import image_comparison\nimport matplotlib.pyplot as plt\nfrom matplotlib.offsetbox import AnchoredOffsetbox, DrawingArea\nfrom matplotlib.patches import Rectangle\n\n\npytestmark = [\n pytest.mark.usefixtures('text_placeholders')\n]\n\n\ndef example_plot(ax, fontsize=12):\n ax.plot([1, 2])\n ax.locator_params(nbins=3)\n ax.set_xlabel('x-label', fontsize=fontsize)\n ax.set_ylabel('y-label', fontsize=fontsize)\n ax.set_title('Title', fontsize=fontsize)\n\n\n@image_comparison(['tight_layout1'], style='mpl20')\ndef test_tight_layout1():\n """Test tight_layout for a single subplot."""\n fig, ax = plt.subplots()\n example_plot(ax, fontsize=24)\n plt.tight_layout()\n\n\n@image_comparison(['tight_layout2'], style='mpl20')\ndef test_tight_layout2():\n """Test tight_layout for multiple subplots."""\n fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)\n example_plot(ax1)\n example_plot(ax2)\n example_plot(ax3)\n example_plot(ax4)\n plt.tight_layout()\n\n\n@image_comparison(['tight_layout3'], style='mpl20')\ndef test_tight_layout3():\n """Test tight_layout for multiple subplots."""\n ax1 = plt.subplot(221)\n ax2 = plt.subplot(223)\n ax3 = plt.subplot(122)\n example_plot(ax1)\n example_plot(ax2)\n example_plot(ax3)\n plt.tight_layout()\n\n\n@image_comparison(['tight_layout4'], style='mpl20')\ndef test_tight_layout4():\n """Test tight_layout for subplot2grid."""\n ax1 = plt.subplot2grid((3, 3), (0, 0))\n ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)\n ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)\n ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)\n example_plot(ax1)\n example_plot(ax2)\n example_plot(ax3)\n example_plot(ax4)\n plt.tight_layout()\n\n\n@image_comparison(['tight_layout5'], style='mpl20')\ndef test_tight_layout5():\n """Test tight_layout for image."""\n ax = plt.subplot()\n arr = np.arange(100).reshape((10, 10))\n ax.imshow(arr, interpolation="none")\n plt.tight_layout()\n\n\n@image_comparison(['tight_layout6'], style='mpl20')\ndef test_tight_layout6():\n """Test tight_layout for gridspec."""\n\n # This raises warnings since tight layout cannot\n # do this fully automatically. But the test is\n # correct since the layout is manually edited\n with warnings.catch_warnings():\n warnings.simplefilter("ignore", UserWarning)\n fig = plt.figure()\n\n gs1 = mpl.gridspec.GridSpec(2, 1)\n ax1 = fig.add_subplot(gs1[0])\n ax2 = fig.add_subplot(gs1[1])\n\n example_plot(ax1)\n example_plot(ax2)\n\n gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])\n\n gs2 = mpl.gridspec.GridSpec(3, 1)\n\n for ss in gs2:\n ax = fig.add_subplot(ss)\n example_plot(ax)\n ax.set_title("")\n ax.set_xlabel("")\n\n ax.set_xlabel("x-label", fontsize=12)\n\n gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.45)\n\n top = min(gs1.top, gs2.top)\n bottom = max(gs1.bottom, gs2.bottom)\n\n gs1.tight_layout(fig, rect=[None, 0 + (bottom-gs1.bottom),\n 0.5, 1 - (gs1.top-top)])\n gs2.tight_layout(fig, rect=[0.5, 0 + (bottom-gs2.bottom),\n None, 1 - (gs2.top-top)],\n h_pad=0.45)\n\n\n@image_comparison(['tight_layout7'], style='mpl20')\ndef test_tight_layout7():\n # tight layout with left and right titles\n fontsize = 24\n fig, ax = plt.subplots()\n ax.plot([1, 2])\n ax.locator_params(nbins=3)\n ax.set_xlabel('x-label', fontsize=fontsize)\n ax.set_ylabel('y-label', fontsize=fontsize)\n ax.set_title('Left Title', loc='left', fontsize=fontsize)\n ax.set_title('Right Title', loc='right', fontsize=fontsize)\n plt.tight_layout()\n\n\n@image_comparison(['tight_layout8'], style='mpl20', tol=0.005)\ndef test_tight_layout8():\n """Test automatic use of tight_layout."""\n fig = plt.figure()\n fig.set_layout_engine(layout='tight', pad=0.1)\n ax = fig.add_subplot()\n example_plot(ax, fontsize=24)\n fig.draw_without_rendering()\n\n\n@image_comparison(['tight_layout9'], style='mpl20')\ndef test_tight_layout9():\n # Test tight_layout for non-visible subplots\n # GH 8244\n f, axarr = plt.subplots(2, 2)\n axarr[1][1].set_visible(False)\n plt.tight_layout()\n\n\ndef test_outward_ticks():\n """Test automatic use of tight_layout."""\n fig = plt.figure()\n ax = fig.add_subplot(221)\n ax.xaxis.set_tick_params(tickdir='out', length=16, width=3)\n ax.yaxis.set_tick_params(tickdir='out', length=16, width=3)\n ax.xaxis.set_tick_params(\n tickdir='out', length=32, width=3, tick1On=True, which='minor')\n ax.yaxis.set_tick_params(\n tickdir='out', length=32, width=3, tick1On=True, which='minor')\n ax.xaxis.set_ticks([0], minor=True)\n ax.yaxis.set_ticks([0], minor=True)\n ax = fig.add_subplot(222)\n ax.xaxis.set_tick_params(tickdir='in', length=32, width=3)\n ax.yaxis.set_tick_params(tickdir='in', length=32, width=3)\n ax = fig.add_subplot(223)\n ax.xaxis.set_tick_params(tickdir='inout', length=32, width=3)\n ax.yaxis.set_tick_params(tickdir='inout', length=32, width=3)\n ax = fig.add_subplot(224)\n ax.xaxis.set_tick_params(tickdir='out', length=32, width=3)\n ax.yaxis.set_tick_params(tickdir='out', length=32, width=3)\n plt.tight_layout()\n # These values were obtained after visual checking that they correspond\n # to a tight layouting that did take the ticks into account.\n expected = [\n [[0.092, 0.605], [0.433, 0.933]],\n [[0.581, 0.605], [0.922, 0.933]],\n [[0.092, 0.138], [0.433, 0.466]],\n [[0.581, 0.138], [0.922, 0.466]],\n ]\n for nn, ax in enumerate(fig.axes):\n assert_array_equal(np.round(ax.get_position().get_points(), 3),\n expected[nn])\n\n\ndef add_offsetboxes(ax, size=10, margin=.1, color='black'):\n """\n Surround ax with OffsetBoxes\n """\n m, mp = margin, 1+margin\n anchor_points = [(-m, -m), (-m, .5), (-m, mp),\n (.5, mp), (mp, mp), (mp, .5),\n (mp, -m), (.5, -m)]\n for point in anchor_points:\n da = DrawingArea(size, size)\n background = Rectangle((0, 0), width=size,\n height=size,\n facecolor=color,\n edgecolor='None',\n linewidth=0,\n antialiased=False)\n da.add_artist(background)\n\n anchored_box = AnchoredOffsetbox(\n loc='center',\n child=da,\n pad=0.,\n frameon=False,\n bbox_to_anchor=point,\n bbox_transform=ax.transAxes,\n borderpad=0.)\n ax.add_artist(anchored_box)\n\n\ndef test_tight_layout_offsetboxes():\n # 0.\n # - Create 4 subplots\n # - Plot a diagonal line on them\n # - Use tight_layout\n #\n # 1.\n # - Same 4 subplots\n # - Surround each plot with 7 boxes\n # - Use tight_layout\n # - See that the squares are included in the tight_layout and that the squares do\n # not overlap\n #\n # 2.\n # - Make the squares around the Axes invisible\n # - See that the invisible squares do not affect the tight_layout\n rows = cols = 2\n colors = ['red', 'blue', 'green', 'yellow']\n x = y = [0, 1]\n\n def _subplots(with_boxes):\n fig, axs = plt.subplots(rows, cols)\n for ax, color in zip(axs.flat, colors):\n ax.plot(x, y, color=color)\n if with_boxes:\n add_offsetboxes(ax, 20, color=color)\n return fig, axs\n\n # 0.\n fig0, axs0 = _subplots(False)\n fig0.tight_layout()\n\n # 1.\n fig1, axs1 = _subplots(True)\n fig1.tight_layout()\n\n # The AnchoredOffsetbox should be added to the bounding of the Axes, causing them to\n # be smaller than the plain figure.\n for ax0, ax1 in zip(axs0.flat, axs1.flat):\n bbox0 = ax0.get_position()\n bbox1 = ax1.get_position()\n assert bbox1.x0 > bbox0.x0\n assert bbox1.x1 < bbox0.x1\n assert bbox1.y0 > bbox0.y0\n assert bbox1.y1 < bbox0.y1\n\n # No AnchoredOffsetbox should overlap with another.\n bboxes = []\n for ax1 in axs1.flat:\n for child in ax1.get_children():\n if not isinstance(child, AnchoredOffsetbox):\n continue\n bbox = child.get_window_extent()\n for other_bbox in bboxes:\n assert not bbox.overlaps(other_bbox)\n bboxes.append(bbox)\n\n # 2.\n fig2, axs2 = _subplots(True)\n for ax in axs2.flat:\n for child in ax.get_children():\n if isinstance(child, AnchoredOffsetbox):\n child.set_visible(False)\n fig2.tight_layout()\n # The invisible AnchoredOffsetbox should not count for tight layout, so it should\n # look the same as when they were never added.\n for ax0, ax2 in zip(axs0.flat, axs2.flat):\n bbox0 = ax0.get_position()\n bbox2 = ax2.get_position()\n assert_array_equal(bbox2.get_points(), bbox0.get_points())\n\n\ndef test_empty_layout():\n """Test that tight layout doesn't cause an error when there are no Axes."""\n fig = plt.gcf()\n fig.tight_layout()\n\n\n@pytest.mark.parametrize("label", ["xlabel", "ylabel"])\ndef test_verybig_decorators(label):\n """Test that no warning emitted when xlabel/ylabel too big."""\n fig, ax = plt.subplots(figsize=(3, 2))\n ax.set(**{label: 'a' * 100})\n\n\ndef test_big_decorators_horizontal():\n """Test that doesn't warn when xlabel too big."""\n fig, axs = plt.subplots(1, 2, figsize=(3, 2))\n axs[0].set_xlabel('a' * 30)\n axs[1].set_xlabel('b' * 30)\n\n\ndef test_big_decorators_vertical():\n """Test that doesn't warn when ylabel too big."""\n fig, axs = plt.subplots(2, 1, figsize=(3, 2))\n axs[0].set_ylabel('a' * 20)\n axs[1].set_ylabel('b' * 20)\n\n\ndef test_badsubplotgrid():\n # test that we get warning for mismatched subplot grids, not than an error\n plt.subplot2grid((4, 5), (0, 0))\n # this is the bad entry:\n plt.subplot2grid((5, 5), (0, 3), colspan=3, rowspan=5)\n with pytest.warns(UserWarning):\n plt.tight_layout()\n\n\ndef test_collapsed():\n # test that if the amount of space required to make all the axes\n # decorations fit would mean that the actual Axes would end up with size\n # zero (i.e. margins add up to more than the available width) that a call\n # to tight_layout will not get applied:\n fig, ax = plt.subplots(tight_layout=True)\n ax.set_xlim([0, 1])\n ax.set_ylim([0, 1])\n\n ax.annotate('BIG LONG STRING', xy=(1.25, 2), xytext=(10.5, 1.75),\n annotation_clip=False)\n p1 = ax.get_position()\n with pytest.warns(UserWarning):\n plt.tight_layout()\n p2 = ax.get_position()\n assert p1.width == p2.width\n # test that passing a rect doesn't crash...\n with pytest.warns(UserWarning):\n plt.tight_layout(rect=[0, 0, 0.8, 0.8])\n\n\ndef test_suptitle():\n fig, ax = plt.subplots(tight_layout=True)\n st = fig.suptitle("foo")\n t = ax.set_title("bar")\n fig.canvas.draw()\n assert st.get_window_extent().y0 > t.get_window_extent().y1\n\n\n@pytest.mark.backend("pdf")\ndef test_non_agg_renderer(monkeypatch, recwarn):\n unpatched_init = mpl.backend_bases.RendererBase.__init__\n\n def __init__(self, *args, **kwargs):\n # Check that we don't instantiate any other renderer than a pdf\n # renderer to perform pdf tight layout.\n assert isinstance(self, mpl.backends.backend_pdf.RendererPdf)\n unpatched_init(self, *args, **kwargs)\n\n monkeypatch.setattr(mpl.backend_bases.RendererBase, "__init__", __init__)\n fig, ax = plt.subplots()\n fig.tight_layout()\n\n\ndef test_manual_colorbar():\n # This should warn, but not raise\n fig, axes = plt.subplots(1, 2)\n pts = axes[1].scatter([0, 1], [0, 1], c=[1, 5])\n ax_rect = axes[1].get_position()\n cax = fig.add_axes(\n [ax_rect.x1 + 0.005, ax_rect.y0, 0.015, ax_rect.height]\n )\n fig.colorbar(pts, cax=cax)\n with pytest.warns(UserWarning, match="This figure includes Axes"):\n fig.tight_layout()\n\n\ndef test_clipped_to_axes():\n # Ensure that _fully_clipped_to_axes() returns True under default\n # conditions for all projection types. Axes.get_tightbbox()\n # uses this to skip artists in layout calculations.\n arr = np.arange(100).reshape((10, 10))\n fig = plt.figure(figsize=(6, 2))\n ax1 = fig.add_subplot(131, projection='rectilinear')\n ax2 = fig.add_subplot(132, projection='mollweide')\n ax3 = fig.add_subplot(133, projection='polar')\n for ax in (ax1, ax2, ax3):\n # Default conditions (clipped by ax.bbox or ax.patch)\n ax.grid(False)\n h, = ax.plot(arr[:, 0])\n m = ax.pcolor(arr)\n assert h._fully_clipped_to_axes()\n assert m._fully_clipped_to_axes()\n # Non-default conditions (not clipped by ax.patch)\n rect = Rectangle((0, 0), 0.5, 0.5, transform=ax.transAxes)\n h.set_clip_path(rect)\n m.set_clip_path(rect.get_path(), rect.get_transform())\n assert not h._fully_clipped_to_axes()\n assert not m._fully_clipped_to_axes()\n\n\ndef test_tight_pads():\n fig, ax = plt.subplots()\n with pytest.warns(PendingDeprecationWarning,\n match='will be deprecated'):\n fig.set_tight_layout({'pad': 0.15})\n fig.draw_without_rendering()\n\n\ndef test_tight_kwargs():\n fig, ax = plt.subplots(tight_layout={'pad': 0.15})\n fig.draw_without_rendering()\n\n\ndef test_tight_toggle():\n fig, ax = plt.subplots()\n with pytest.warns(PendingDeprecationWarning):\n fig.set_tight_layout(True)\n assert fig.get_tight_layout()\n fig.set_tight_layout(False)\n assert not fig.get_tight_layout()\n fig.set_tight_layout(True)\n assert fig.get_tight_layout()\n | .venv\Lib\site-packages\matplotlib\tests\test_tightlayout.py | test_tightlayout.py | Python | 13,978 | 0.95 | 0.125581 | 0.129944 | react-lib | 145 | 2024-06-02T22:45:38.073091 | Apache-2.0 | true | 2de2f30e54408c029bd5f7fb847365c3 |
import copy\n\nimport numpy as np\nfrom numpy.testing import (assert_allclose, assert_almost_equal,\n assert_array_equal, assert_array_almost_equal)\nimport pytest\n\nfrom matplotlib import scale\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport matplotlib.transforms as mtransforms\nfrom matplotlib.transforms import Affine2D, Bbox, TransformedBbox, _ScaledRotation\nfrom matplotlib.path import Path\nfrom matplotlib.testing.decorators import image_comparison, check_figures_equal\nfrom unittest.mock import MagicMock\n\n\nclass TestAffine2D:\n single_point = [1.0, 1.0]\n multiple_points = [[0.0, 2.0], [3.0, 3.0], [4.0, 0.0]]\n pivot = single_point\n\n def test_init(self):\n Affine2D([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n Affine2D(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], int))\n Affine2D(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], float))\n\n def test_values(self):\n np.random.seed(19680801)\n values = np.random.random(6)\n assert_array_equal(Affine2D.from_values(*values).to_values(), values)\n\n def test_modify_inplace(self):\n # Some polar transforms require modifying the matrix in place.\n trans = Affine2D()\n mtx = trans.get_matrix()\n mtx[0, 0] = 42\n assert_array_equal(trans.get_matrix(), [[42, 0, 0], [0, 1, 0], [0, 0, 1]])\n\n def test_clear(self):\n a = Affine2D(np.random.rand(3, 3) + 5) # Anything non-identity.\n a.clear()\n assert_array_equal(a.get_matrix(), [[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n\n def test_rotate(self):\n r_pi_2 = Affine2D().rotate(np.pi / 2)\n r90 = Affine2D().rotate_deg(90)\n assert_array_equal(r_pi_2.get_matrix(), r90.get_matrix())\n assert_array_almost_equal(r90.transform(self.single_point), [-1, 1])\n assert_array_almost_equal(r90.transform(self.multiple_points),\n [[-2, 0], [-3, 3], [0, 4]])\n\n r_pi = Affine2D().rotate(np.pi)\n r180 = Affine2D().rotate_deg(180)\n assert_array_equal(r_pi.get_matrix(), r180.get_matrix())\n assert_array_almost_equal(r180.transform(self.single_point), [-1, -1])\n assert_array_almost_equal(r180.transform(self.multiple_points),\n [[0, -2], [-3, -3], [-4, 0]])\n\n r_pi_3_2 = Affine2D().rotate(3 * np.pi / 2)\n r270 = Affine2D().rotate_deg(270)\n assert_array_equal(r_pi_3_2.get_matrix(), r270.get_matrix())\n assert_array_almost_equal(r270.transform(self.single_point), [1, -1])\n assert_array_almost_equal(r270.transform(self.multiple_points),\n [[2, 0], [3, -3], [0, -4]])\n\n assert_array_equal((r90 + r90).get_matrix(), r180.get_matrix())\n assert_array_equal((r90 + r180).get_matrix(), r270.get_matrix())\n\n def test_rotate_around(self):\n r_pi_2 = Affine2D().rotate_around(*self.pivot, np.pi / 2)\n r90 = Affine2D().rotate_deg_around(*self.pivot, 90)\n assert_array_equal(r_pi_2.get_matrix(), r90.get_matrix())\n assert_array_almost_equal(r90.transform(self.single_point), [1, 1])\n assert_array_almost_equal(r90.transform(self.multiple_points),\n [[0, 0], [-1, 3], [2, 4]])\n\n r_pi = Affine2D().rotate_around(*self.pivot, np.pi)\n r180 = Affine2D().rotate_deg_around(*self.pivot, 180)\n assert_array_equal(r_pi.get_matrix(), r180.get_matrix())\n assert_array_almost_equal(r180.transform(self.single_point), [1, 1])\n assert_array_almost_equal(r180.transform(self.multiple_points),\n [[2, 0], [-1, -1], [-2, 2]])\n\n r_pi_3_2 = Affine2D().rotate_around(*self.pivot, 3 * np.pi / 2)\n r270 = Affine2D().rotate_deg_around(*self.pivot, 270)\n assert_array_equal(r_pi_3_2.get_matrix(), r270.get_matrix())\n assert_array_almost_equal(r270.transform(self.single_point), [1, 1])\n assert_array_almost_equal(r270.transform(self.multiple_points),\n [[2, 2], [3, -1], [0, -2]])\n\n assert_array_almost_equal((r90 + r90).get_matrix(), r180.get_matrix())\n assert_array_almost_equal((r90 + r180).get_matrix(), r270.get_matrix())\n\n def test_scale(self):\n sx = Affine2D().scale(3, 1)\n sy = Affine2D().scale(1, -2)\n trans = Affine2D().scale(3, -2)\n assert_array_equal((sx + sy).get_matrix(), trans.get_matrix())\n assert_array_equal(trans.transform(self.single_point), [3, -2])\n assert_array_equal(trans.transform(self.multiple_points),\n [[0, -4], [9, -6], [12, 0]])\n\n def test_skew(self):\n trans_rad = Affine2D().skew(np.pi / 8, np.pi / 12)\n trans_deg = Affine2D().skew_deg(22.5, 15)\n assert_array_equal(trans_rad.get_matrix(), trans_deg.get_matrix())\n # Using ~atan(0.5), ~atan(0.25) produces roundish numbers on output.\n trans = Affine2D().skew_deg(26.5650512, 14.0362435)\n assert_array_almost_equal(trans.transform(self.single_point), [1.5, 1.25])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[1, 2], [4.5, 3.75], [4, 1]])\n\n def test_translate(self):\n tx = Affine2D().translate(23, 0)\n ty = Affine2D().translate(0, 42)\n trans = Affine2D().translate(23, 42)\n assert_array_equal((tx + ty).get_matrix(), trans.get_matrix())\n assert_array_equal(trans.transform(self.single_point), [24, 43])\n assert_array_equal(trans.transform(self.multiple_points),\n [[23, 44], [26, 45], [27, 42]])\n\n def test_rotate_plus_other(self):\n trans = Affine2D().rotate_deg(90).rotate_deg_around(*self.pivot, 180)\n trans_added = (Affine2D().rotate_deg(90) +\n Affine2D().rotate_deg_around(*self.pivot, 180))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [3, 1])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[4, 2], [5, -1], [2, -2]])\n\n trans = Affine2D().rotate_deg(90).scale(3, -2)\n trans_added = Affine2D().rotate_deg(90) + Affine2D().scale(3, -2)\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [-3, -2])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[-6, -0], [-9, -6], [0, -8]])\n\n trans = (Affine2D().rotate_deg(90)\n .skew_deg(26.5650512, 14.0362435)) # ~atan(0.5), ~atan(0.25)\n trans_added = (Affine2D().rotate_deg(90) +\n Affine2D().skew_deg(26.5650512, 14.0362435))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [-0.5, 0.75])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[-2, -0.5], [-1.5, 2.25], [2, 4]])\n\n trans = Affine2D().rotate_deg(90).translate(23, 42)\n trans_added = Affine2D().rotate_deg(90) + Affine2D().translate(23, 42)\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [22, 43])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[21, 42], [20, 45], [23, 46]])\n\n def test_rotate_around_plus_other(self):\n trans = Affine2D().rotate_deg_around(*self.pivot, 90).rotate_deg(180)\n trans_added = (Affine2D().rotate_deg_around(*self.pivot, 90) +\n Affine2D().rotate_deg(180))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [-1, -1])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[0, 0], [1, -3], [-2, -4]])\n\n trans = Affine2D().rotate_deg_around(*self.pivot, 90).scale(3, -2)\n trans_added = (Affine2D().rotate_deg_around(*self.pivot, 90) +\n Affine2D().scale(3, -2))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [3, -2])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[0, 0], [-3, -6], [6, -8]])\n\n trans = (Affine2D().rotate_deg_around(*self.pivot, 90)\n .skew_deg(26.5650512, 14.0362435)) # ~atan(0.5), ~atan(0.25)\n trans_added = (Affine2D().rotate_deg_around(*self.pivot, 90) +\n Affine2D().skew_deg(26.5650512, 14.0362435))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [1.5, 1.25])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[0, 0], [0.5, 2.75], [4, 4.5]])\n\n trans = Affine2D().rotate_deg_around(*self.pivot, 90).translate(23, 42)\n trans_added = (Affine2D().rotate_deg_around(*self.pivot, 90) +\n Affine2D().translate(23, 42))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [24, 43])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[23, 42], [22, 45], [25, 46]])\n\n def test_scale_plus_other(self):\n trans = Affine2D().scale(3, -2).rotate_deg(90)\n trans_added = Affine2D().scale(3, -2) + Affine2D().rotate_deg(90)\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_equal(trans.transform(self.single_point), [2, 3])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[4, 0], [6, 9], [0, 12]])\n\n trans = Affine2D().scale(3, -2).rotate_deg_around(*self.pivot, 90)\n trans_added = (Affine2D().scale(3, -2) +\n Affine2D().rotate_deg_around(*self.pivot, 90))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_equal(trans.transform(self.single_point), [4, 3])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[6, 0], [8, 9], [2, 12]])\n\n trans = (Affine2D().scale(3, -2)\n .skew_deg(26.5650512, 14.0362435)) # ~atan(0.5), ~atan(0.25)\n trans_added = (Affine2D().scale(3, -2) +\n Affine2D().skew_deg(26.5650512, 14.0362435))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [2, -1.25])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[-2, -4], [6, -3.75], [12, 3]])\n\n trans = Affine2D().scale(3, -2).translate(23, 42)\n trans_added = Affine2D().scale(3, -2) + Affine2D().translate(23, 42)\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_equal(trans.transform(self.single_point), [26, 40])\n assert_array_equal(trans.transform(self.multiple_points),\n [[23, 38], [32, 36], [35, 42]])\n\n def test_skew_plus_other(self):\n # Using ~atan(0.5), ~atan(0.25) produces roundish numbers on output.\n trans = Affine2D().skew_deg(26.5650512, 14.0362435).rotate_deg(90)\n trans_added = (Affine2D().skew_deg(26.5650512, 14.0362435) +\n Affine2D().rotate_deg(90))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [-1.25, 1.5])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[-2, 1], [-3.75, 4.5], [-1, 4]])\n\n trans = (Affine2D().skew_deg(26.5650512, 14.0362435)\n .rotate_deg_around(*self.pivot, 90))\n trans_added = (Affine2D().skew_deg(26.5650512, 14.0362435) +\n Affine2D().rotate_deg_around(*self.pivot, 90))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [0.75, 1.5])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[0, 1], [-1.75, 4.5], [1, 4]])\n\n trans = Affine2D().skew_deg(26.5650512, 14.0362435).scale(3, -2)\n trans_added = (Affine2D().skew_deg(26.5650512, 14.0362435) +\n Affine2D().scale(3, -2))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [4.5, -2.5])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[3, -4], [13.5, -7.5], [12, -2]])\n\n trans = Affine2D().skew_deg(26.5650512, 14.0362435).translate(23, 42)\n trans_added = (Affine2D().skew_deg(26.5650512, 14.0362435) +\n Affine2D().translate(23, 42))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [24.5, 43.25])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[24, 44], [27.5, 45.75], [27, 43]])\n\n def test_translate_plus_other(self):\n trans = Affine2D().translate(23, 42).rotate_deg(90)\n trans_added = Affine2D().translate(23, 42) + Affine2D().rotate_deg(90)\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [-43, 24])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[-44, 23], [-45, 26], [-42, 27]])\n\n trans = Affine2D().translate(23, 42).rotate_deg_around(*self.pivot, 90)\n trans_added = (Affine2D().translate(23, 42) +\n Affine2D().rotate_deg_around(*self.pivot, 90))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [-41, 24])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[-42, 23], [-43, 26], [-40, 27]])\n\n trans = Affine2D().translate(23, 42).scale(3, -2)\n trans_added = Affine2D().translate(23, 42) + Affine2D().scale(3, -2)\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [72, -86])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[69, -88], [78, -90], [81, -84]])\n\n trans = (Affine2D().translate(23, 42)\n .skew_deg(26.5650512, 14.0362435)) # ~atan(0.5), ~atan(0.25)\n trans_added = (Affine2D().translate(23, 42) +\n Affine2D().skew_deg(26.5650512, 14.0362435))\n assert_array_equal(trans.get_matrix(), trans_added.get_matrix())\n assert_array_almost_equal(trans.transform(self.single_point), [45.5, 49])\n assert_array_almost_equal(trans.transform(self.multiple_points),\n [[45, 49.75], [48.5, 51.5], [48, 48.75]])\n\n def test_invalid_transform(self):\n t = mtransforms.Affine2D()\n # There are two different exceptions, since the wrong number of\n # dimensions is caught when constructing an array_view, and that\n # raises a ValueError, and a wrong shape with a possible number\n # of dimensions is caught by our CALL_CPP macro, which always\n # raises the less precise RuntimeError.\n with pytest.raises(ValueError):\n t.transform(1)\n with pytest.raises(ValueError):\n t.transform([[[1]]])\n with pytest.raises(RuntimeError):\n t.transform([])\n with pytest.raises(RuntimeError):\n t.transform([1])\n with pytest.raises(ValueError):\n t.transform([[1]])\n with pytest.raises(ValueError):\n t.transform([[1, 2, 3]])\n\n def test_copy(self):\n a = mtransforms.Affine2D()\n b = mtransforms.Affine2D()\n s = a + b\n # Updating a dependee should invalidate a copy of the dependent.\n s.get_matrix() # resolve it.\n s1 = copy.copy(s)\n assert not s._invalid and not s1._invalid\n a.translate(1, 2)\n assert s._invalid and s1._invalid\n assert (s1.get_matrix() == a.get_matrix()).all()\n # Updating a copy of a dependee shouldn't invalidate a dependent.\n s.get_matrix() # resolve it.\n b1 = copy.copy(b)\n b1.translate(3, 4)\n assert not s._invalid\n assert_array_equal(s.get_matrix(), a.get_matrix())\n\n def test_deepcopy(self):\n a = mtransforms.Affine2D()\n b = mtransforms.Affine2D()\n s = a + b\n # Updating a dependee shouldn't invalidate a deepcopy of the dependent.\n s.get_matrix() # resolve it.\n s1 = copy.deepcopy(s)\n assert not s._invalid and not s1._invalid\n a.translate(1, 2)\n assert s._invalid and not s1._invalid\n assert_array_equal(s1.get_matrix(), mtransforms.Affine2D().get_matrix())\n # Updating a deepcopy of a dependee shouldn't invalidate a dependent.\n s.get_matrix() # resolve it.\n b1 = copy.deepcopy(b)\n b1.translate(3, 4)\n assert not s._invalid\n assert_array_equal(s.get_matrix(), a.get_matrix())\n\n\nclass TestAffineDeltaTransform:\n def test_invalidate(self):\n before = np.array([[1.0, 4.0, 0.0],\n [5.0, 1.0, 0.0],\n [0.0, 0.0, 1.0]])\n after = np.array([[1.0, 3.0, 0.0],\n [5.0, 1.0, 0.0],\n [0.0, 0.0, 1.0]])\n\n # Translation and skew present\n base = mtransforms.Affine2D.from_values(1, 5, 4, 1, 2, 3)\n t = mtransforms.AffineDeltaTransform(base)\n assert_array_equal(t.get_matrix(), before)\n\n # Mess with the internal structure of `base` without invalidating\n # This should not affect this transform because it's a passthrough:\n # it's always invalid\n base.get_matrix()[0, 1:] = 3\n assert_array_equal(t.get_matrix(), after)\n\n # Invalidate the base\n base.invalidate()\n assert_array_equal(t.get_matrix(), after)\n\n\ndef test_non_affine_caching():\n class AssertingNonAffineTransform(mtransforms.Transform):\n """\n This transform raises an assertion error when called when it\n shouldn't be and ``self.raise_on_transform`` is True.\n\n """\n input_dims = output_dims = 2\n is_affine = False\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.raise_on_transform = False\n self.underlying_transform = mtransforms.Affine2D().scale(10, 10)\n\n def transform_path_non_affine(self, path):\n assert not self.raise_on_transform, \\n 'Invalidated affine part of transform unnecessarily.'\n return self.underlying_transform.transform_path(path)\n transform_path = transform_path_non_affine\n\n def transform_non_affine(self, path):\n assert not self.raise_on_transform, \\n 'Invalidated affine part of transform unnecessarily.'\n return self.underlying_transform.transform(path)\n transform = transform_non_affine\n\n my_trans = AssertingNonAffineTransform()\n ax = plt.axes()\n plt.plot(np.arange(10), transform=my_trans + ax.transData)\n plt.draw()\n # enable the transform to raise an exception if it's non-affine transform\n # method is triggered again.\n my_trans.raise_on_transform = True\n ax.transAxes.invalidate()\n plt.draw()\n\n\ndef test_external_transform_api():\n class ScaledBy:\n def __init__(self, scale_factor):\n self._scale_factor = scale_factor\n\n def _as_mpl_transform(self, axes):\n return (mtransforms.Affine2D().scale(self._scale_factor)\n + axes.transData)\n\n ax = plt.axes()\n line, = plt.plot(np.arange(10), transform=ScaledBy(10))\n ax.set_xlim(0, 100)\n ax.set_ylim(0, 100)\n # assert that the top transform of the line is the scale transform.\n assert_allclose(line.get_transform()._a.get_matrix(),\n mtransforms.Affine2D().scale(10).get_matrix())\n\n\n@image_comparison(['pre_transform_data'], remove_text=True, style='mpl20',\n tol=0.05)\ndef test_pre_transform_plotting():\n # a catch-all for as many as possible plot layouts which handle\n # pre-transforming the data NOTE: The axis range is important in this\n # plot. It should be x10 what the data suggests it should be\n\n ax = plt.axes()\n times10 = mtransforms.Affine2D().scale(10)\n\n ax.contourf(np.arange(48).reshape(6, 8), transform=times10 + ax.transData)\n\n ax.pcolormesh(np.linspace(0, 4, 7),\n np.linspace(5.5, 8, 9),\n np.arange(48).reshape(8, 6),\n transform=times10 + ax.transData)\n\n ax.scatter(np.linspace(0, 10), np.linspace(10, 0),\n transform=times10 + ax.transData)\n\n x = np.linspace(8, 10, 20)\n y = np.linspace(1, 5, 20)\n u = 2*np.sin(x) + np.cos(y[:, np.newaxis])\n v = np.sin(x) - np.cos(y[:, np.newaxis])\n\n ax.streamplot(x, y, u, v, transform=times10 + ax.transData,\n linewidth=np.hypot(u, v))\n\n # reduce the vector data down a bit for barb and quiver plotting\n x, y = x[::3], y[::3]\n u, v = u[::3, ::3], v[::3, ::3]\n\n ax.quiver(x, y + 5, u, v, transform=times10 + ax.transData)\n\n ax.barbs(x - 3, y + 5, u**2, v**2, transform=times10 + ax.transData)\n\n\ndef test_contour_pre_transform_limits():\n ax = plt.axes()\n xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20))\n ax.contourf(xs, ys, np.log(xs * ys),\n transform=mtransforms.Affine2D().scale(0.1) + ax.transData)\n\n expected = np.array([[1.5, 1.24],\n [2., 1.25]])\n assert_almost_equal(expected, ax.dataLim.get_points())\n\n\ndef test_pcolor_pre_transform_limits():\n # Based on test_contour_pre_transform_limits()\n ax = plt.axes()\n xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20))\n ax.pcolor(xs, ys, np.log(xs * ys)[:-1, :-1],\n transform=mtransforms.Affine2D().scale(0.1) + ax.transData)\n\n expected = np.array([[1.5, 1.24],\n [2., 1.25]])\n assert_almost_equal(expected, ax.dataLim.get_points())\n\n\ndef test_pcolormesh_pre_transform_limits():\n # Based on test_contour_pre_transform_limits()\n ax = plt.axes()\n xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20))\n ax.pcolormesh(xs, ys, np.log(xs * ys)[:-1, :-1],\n transform=mtransforms.Affine2D().scale(0.1) + ax.transData)\n\n expected = np.array([[1.5, 1.24],\n [2., 1.25]])\n assert_almost_equal(expected, ax.dataLim.get_points())\n\n\ndef test_pcolormesh_gouraud_nans():\n np.random.seed(19680801)\n\n values = np.linspace(0, 180, 3)\n radii = np.linspace(100, 1000, 10)\n z, y = np.meshgrid(values, radii)\n x = np.radians(np.random.rand(*z.shape) * 100)\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection="polar")\n # Setting the limit to cause clipping of the r values causes NaN to be\n # introduced; these should not crash but be ignored as in other path\n # operations.\n ax.set_rlim(101, 1000)\n ax.pcolormesh(x, y, z, shading="gouraud")\n\n fig.canvas.draw()\n\n\ndef test_Affine2D_from_values():\n points = np.array([[0, 0],\n [10, 20],\n [-1, 0],\n ])\n\n t = mtransforms.Affine2D.from_values(1, 0, 0, 0, 0, 0)\n actual = t.transform(points)\n expected = np.array([[0, 0], [10, 0], [-1, 0]])\n assert_almost_equal(actual, expected)\n\n t = mtransforms.Affine2D.from_values(0, 2, 0, 0, 0, 0)\n actual = t.transform(points)\n expected = np.array([[0, 0], [0, 20], [0, -2]])\n assert_almost_equal(actual, expected)\n\n t = mtransforms.Affine2D.from_values(0, 0, 3, 0, 0, 0)\n actual = t.transform(points)\n expected = np.array([[0, 0], [60, 0], [0, 0]])\n assert_almost_equal(actual, expected)\n\n t = mtransforms.Affine2D.from_values(0, 0, 0, 4, 0, 0)\n actual = t.transform(points)\n expected = np.array([[0, 0], [0, 80], [0, 0]])\n assert_almost_equal(actual, expected)\n\n t = mtransforms.Affine2D.from_values(0, 0, 0, 0, 5, 0)\n actual = t.transform(points)\n expected = np.array([[5, 0], [5, 0], [5, 0]])\n assert_almost_equal(actual, expected)\n\n t = mtransforms.Affine2D.from_values(0, 0, 0, 0, 0, 6)\n actual = t.transform(points)\n expected = np.array([[0, 6], [0, 6], [0, 6]])\n assert_almost_equal(actual, expected)\n\n\ndef test_affine_inverted_invalidated():\n # Ensure that the an affine transform is not declared valid on access\n point = [1.0, 1.0]\n t = mtransforms.Affine2D()\n\n assert_almost_equal(point, t.transform(t.inverted().transform(point)))\n # Change and access the transform\n t.translate(1.0, 1.0).get_matrix()\n assert_almost_equal(point, t.transform(t.inverted().transform(point)))\n\n\ndef test_clipping_of_log():\n # issue 804\n path = Path._create_closed([(0.2, -99), (0.4, -99), (0.4, 20), (0.2, 20)])\n # something like this happens in plotting logarithmic histograms\n trans = mtransforms.BlendedGenericTransform(\n mtransforms.Affine2D(), scale.LogTransform(10, 'clip'))\n tpath = trans.transform_path_non_affine(path)\n result = tpath.iter_segments(trans.get_affine(),\n clip=(0, 0, 100, 100),\n simplify=False)\n tpoints, tcodes = zip(*result)\n assert_allclose(tcodes, path.codes[:-1]) # No longer closed.\n\n\nclass NonAffineForTest(mtransforms.Transform):\n """\n A class which looks like a non affine transform, but does whatever\n the given transform does (even if it is affine). This is very useful\n for testing NonAffine behaviour with a simple Affine transform.\n\n """\n is_affine = False\n output_dims = 2\n input_dims = 2\n\n def __init__(self, real_trans, *args, **kwargs):\n self.real_trans = real_trans\n super().__init__(*args, **kwargs)\n\n def transform_non_affine(self, values):\n return self.real_trans.transform(values)\n\n def transform_path_non_affine(self, path):\n return self.real_trans.transform_path(path)\n\n\nclass TestBasicTransform:\n def setup_method(self):\n\n self.ta1 = mtransforms.Affine2D(shorthand_name='ta1').rotate(np.pi / 2)\n self.ta2 = mtransforms.Affine2D(shorthand_name='ta2').translate(10, 0)\n self.ta3 = mtransforms.Affine2D(shorthand_name='ta3').scale(1, 2)\n\n self.tn1 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2),\n shorthand_name='tn1')\n self.tn2 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2),\n shorthand_name='tn2')\n self.tn3 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2),\n shorthand_name='tn3')\n\n # creates a transform stack which looks like ((A, (N, A)), A)\n self.stack1 = (self.ta1 + (self.tn1 + self.ta2)) + self.ta3\n # creates a transform stack which looks like (((A, N), A), A)\n self.stack2 = self.ta1 + self.tn1 + self.ta2 + self.ta3\n # creates a transform stack which is a subset of stack2\n self.stack2_subset = self.tn1 + self.ta2 + self.ta3\n\n # when in debug, the transform stacks can produce dot images:\n# self.stack1.write_graphviz(file('stack1.dot', 'w'))\n# self.stack2.write_graphviz(file('stack2.dot', 'w'))\n# self.stack2_subset.write_graphviz(file('stack2_subset.dot', 'w'))\n\n def test_transform_depth(self):\n assert self.stack1.depth == 4\n assert self.stack2.depth == 4\n assert self.stack2_subset.depth == 3\n\n def test_left_to_right_iteration(self):\n stack3 = (self.ta1 + (self.tn1 + (self.ta2 + self.tn2))) + self.ta3\n# stack3.write_graphviz(file('stack3.dot', 'w'))\n\n target_transforms = [stack3,\n (self.tn1 + (self.ta2 + self.tn2)) + self.ta3,\n (self.ta2 + self.tn2) + self.ta3,\n self.tn2 + self.ta3,\n self.ta3,\n ]\n r = [rh for _, rh in stack3._iter_break_from_left_to_right()]\n assert len(r) == len(target_transforms)\n\n for target_stack, stack in zip(target_transforms, r):\n assert target_stack == stack\n\n def test_transform_shortcuts(self):\n assert self.stack1 - self.stack2_subset == self.ta1\n assert self.stack2 - self.stack2_subset == self.ta1\n\n assert self.stack2_subset - self.stack2 == self.ta1.inverted()\n assert (self.stack2_subset - self.stack2).depth == 1\n\n with pytest.raises(ValueError):\n self.stack1 - self.stack2\n\n aff1 = self.ta1 + (self.ta2 + self.ta3)\n aff2 = self.ta2 + self.ta3\n\n assert aff1 - aff2 == self.ta1\n assert aff1 - self.ta2 == aff1 + self.ta2.inverted()\n\n assert self.stack1 - self.ta3 == self.ta1 + (self.tn1 + self.ta2)\n assert self.stack2 - self.ta3 == self.ta1 + self.tn1 + self.ta2\n\n assert ((self.ta2 + self.ta3) - self.ta3 + self.ta3 ==\n self.ta2 + self.ta3)\n\n def test_contains_branch(self):\n r1 = (self.ta2 + self.ta1)\n r2 = (self.ta2 + self.ta1)\n assert r1 == r2\n assert r1 != self.ta1\n assert r1.contains_branch(r2)\n assert r1.contains_branch(self.ta1)\n assert not r1.contains_branch(self.ta2)\n assert not r1.contains_branch(self.ta2 + self.ta2)\n\n assert r1 == r2\n\n assert self.stack1.contains_branch(self.ta3)\n assert self.stack2.contains_branch(self.ta3)\n\n assert self.stack1.contains_branch(self.stack2_subset)\n assert self.stack2.contains_branch(self.stack2_subset)\n\n assert not self.stack2_subset.contains_branch(self.stack1)\n assert not self.stack2_subset.contains_branch(self.stack2)\n\n assert self.stack1.contains_branch(self.ta2 + self.ta3)\n assert self.stack2.contains_branch(self.ta2 + self.ta3)\n\n assert not self.stack1.contains_branch(self.tn1 + self.ta2)\n\n blend = mtransforms.BlendedGenericTransform(self.tn2, self.stack2)\n x, y = blend.contains_branch_seperately(self.stack2_subset)\n stack_blend = self.tn3 + blend\n sx, sy = stack_blend.contains_branch_seperately(self.stack2_subset)\n assert x is sx is False\n assert y is sy is True\n\n def test_affine_simplification(self):\n # tests that a transform stack only calls as much is absolutely\n # necessary "non-affine" allowing the best possible optimization with\n # complex transformation stacks.\n points = np.array([[0, 0], [10, 20], [np.nan, 1], [-1, 0]],\n dtype=np.float64)\n na_pts = self.stack1.transform_non_affine(points)\n all_pts = self.stack1.transform(points)\n\n na_expected = np.array([[1., 2.], [-19., 12.],\n [np.nan, np.nan], [1., 1.]], dtype=np.float64)\n all_expected = np.array([[11., 4.], [-9., 24.],\n [np.nan, np.nan], [11., 2.]],\n dtype=np.float64)\n\n # check we have the expected results from doing the affine part only\n assert_array_almost_equal(na_pts, na_expected)\n # check we have the expected results from a full transformation\n assert_array_almost_equal(all_pts, all_expected)\n # check we have the expected results from doing the transformation in\n # two steps\n assert_array_almost_equal(self.stack1.transform_affine(na_pts),\n all_expected)\n # check that getting the affine transformation first, then fully\n # transforming using that yields the same result as before.\n assert_array_almost_equal(self.stack1.get_affine().transform(na_pts),\n all_expected)\n\n # check that the affine part of stack1 & stack2 are equivalent\n # (i.e. the optimization is working)\n expected_result = (self.ta2 + self.ta3).get_matrix()\n result = self.stack1.get_affine().get_matrix()\n assert_array_equal(expected_result, result)\n\n result = self.stack2.get_affine().get_matrix()\n assert_array_equal(expected_result, result)\n\n\nclass TestTransformPlotInterface:\n def test_line_extent_axes_coords(self):\n # a simple line in axes coordinates\n ax = plt.axes()\n ax.plot([0.1, 1.2, 0.8], [0.9, 0.5, 0.8], transform=ax.transAxes)\n assert_array_equal(ax.dataLim.get_points(),\n np.array([[np.inf, np.inf],\n [-np.inf, -np.inf]]))\n\n def test_line_extent_data_coords(self):\n # a simple line in data coordinates\n ax = plt.axes()\n ax.plot([0.1, 1.2, 0.8], [0.9, 0.5, 0.8], transform=ax.transData)\n assert_array_equal(ax.dataLim.get_points(),\n np.array([[0.1, 0.5], [1.2, 0.9]]))\n\n def test_line_extent_compound_coords1(self):\n # a simple line in data coordinates in the y component, and in axes\n # coordinates in the x\n ax = plt.axes()\n trans = mtransforms.blended_transform_factory(ax.transAxes,\n ax.transData)\n ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans)\n assert_array_equal(ax.dataLim.get_points(),\n np.array([[np.inf, -5.],\n [-np.inf, 35.]]))\n\n def test_line_extent_predata_transform_coords(self):\n # a simple line in (offset + data) coordinates\n ax = plt.axes()\n trans = mtransforms.Affine2D().scale(10) + ax.transData\n ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans)\n assert_array_equal(ax.dataLim.get_points(),\n np.array([[1., -50.], [12., 350.]]))\n\n def test_line_extent_compound_coords2(self):\n # a simple line in (offset + data) coordinates in the y component, and\n # in axes coordinates in the x\n ax = plt.axes()\n trans = mtransforms.blended_transform_factory(\n ax.transAxes, mtransforms.Affine2D().scale(10) + ax.transData)\n ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans)\n assert_array_equal(ax.dataLim.get_points(),\n np.array([[np.inf, -50.], [-np.inf, 350.]]))\n\n def test_line_extents_affine(self):\n ax = plt.axes()\n offset = mtransforms.Affine2D().translate(10, 10)\n plt.plot(np.arange(10), transform=offset + ax.transData)\n expected_data_lim = np.array([[0., 0.], [9., 9.]]) + 10\n assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)\n\n def test_line_extents_non_affine(self):\n ax = plt.axes()\n offset = mtransforms.Affine2D().translate(10, 10)\n na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10))\n plt.plot(np.arange(10), transform=offset + na_offset + ax.transData)\n expected_data_lim = np.array([[0., 0.], [9., 9.]]) + 20\n assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)\n\n def test_pathc_extents_non_affine(self):\n ax = plt.axes()\n offset = mtransforms.Affine2D().translate(10, 10)\n na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10))\n pth = Path([[0, 0], [0, 10], [10, 10], [10, 0]])\n patch = mpatches.PathPatch(pth,\n transform=offset + na_offset + ax.transData)\n ax.add_patch(patch)\n expected_data_lim = np.array([[0., 0.], [10., 10.]]) + 20\n assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)\n\n def test_pathc_extents_affine(self):\n ax = plt.axes()\n offset = mtransforms.Affine2D().translate(10, 10)\n pth = Path([[0, 0], [0, 10], [10, 10], [10, 0]])\n patch = mpatches.PathPatch(pth, transform=offset + ax.transData)\n ax.add_patch(patch)\n expected_data_lim = np.array([[0., 0.], [10., 10.]]) + 10\n assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)\n\n def test_line_extents_for_non_affine_transData(self):\n ax = plt.axes(projection='polar')\n # add 10 to the radius of the data\n offset = mtransforms.Affine2D().translate(0, 10)\n\n plt.plot(np.arange(10), transform=offset + ax.transData)\n # the data lim of a polar plot is stored in coordinates\n # before a transData transformation, hence the data limits\n # are not what is being shown on the actual plot.\n expected_data_lim = np.array([[0., 0.], [9., 9.]]) + [0, 10]\n assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)\n\n\ndef assert_bbox_eq(bbox1, bbox2):\n assert_array_equal(bbox1.bounds, bbox2.bounds)\n\n\ndef test_bbox_frozen_copies_minpos():\n bbox = mtransforms.Bbox.from_extents(0.0, 0.0, 1.0, 1.0, minpos=1.0)\n frozen = bbox.frozen()\n assert_array_equal(frozen.minpos, bbox.minpos)\n\n\ndef test_bbox_intersection():\n bbox_from_ext = mtransforms.Bbox.from_extents\n inter = mtransforms.Bbox.intersection\n\n r1 = bbox_from_ext(0, 0, 1, 1)\n r2 = bbox_from_ext(0.5, 0.5, 1.5, 1.5)\n r3 = bbox_from_ext(0.5, 0, 0.75, 0.75)\n r4 = bbox_from_ext(0.5, 1.5, 1, 2.5)\n r5 = bbox_from_ext(1, 1, 2, 2)\n\n # self intersection -> no change\n assert_bbox_eq(inter(r1, r1), r1)\n # simple intersection\n assert_bbox_eq(inter(r1, r2), bbox_from_ext(0.5, 0.5, 1, 1))\n # r3 contains r2\n assert_bbox_eq(inter(r1, r3), r3)\n # no intersection\n assert inter(r1, r4) is None\n # single point\n assert_bbox_eq(inter(r1, r5), bbox_from_ext(1, 1, 1, 1))\n\n\ndef test_bbox_as_strings():\n b = mtransforms.Bbox([[.5, 0], [.75, .75]])\n assert_bbox_eq(b, eval(repr(b), {'Bbox': mtransforms.Bbox}))\n asdict = eval(str(b), {'Bbox': dict})\n for k, v in asdict.items():\n assert getattr(b, k) == v\n fmt = '.1f'\n asdict = eval(format(b, fmt), {'Bbox': dict})\n for k, v in asdict.items():\n assert eval(format(getattr(b, k), fmt)) == v\n\n\ndef test_str_transform():\n # The str here should not be considered as "absolutely stable", and may be\n # reformatted later; this is just a smoketest for __str__.\n assert str(plt.subplot(projection="polar").transData) == """\\nCompositeGenericTransform(\n CompositeGenericTransform(\n CompositeGenericTransform(\n TransformWrapper(\n BlendedAffine2D(\n IdentityTransform(),\n IdentityTransform())),\n CompositeAffine2D(\n Affine2D().scale(1.0),\n Affine2D().scale(1.0))),\n PolarTransform(\n PolarAxes(0.125,0.1;0.775x0.8),\n use_rmin=True,\n apply_theta_transforms=False)),\n CompositeGenericTransform(\n CompositeGenericTransform(\n PolarAffine(\n TransformWrapper(\n BlendedAffine2D(\n IdentityTransform(),\n IdentityTransform())),\n LockableBbox(\n Bbox(x0=0.0, y0=0.0, x1=6.283185307179586, y1=1.0),\n [[-- --]\n [-- --]])),\n BboxTransformFrom(\n _WedgeBbox(\n (0.5, 0.5),\n TransformedBbox(\n Bbox(x0=0.0, y0=0.0, x1=6.283185307179586, y1=1.0),\n CompositeAffine2D(\n Affine2D().scale(1.0),\n Affine2D().scale(1.0))),\n LockableBbox(\n Bbox(x0=0.0, y0=0.0, x1=6.283185307179586, y1=1.0),\n [[-- --]\n [-- --]])))),\n BboxTransformTo(\n TransformedBbox(\n Bbox(x0=0.125, y0=0.09999999999999998, x1=0.9, y1=0.9),\n BboxTransformTo(\n TransformedBbox(\n Bbox(x0=0.0, y0=0.0, x1=8.0, y1=6.0),\n Affine2D().scale(80.0)))))))"""\n\n\ndef test_transform_single_point():\n t = mtransforms.Affine2D()\n r = t.transform_affine((1, 1))\n assert r.shape == (2,)\n\n\ndef test_log_transform():\n # Tests that the last line runs without exception (previously the\n # transform would fail if one of the axes was logarithmic).\n fig, ax = plt.subplots()\n ax.set_yscale('log')\n ax.transData.transform((1, 1))\n\n\ndef test_nan_overlap():\n a = mtransforms.Bbox([[0, 0], [1, 1]])\n b = mtransforms.Bbox([[0, 0], [1, np.nan]])\n assert not a.overlaps(b)\n\n\ndef test_transform_angles():\n t = mtransforms.Affine2D() # Identity transform\n angles = np.array([20, 45, 60])\n points = np.array([[0, 0], [1, 1], [2, 2]])\n\n # Identity transform does not change angles\n new_angles = t.transform_angles(angles, points)\n assert_array_almost_equal(angles, new_angles)\n\n # points missing a 2nd dimension\n with pytest.raises(ValueError):\n t.transform_angles(angles, points[0:2, 0:1])\n\n # Number of angles != Number of points\n with pytest.raises(ValueError):\n t.transform_angles(angles, points[0:2, :])\n\n\ndef test_nonsingular():\n # test for zero-expansion type cases; other cases may be added later\n zero_expansion = np.array([-0.001, 0.001])\n cases = [(0, np.nan), (0, 0), (0, 7.9e-317)]\n for args in cases:\n out = np.array(mtransforms.nonsingular(*args))\n assert_array_equal(out, zero_expansion)\n\n\ndef test_transformed_path():\n points = [(0, 0), (1, 0), (1, 1), (0, 1)]\n path = Path(points, closed=True)\n\n trans = mtransforms.Affine2D()\n trans_path = mtransforms.TransformedPath(path, trans)\n assert_allclose(trans_path.get_fully_transformed_path().vertices, points)\n\n # Changing the transform should change the result.\n r2 = 1 / np.sqrt(2)\n trans.rotate(np.pi / 4)\n assert_allclose(trans_path.get_fully_transformed_path().vertices,\n [(0, 0), (r2, r2), (0, 2 * r2), (-r2, r2)],\n atol=1e-15)\n\n # Changing the path does not change the result (it's cached).\n path.points = [(0, 0)] * 4\n assert_allclose(trans_path.get_fully_transformed_path().vertices,\n [(0, 0), (r2, r2), (0, 2 * r2), (-r2, r2)],\n atol=1e-15)\n\n\ndef test_transformed_patch_path():\n trans = mtransforms.Affine2D()\n patch = mpatches.Wedge((0, 0), 1, 45, 135, transform=trans)\n\n tpatch = mtransforms.TransformedPatchPath(patch)\n points = tpatch.get_fully_transformed_path().vertices\n\n # Changing the transform should change the result.\n trans.scale(2)\n assert_allclose(tpatch.get_fully_transformed_path().vertices, points * 2)\n\n # Changing the path should change the result (and cancel out the scaling\n # from the transform).\n patch.set_radius(0.5)\n assert_allclose(tpatch.get_fully_transformed_path().vertices, points)\n\n\n@pytest.mark.parametrize('locked_element', ['x0', 'y0', 'x1', 'y1'])\ndef test_lockable_bbox(locked_element):\n other_elements = ['x0', 'y0', 'x1', 'y1']\n other_elements.remove(locked_element)\n\n orig = mtransforms.Bbox.unit()\n locked = mtransforms.LockableBbox(orig, **{locked_element: 2})\n\n # LockableBbox should keep its locked element as specified in __init__.\n assert getattr(locked, locked_element) == 2\n assert getattr(locked, 'locked_' + locked_element) == 2\n for elem in other_elements:\n assert getattr(locked, elem) == getattr(orig, elem)\n\n # Changing underlying Bbox should update everything but locked element.\n orig.set_points(orig.get_points() + 10)\n assert getattr(locked, locked_element) == 2\n assert getattr(locked, 'locked_' + locked_element) == 2\n for elem in other_elements:\n assert getattr(locked, elem) == getattr(orig, elem)\n\n # Unlocking element should revert values back to the underlying Bbox.\n setattr(locked, 'locked_' + locked_element, None)\n assert getattr(locked, 'locked_' + locked_element) is None\n assert np.all(orig.get_points() == locked.get_points())\n\n # Relocking an element should change its value, but not others.\n setattr(locked, 'locked_' + locked_element, 3)\n assert getattr(locked, locked_element) == 3\n assert getattr(locked, 'locked_' + locked_element) == 3\n for elem in other_elements:\n assert getattr(locked, elem) == getattr(orig, elem)\n\n\ndef test_transformwrapper():\n t = mtransforms.TransformWrapper(mtransforms.Affine2D())\n with pytest.raises(ValueError, match=(\n r"The input and output dims of the new child \(1, 1\) "\n r"do not match those of current child \(2, 2\)")):\n t.set(scale.LogTransform(10))\n\n\n@check_figures_equal(extensions=["png"])\ndef test_scale_swapping(fig_test, fig_ref):\n np.random.seed(19680801)\n samples = np.random.normal(size=10)\n x = np.linspace(-5, 5, 10)\n\n for fig, log_state in zip([fig_test, fig_ref], [True, False]):\n ax = fig.subplots()\n ax.hist(samples, log=log_state, density=True)\n ax.plot(x, np.exp(-(x**2) / 2) / np.sqrt(2 * np.pi))\n fig.canvas.draw()\n ax.set_yscale('linear')\n\n\ndef test_offset_copy_errors():\n with pytest.raises(ValueError,\n match="'fontsize' is not a valid value for units;"\n " supported values are 'dots', 'points', 'inches'"):\n mtransforms.offset_copy(None, units='fontsize')\n\n with pytest.raises(ValueError,\n match='For units of inches or points a fig kwarg is needed'):\n mtransforms.offset_copy(None, units='inches')\n\n\ndef test_transformedbbox_contains():\n bb = TransformedBbox(Bbox.unit(), Affine2D().rotate_deg(30))\n assert bb.contains(.8, .5)\n assert bb.contains(-.4, .85)\n assert not bb.contains(.9, .5)\n bb = TransformedBbox(Bbox.unit(), Affine2D().translate(.25, .5))\n assert bb.contains(1.25, 1.5)\n assert not bb.fully_contains(1.25, 1.5)\n assert not bb.fully_contains(.1, .1)\n\n\ndef test_interval_contains():\n assert mtransforms.interval_contains((0, 1), 0.5)\n assert mtransforms.interval_contains((0, 1), 0)\n assert mtransforms.interval_contains((0, 1), 1)\n assert not mtransforms.interval_contains((0, 1), -1)\n assert not mtransforms.interval_contains((0, 1), 2)\n assert mtransforms.interval_contains((1, 0), 0.5)\n\n\ndef test_interval_contains_open():\n assert mtransforms.interval_contains_open((0, 1), 0.5)\n assert not mtransforms.interval_contains_open((0, 1), 0)\n assert not mtransforms.interval_contains_open((0, 1), 1)\n assert not mtransforms.interval_contains_open((0, 1), -1)\n assert not mtransforms.interval_contains_open((0, 1), 2)\n assert mtransforms.interval_contains_open((1, 0), 0.5)\n\n\ndef test_scaledrotation_initialization():\n """Test that the ScaledRotation object is initialized correctly."""\n theta = 1.0 # Arbitrary theta value for testing\n trans_shift = MagicMock() # Mock the trans_shift transformation\n scaled_rot = _ScaledRotation(theta, trans_shift)\n assert scaled_rot._theta == theta\n assert scaled_rot._trans_shift == trans_shift\n assert scaled_rot._mtx is None\n\n\ndef test_scaledrotation_get_matrix_invalid():\n """Test get_matrix when the matrix is invalid and needs recalculation."""\n theta = np.pi / 2\n trans_shift = MagicMock(transform=MagicMock(return_value=[[theta, 0]]))\n scaled_rot = _ScaledRotation(theta, trans_shift)\n scaled_rot._invalid = True\n matrix = scaled_rot.get_matrix()\n trans_shift.transform.assert_called_once_with([[theta, 0]])\n expected_rotation = np.array([[0, -1],\n [1, 0]])\n assert matrix is not None\n assert_allclose(matrix[:2, :2], expected_rotation, atol=1e-15)\n | .venv\Lib\site-packages\matplotlib\tests\test_transforms.py | test_transforms.py | Python | 48,671 | 0.95 | 0.089302 | 0.091694 | vue-tools | 477 | 2023-08-27T14:00:42.886153 | MIT | true | 4bbd32b251f3699f9ac30cedf5faa32b |
import numpy as np\nfrom numpy.testing import (\n assert_array_equal, assert_array_almost_equal, assert_array_less)\nimport numpy.ma.testutils as matest\nimport pytest\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.tri as mtri\nfrom matplotlib.path import Path\nfrom matplotlib.testing.decorators import image_comparison, check_figures_equal\n\n\nclass TestTriangulationParams:\n x = [-1, 0, 1, 0]\n y = [0, -1, 0, 1]\n triangles = [[0, 1, 2], [0, 2, 3]]\n mask = [False, True]\n\n @pytest.mark.parametrize('args, kwargs, expected', [\n ([x, y], {}, [x, y, None, None]),\n ([x, y, triangles], {}, [x, y, triangles, None]),\n ([x, y], dict(triangles=triangles), [x, y, triangles, None]),\n ([x, y], dict(mask=mask), [x, y, None, mask]),\n ([x, y, triangles], dict(mask=mask), [x, y, triangles, mask]),\n ([x, y], dict(triangles=triangles, mask=mask), [x, y, triangles, mask])\n ])\n def test_extract_triangulation_params(self, args, kwargs, expected):\n other_args = [1, 2]\n other_kwargs = {'a': 3, 'b': '4'}\n x_, y_, triangles_, mask_, args_, kwargs_ = \\n mtri.Triangulation._extract_triangulation_params(\n args + other_args, {**kwargs, **other_kwargs})\n x, y, triangles, mask = expected\n assert x_ is x\n assert y_ is y\n assert_array_equal(triangles_, triangles)\n assert mask_ is mask\n assert args_ == other_args\n assert kwargs_ == other_kwargs\n\n\ndef test_extract_triangulation_positional_mask():\n # mask cannot be passed positionally\n mask = [True]\n args = [[0, 2, 1], [0, 0, 1], [[0, 1, 2]], mask]\n x_, y_, triangles_, mask_, args_, kwargs_ = \\n mtri.Triangulation._extract_triangulation_params(args, {})\n assert mask_ is None\n assert args_ == [mask]\n # the positional mask must be caught downstream because this must pass\n # unknown args through\n\n\ndef test_triangulation_init():\n x = [-1, 0, 1, 0]\n y = [0, -1, 0, 1]\n with pytest.raises(ValueError, match="x and y must be equal-length"):\n mtri.Triangulation(x, [1, 2])\n with pytest.raises(\n ValueError,\n match=r"triangles must be a \(N, 3\) int array, but found shape "\n r"\(3,\)"):\n mtri.Triangulation(x, y, [0, 1, 2])\n with pytest.raises(\n ValueError,\n match=r"triangles must be a \(N, 3\) int array, not 'other'"):\n mtri.Triangulation(x, y, 'other')\n with pytest.raises(ValueError, match="found value 99"):\n mtri.Triangulation(x, y, [[0, 1, 99]])\n with pytest.raises(ValueError, match="found value -1"):\n mtri.Triangulation(x, y, [[0, 1, -1]])\n\n\ndef test_triangulation_set_mask():\n x = [-1, 0, 1, 0]\n y = [0, -1, 0, 1]\n triangles = [[0, 1, 2], [2, 3, 0]]\n triang = mtri.Triangulation(x, y, triangles)\n\n # Check neighbors, which forces creation of C++ triangulation\n assert_array_equal(triang.neighbors, [[-1, -1, 1], [-1, -1, 0]])\n\n # Set mask\n triang.set_mask([False, True])\n assert_array_equal(triang.mask, [False, True])\n\n # Reset mask\n triang.set_mask(None)\n assert triang.mask is None\n\n msg = r"mask array must have same length as triangles array"\n for mask in ([False, True, False], [False], [True], False, True):\n with pytest.raises(ValueError, match=msg):\n triang.set_mask(mask)\n\n\ndef test_delaunay():\n # No duplicate points, regular grid.\n nx = 5\n ny = 4\n x, y = np.meshgrid(np.linspace(0.0, 1.0, nx), np.linspace(0.0, 1.0, ny))\n x = x.ravel()\n y = y.ravel()\n npoints = nx*ny\n ntriangles = 2 * (nx-1) * (ny-1)\n nedges = 3*nx*ny - 2*nx - 2*ny + 1\n\n # Create delaunay triangulation.\n triang = mtri.Triangulation(x, y)\n\n # The tests in the remainder of this function should be passed by any\n # triangulation that does not contain duplicate points.\n\n # Points - floating point.\n assert_array_almost_equal(triang.x, x)\n assert_array_almost_equal(triang.y, y)\n\n # Triangles - integers.\n assert len(triang.triangles) == ntriangles\n assert np.min(triang.triangles) == 0\n assert np.max(triang.triangles) == npoints-1\n\n # Edges - integers.\n assert len(triang.edges) == nedges\n assert np.min(triang.edges) == 0\n assert np.max(triang.edges) == npoints-1\n\n # Neighbors - integers.\n # Check that neighbors calculated by C++ triangulation class are the same\n # as those returned from delaunay routine.\n neighbors = triang.neighbors\n triang._neighbors = None\n assert_array_equal(triang.neighbors, neighbors)\n\n # Is each point used in at least one triangle?\n assert_array_equal(np.unique(triang.triangles), np.arange(npoints))\n\n\ndef test_delaunay_duplicate_points():\n npoints = 10\n duplicate = 7\n duplicate_of = 3\n\n np.random.seed(23)\n x = np.random.random(npoints)\n y = np.random.random(npoints)\n x[duplicate] = x[duplicate_of]\n y[duplicate] = y[duplicate_of]\n\n # Create delaunay triangulation.\n triang = mtri.Triangulation(x, y)\n\n # Duplicate points should be ignored, so the index of the duplicate points\n # should not appear in any triangle.\n assert_array_equal(np.unique(triang.triangles),\n np.delete(np.arange(npoints), duplicate))\n\n\ndef test_delaunay_points_in_line():\n # Cannot triangulate points that are all in a straight line, but check\n # that delaunay code fails gracefully.\n x = np.linspace(0.0, 10.0, 11)\n y = np.linspace(0.0, 10.0, 11)\n with pytest.raises(RuntimeError):\n mtri.Triangulation(x, y)\n\n # Add an extra point not on the line and the triangulation is OK.\n x = np.append(x, 2.0)\n y = np.append(y, 8.0)\n mtri.Triangulation(x, y)\n\n\n@pytest.mark.parametrize('x, y', [\n # Triangulation should raise a ValueError if passed less than 3 points.\n ([], []),\n ([1], [5]),\n ([1, 2], [5, 6]),\n # Triangulation should also raise a ValueError if passed duplicate points\n # such that there are less than 3 unique points.\n ([1, 2, 1], [5, 6, 5]),\n ([1, 2, 2], [5, 6, 6]),\n ([1, 1, 1, 2, 1, 2], [5, 5, 5, 6, 5, 6]),\n])\ndef test_delaunay_insufficient_points(x, y):\n with pytest.raises(ValueError):\n mtri.Triangulation(x, y)\n\n\ndef test_delaunay_robust():\n # Fails when mtri.Triangulation uses matplotlib.delaunay, works when using\n # qhull.\n tri_points = np.array([\n [0.8660254037844384, -0.5000000000000004],\n [0.7577722283113836, -0.5000000000000004],\n [0.6495190528383288, -0.5000000000000003],\n [0.5412658773652739, -0.5000000000000003],\n [0.811898816047911, -0.40625000000000044],\n [0.7036456405748561, -0.4062500000000004],\n [0.5953924651018013, -0.40625000000000033]])\n test_points = np.asarray([\n [0.58, -0.46],\n [0.65, -0.46],\n [0.65, -0.42],\n [0.7, -0.48],\n [0.7, -0.44],\n [0.75, -0.44],\n [0.8, -0.48]])\n\n # Utility function that indicates if a triangle defined by 3 points\n # (xtri, ytri) contains the test point xy. Avoid calling with a point that\n # lies on or very near to an edge of the triangle.\n def tri_contains_point(xtri, ytri, xy):\n tri_points = np.vstack((xtri, ytri)).T\n return Path(tri_points).contains_point(xy)\n\n # Utility function that returns how many triangles of the specified\n # triangulation contain the test point xy. Avoid calling with a point that\n # lies on or very near to an edge of any triangle in the triangulation.\n def tris_contain_point(triang, xy):\n return sum(tri_contains_point(triang.x[tri], triang.y[tri], xy)\n for tri in triang.triangles)\n\n # Using matplotlib.delaunay, an invalid triangulation is created with\n # overlapping triangles; qhull is OK.\n triang = mtri.Triangulation(tri_points[:, 0], tri_points[:, 1])\n for test_point in test_points:\n assert tris_contain_point(triang, test_point) == 1\n\n # If ignore the first point of tri_points, matplotlib.delaunay throws a\n # KeyError when calculating the convex hull; qhull is OK.\n triang = mtri.Triangulation(tri_points[1:, 0], tri_points[1:, 1])\n\n\n@image_comparison(['tripcolor1.png'])\ndef test_tripcolor():\n x = np.asarray([0, 0.5, 1, 0, 0.5, 1, 0, 0.5, 1, 0.75])\n y = np.asarray([0, 0, 0, 0.5, 0.5, 0.5, 1, 1, 1, 0.75])\n triangles = np.asarray([\n [0, 1, 3], [1, 4, 3],\n [1, 2, 4], [2, 5, 4],\n [3, 4, 6], [4, 7, 6],\n [4, 5, 9], [7, 4, 9], [8, 7, 9], [5, 8, 9]])\n\n # Triangulation with same number of points and triangles.\n triang = mtri.Triangulation(x, y, triangles)\n\n Cpoints = x + 0.5*y\n\n xmid = x[triang.triangles].mean(axis=1)\n ymid = y[triang.triangles].mean(axis=1)\n Cfaces = 0.5*xmid + ymid\n\n plt.subplot(121)\n plt.tripcolor(triang, Cpoints, edgecolors='k')\n plt.title('point colors')\n\n plt.subplot(122)\n plt.tripcolor(triang, facecolors=Cfaces, edgecolors='k')\n plt.title('facecolors')\n\n\ndef test_tripcolor_color():\n x = [-1, 0, 1, 0]\n y = [0, -1, 0, 1]\n fig, ax = plt.subplots()\n with pytest.raises(TypeError, match=r"tripcolor\(\) missing 1 required "):\n ax.tripcolor(x, y)\n with pytest.raises(ValueError, match="The length of c must match either"):\n ax.tripcolor(x, y, [1, 2, 3])\n with pytest.raises(ValueError,\n match="length of facecolors must match .* triangles"):\n ax.tripcolor(x, y, facecolors=[1, 2, 3, 4])\n with pytest.raises(ValueError,\n match="'gouraud' .* at the points.* not at the faces"):\n ax.tripcolor(x, y, facecolors=[1, 2], shading='gouraud')\n with pytest.raises(ValueError,\n match="'gouraud' .* at the points.* not at the faces"):\n ax.tripcolor(x, y, [1, 2], shading='gouraud') # faces\n with pytest.raises(TypeError,\n match="positional.*'c'.*keyword-only.*'facecolors'"):\n ax.tripcolor(x, y, C=[1, 2, 3, 4])\n with pytest.raises(TypeError, match="Unexpected positional parameter"):\n ax.tripcolor(x, y, [1, 2], 'unused_positional')\n\n # smoke test for valid color specifications (via C or facecolors)\n ax.tripcolor(x, y, [1, 2, 3, 4]) # edges\n ax.tripcolor(x, y, [1, 2, 3, 4], shading='gouraud') # edges\n ax.tripcolor(x, y, [1, 2]) # faces\n ax.tripcolor(x, y, facecolors=[1, 2]) # faces\n\n\ndef test_tripcolor_clim():\n np.random.seed(19680801)\n a, b, c = np.random.rand(10), np.random.rand(10), np.random.rand(10)\n\n ax = plt.figure().add_subplot()\n clim = (0.25, 0.75)\n norm = ax.tripcolor(a, b, c, clim=clim).norm\n assert (norm.vmin, norm.vmax) == clim\n\n\ndef test_tripcolor_warnings():\n x = [-1, 0, 1, 0]\n y = [0, -1, 0, 1]\n c = [0.4, 0.5]\n fig, ax = plt.subplots()\n # facecolors takes precedence over c\n with pytest.warns(UserWarning, match="Positional parameter c .*no effect"):\n ax.tripcolor(x, y, c, facecolors=c)\n with pytest.warns(UserWarning, match="Positional parameter c .*no effect"):\n ax.tripcolor(x, y, 'interpreted as c', facecolors=c)\n\n\ndef test_no_modify():\n # Test that Triangulation does not modify triangles array passed to it.\n triangles = np.array([[3, 2, 0], [3, 1, 0]], dtype=np.int32)\n points = np.array([(0, 0), (0, 1.1), (1, 0), (1, 1)])\n\n old_triangles = triangles.copy()\n mtri.Triangulation(points[:, 0], points[:, 1], triangles).edges\n assert_array_equal(old_triangles, triangles)\n\n\ndef test_trifinder():\n # Test points within triangles of masked triangulation.\n x, y = np.meshgrid(np.arange(4), np.arange(4))\n x = x.ravel()\n y = y.ravel()\n triangles = [[0, 1, 4], [1, 5, 4], [1, 2, 5], [2, 6, 5], [2, 3, 6],\n [3, 7, 6], [4, 5, 8], [5, 9, 8], [5, 6, 9], [6, 10, 9],\n [6, 7, 10], [7, 11, 10], [8, 9, 12], [9, 13, 12], [9, 10, 13],\n [10, 14, 13], [10, 11, 14], [11, 15, 14]]\n mask = np.zeros(len(triangles))\n mask[8:10] = 1\n triang = mtri.Triangulation(x, y, triangles, mask)\n trifinder = triang.get_trifinder()\n\n xs = [0.25, 1.25, 2.25, 3.25]\n ys = [0.25, 1.25, 2.25, 3.25]\n xs, ys = np.meshgrid(xs, ys)\n xs = xs.ravel()\n ys = ys.ravel()\n tris = trifinder(xs, ys)\n assert_array_equal(tris, [0, 2, 4, -1, 6, -1, 10, -1,\n 12, 14, 16, -1, -1, -1, -1, -1])\n tris = trifinder(xs-0.5, ys-0.5)\n assert_array_equal(tris, [-1, -1, -1, -1, -1, 1, 3, 5,\n -1, 7, -1, 11, -1, 13, 15, 17])\n\n # Test points exactly on boundary edges of masked triangulation.\n xs = [0.5, 1.5, 2.5, 0.5, 1.5, 2.5, 1.5, 1.5, 0.0, 1.0, 2.0, 3.0]\n ys = [0.0, 0.0, 0.0, 3.0, 3.0, 3.0, 1.0, 2.0, 1.5, 1.5, 1.5, 1.5]\n tris = trifinder(xs, ys)\n assert_array_equal(tris, [0, 2, 4, 13, 15, 17, 3, 14, 6, 7, 10, 11])\n\n # Test points exactly on boundary corners of masked triangulation.\n xs = [0.0, 3.0]\n ys = [0.0, 3.0]\n tris = trifinder(xs, ys)\n assert_array_equal(tris, [0, 17])\n\n #\n # Test triangles with horizontal colinear points. These are not valid\n # triangulations, but we try to deal with the simplest violations.\n #\n\n # If +ve, triangulation is OK, if -ve triangulation invalid,\n # if zero have colinear points but should pass tests anyway.\n delta = 0.0\n\n x = [1.5, 0, 1, 2, 3, 1.5, 1.5]\n y = [-1, 0, 0, 0, 0, delta, 1]\n triangles = [[0, 2, 1], [0, 3, 2], [0, 4, 3], [1, 2, 5], [2, 3, 5],\n [3, 4, 5], [1, 5, 6], [4, 6, 5]]\n triang = mtri.Triangulation(x, y, triangles)\n trifinder = triang.get_trifinder()\n\n xs = [-0.1, 0.4, 0.9, 1.4, 1.9, 2.4, 2.9]\n ys = [-0.1, 0.1]\n xs, ys = np.meshgrid(xs, ys)\n tris = trifinder(xs, ys)\n assert_array_equal(tris, [[-1, 0, 0, 1, 1, 2, -1],\n [-1, 6, 6, 6, 7, 7, -1]])\n\n #\n # Test triangles with vertical colinear points. These are not valid\n # triangulations, but we try to deal with the simplest violations.\n #\n\n # If +ve, triangulation is OK, if -ve triangulation invalid,\n # if zero have colinear points but should pass tests anyway.\n delta = 0.0\n\n x = [-1, -delta, 0, 0, 0, 0, 1]\n y = [1.5, 1.5, 0, 1, 2, 3, 1.5]\n triangles = [[0, 1, 2], [0, 1, 5], [1, 2, 3], [1, 3, 4], [1, 4, 5],\n [2, 6, 3], [3, 6, 4], [4, 6, 5]]\n triang = mtri.Triangulation(x, y, triangles)\n trifinder = triang.get_trifinder()\n\n xs = [-0.1, 0.1]\n ys = [-0.1, 0.4, 0.9, 1.4, 1.9, 2.4, 2.9]\n xs, ys = np.meshgrid(xs, ys)\n tris = trifinder(xs, ys)\n assert_array_equal(tris, [[-1, -1], [0, 5], [0, 5], [0, 6], [1, 6], [1, 7],\n [-1, -1]])\n\n # Test that changing triangulation by setting a mask causes the trifinder\n # to be reinitialised.\n x = [0, 1, 0, 1]\n y = [0, 0, 1, 1]\n triangles = [[0, 1, 2], [1, 3, 2]]\n triang = mtri.Triangulation(x, y, triangles)\n trifinder = triang.get_trifinder()\n\n xs = [-0.2, 0.2, 0.8, 1.2]\n ys = [0.5, 0.5, 0.5, 0.5]\n tris = trifinder(xs, ys)\n assert_array_equal(tris, [-1, 0, 1, -1])\n\n triang.set_mask([1, 0])\n assert trifinder == triang.get_trifinder()\n tris = trifinder(xs, ys)\n assert_array_equal(tris, [-1, -1, 1, -1])\n\n\ndef test_triinterp():\n # Test points within triangles of masked triangulation.\n x, y = np.meshgrid(np.arange(4), np.arange(4))\n x = x.ravel()\n y = y.ravel()\n z = 1.23*x - 4.79*y\n triangles = [[0, 1, 4], [1, 5, 4], [1, 2, 5], [2, 6, 5], [2, 3, 6],\n [3, 7, 6], [4, 5, 8], [5, 9, 8], [5, 6, 9], [6, 10, 9],\n [6, 7, 10], [7, 11, 10], [8, 9, 12], [9, 13, 12], [9, 10, 13],\n [10, 14, 13], [10, 11, 14], [11, 15, 14]]\n mask = np.zeros(len(triangles))\n mask[8:10] = 1\n triang = mtri.Triangulation(x, y, triangles, mask)\n linear_interp = mtri.LinearTriInterpolator(triang, z)\n cubic_min_E = mtri.CubicTriInterpolator(triang, z)\n cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')\n\n xs = np.linspace(0.25, 2.75, 6)\n ys = [0.25, 0.75, 2.25, 2.75]\n xs, ys = np.meshgrid(xs, ys) # Testing arrays with array.ndim = 2\n for interp in (linear_interp, cubic_min_E, cubic_geom):\n zs = interp(xs, ys)\n assert_array_almost_equal(zs, (1.23*xs - 4.79*ys))\n\n # Test points outside triangulation.\n xs = [-0.25, 1.25, 1.75, 3.25]\n ys = xs\n xs, ys = np.meshgrid(xs, ys)\n for interp in (linear_interp, cubic_min_E, cubic_geom):\n zs = linear_interp(xs, ys)\n assert_array_equal(zs.mask, [[True]*4]*4)\n\n # Test mixed configuration (outside / inside).\n xs = np.linspace(0.25, 1.75, 6)\n ys = [0.25, 0.75, 1.25, 1.75]\n xs, ys = np.meshgrid(xs, ys)\n for interp in (linear_interp, cubic_min_E, cubic_geom):\n zs = interp(xs, ys)\n matest.assert_array_almost_equal(zs, (1.23*xs - 4.79*ys))\n mask = (xs >= 1) * (xs <= 2) * (ys >= 1) * (ys <= 2)\n assert_array_equal(zs.mask, mask)\n\n # 2nd order patch test: on a grid with an 'arbitrary shaped' triangle,\n # patch test shall be exact for quadratic functions and cubic\n # interpolator if *kind* = user\n (a, b, c) = (1.23, -4.79, 0.6)\n\n def quad(x, y):\n return a*(x-0.5)**2 + b*(y-0.5)**2 + c*x*y\n\n def gradient_quad(x, y):\n return (2*a*(x-0.5) + c*y, 2*b*(y-0.5) + c*x)\n\n x = np.array([0.2, 0.33367, 0.669, 0., 1., 1., 0.])\n y = np.array([0.3, 0.80755, 0.4335, 0., 0., 1., 1.])\n triangles = np.array([[0, 1, 2], [3, 0, 4], [4, 0, 2], [4, 2, 5],\n [1, 5, 2], [6, 5, 1], [6, 1, 0], [6, 0, 3]])\n triang = mtri.Triangulation(x, y, triangles)\n z = quad(x, y)\n dz = gradient_quad(x, y)\n # test points for 2nd order patch test\n xs = np.linspace(0., 1., 5)\n ys = np.linspace(0., 1., 5)\n xs, ys = np.meshgrid(xs, ys)\n cubic_user = mtri.CubicTriInterpolator(triang, z, kind='user', dz=dz)\n interp_zs = cubic_user(xs, ys)\n assert_array_almost_equal(interp_zs, quad(xs, ys))\n (interp_dzsdx, interp_dzsdy) = cubic_user.gradient(x, y)\n (dzsdx, dzsdy) = gradient_quad(x, y)\n assert_array_almost_equal(interp_dzsdx, dzsdx)\n assert_array_almost_equal(interp_dzsdy, dzsdy)\n\n # Cubic improvement: cubic interpolation shall perform better than linear\n # on a sufficiently dense mesh for a quadratic function.\n n = 11\n x, y = np.meshgrid(np.linspace(0., 1., n+1), np.linspace(0., 1., n+1))\n x = x.ravel()\n y = y.ravel()\n z = quad(x, y)\n triang = mtri.Triangulation(x, y, triangles=meshgrid_triangles(n+1))\n xs, ys = np.meshgrid(np.linspace(0.1, 0.9, 5), np.linspace(0.1, 0.9, 5))\n xs = xs.ravel()\n ys = ys.ravel()\n linear_interp = mtri.LinearTriInterpolator(triang, z)\n cubic_min_E = mtri.CubicTriInterpolator(triang, z)\n cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')\n zs = quad(xs, ys)\n diff_lin = np.abs(linear_interp(xs, ys) - zs)\n for interp in (cubic_min_E, cubic_geom):\n diff_cubic = np.abs(interp(xs, ys) - zs)\n assert np.max(diff_lin) >= 10 * np.max(diff_cubic)\n assert (np.dot(diff_lin, diff_lin) >=\n 100 * np.dot(diff_cubic, diff_cubic))\n\n\ndef test_triinterpcubic_C1_continuity():\n # Below the 4 tests which demonstrate C1 continuity of the\n # TriCubicInterpolator (testing the cubic shape functions on arbitrary\n # triangle):\n #\n # 1) Testing continuity of function & derivatives at corner for all 9\n # shape functions. Testing also function values at same location.\n # 2) Testing C1 continuity along each edge (as gradient is polynomial of\n # 2nd order, it is sufficient to test at the middle).\n # 3) Testing C1 continuity at triangle barycenter (where the 3 subtriangles\n # meet)\n # 4) Testing C1 continuity at median 1/3 points (midside between 2\n # subtriangles)\n\n # Utility test function check_continuity\n def check_continuity(interpolator, loc, values=None):\n """\n Checks the continuity of interpolator (and its derivatives) near\n location loc. Can check the value at loc itself if *values* is\n provided.\n\n *interpolator* TriInterpolator\n *loc* location to test (x0, y0)\n *values* (optional) array [z0, dzx0, dzy0] to check the value at *loc*\n """\n n_star = 24 # Number of continuity points in a boundary of loc\n epsilon = 1.e-10 # Distance for loc boundary\n k = 100. # Continuity coefficient\n (loc_x, loc_y) = loc\n star_x = loc_x + epsilon*np.cos(np.linspace(0., 2*np.pi, n_star))\n star_y = loc_y + epsilon*np.sin(np.linspace(0., 2*np.pi, n_star))\n z = interpolator([loc_x], [loc_y])[0]\n (dzx, dzy) = interpolator.gradient([loc_x], [loc_y])\n if values is not None:\n assert_array_almost_equal(z, values[0])\n assert_array_almost_equal(dzx[0], values[1])\n assert_array_almost_equal(dzy[0], values[2])\n diff_z = interpolator(star_x, star_y) - z\n (tab_dzx, tab_dzy) = interpolator.gradient(star_x, star_y)\n diff_dzx = tab_dzx - dzx\n diff_dzy = tab_dzy - dzy\n assert_array_less(diff_z, epsilon*k)\n assert_array_less(diff_dzx, epsilon*k)\n assert_array_less(diff_dzy, epsilon*k)\n\n # Drawing arbitrary triangle (a, b, c) inside a unit square.\n (ax, ay) = (0.2, 0.3)\n (bx, by) = (0.33367, 0.80755)\n (cx, cy) = (0.669, 0.4335)\n x = np.array([ax, bx, cx, 0., 1., 1., 0.])\n y = np.array([ay, by, cy, 0., 0., 1., 1.])\n triangles = np.array([[0, 1, 2], [3, 0, 4], [4, 0, 2], [4, 2, 5],\n [1, 5, 2], [6, 5, 1], [6, 1, 0], [6, 0, 3]])\n triang = mtri.Triangulation(x, y, triangles)\n\n for idof in range(9):\n z = np.zeros(7, dtype=np.float64)\n dzx = np.zeros(7, dtype=np.float64)\n dzy = np.zeros(7, dtype=np.float64)\n values = np.zeros([3, 3], dtype=np.float64)\n case = idof//3\n values[case, idof % 3] = 1.0\n if case == 0:\n z[idof] = 1.0\n elif case == 1:\n dzx[idof % 3] = 1.0\n elif case == 2:\n dzy[idof % 3] = 1.0\n interp = mtri.CubicTriInterpolator(triang, z, kind='user',\n dz=(dzx, dzy))\n # Test 1) Checking values and continuity at nodes\n check_continuity(interp, (ax, ay), values[:, 0])\n check_continuity(interp, (bx, by), values[:, 1])\n check_continuity(interp, (cx, cy), values[:, 2])\n # Test 2) Checking continuity at midside nodes\n check_continuity(interp, ((ax+bx)*0.5, (ay+by)*0.5))\n check_continuity(interp, ((ax+cx)*0.5, (ay+cy)*0.5))\n check_continuity(interp, ((cx+bx)*0.5, (cy+by)*0.5))\n # Test 3) Checking continuity at barycenter\n check_continuity(interp, ((ax+bx+cx)/3., (ay+by+cy)/3.))\n # Test 4) Checking continuity at median 1/3-point\n check_continuity(interp, ((4.*ax+bx+cx)/6., (4.*ay+by+cy)/6.))\n check_continuity(interp, ((ax+4.*bx+cx)/6., (ay+4.*by+cy)/6.))\n check_continuity(interp, ((ax+bx+4.*cx)/6., (ay+by+4.*cy)/6.))\n\n\ndef test_triinterpcubic_cg_solver():\n # Now 3 basic tests of the Sparse CG solver, used for\n # TriCubicInterpolator with *kind* = 'min_E'\n # 1) A commonly used test involves a 2d Poisson matrix.\n def poisson_sparse_matrix(n, m):\n """\n Return the sparse, (n*m, n*m) matrix in coo format resulting from the\n discretisation of the 2-dimensional Poisson equation according to a\n finite difference numerical scheme on a uniform (n, m) grid.\n """\n l = m*n\n rows = np.concatenate([\n np.arange(l, dtype=np.int32),\n np.arange(l-1, dtype=np.int32), np.arange(1, l, dtype=np.int32),\n np.arange(l-n, dtype=np.int32), np.arange(n, l, dtype=np.int32)])\n cols = np.concatenate([\n np.arange(l, dtype=np.int32),\n np.arange(1, l, dtype=np.int32), np.arange(l-1, dtype=np.int32),\n np.arange(n, l, dtype=np.int32), np.arange(l-n, dtype=np.int32)])\n vals = np.concatenate([\n 4*np.ones(l, dtype=np.float64),\n -np.ones(l-1, dtype=np.float64), -np.ones(l-1, dtype=np.float64),\n -np.ones(l-n, dtype=np.float64), -np.ones(l-n, dtype=np.float64)])\n # In fact +1 and -1 diags have some zeros\n vals[l:2*l-1][m-1::m] = 0.\n vals[2*l-1:3*l-2][m-1::m] = 0.\n return vals, rows, cols, (n*m, n*m)\n\n # Instantiating a sparse Poisson matrix of size 48 x 48:\n (n, m) = (12, 4)\n mat = mtri._triinterpolate._Sparse_Matrix_coo(*poisson_sparse_matrix(n, m))\n mat.compress_csc()\n mat_dense = mat.to_dense()\n # Testing a sparse solve for all 48 basis vector\n for itest in range(n*m):\n b = np.zeros(n*m, dtype=np.float64)\n b[itest] = 1.\n x, _ = mtri._triinterpolate._cg(A=mat, b=b, x0=np.zeros(n*m),\n tol=1.e-10)\n assert_array_almost_equal(np.dot(mat_dense, x), b)\n\n # 2) Same matrix with inserting 2 rows - cols with null diag terms\n # (but still linked with the rest of the matrix by extra-diag terms)\n (i_zero, j_zero) = (12, 49)\n vals, rows, cols, _ = poisson_sparse_matrix(n, m)\n rows = rows + 1*(rows >= i_zero) + 1*(rows >= j_zero)\n cols = cols + 1*(cols >= i_zero) + 1*(cols >= j_zero)\n # adding extra-diag terms\n rows = np.concatenate([rows, [i_zero, i_zero-1, j_zero, j_zero-1]])\n cols = np.concatenate([cols, [i_zero-1, i_zero, j_zero-1, j_zero]])\n vals = np.concatenate([vals, [1., 1., 1., 1.]])\n mat = mtri._triinterpolate._Sparse_Matrix_coo(vals, rows, cols,\n (n*m + 2, n*m + 2))\n mat.compress_csc()\n mat_dense = mat.to_dense()\n # Testing a sparse solve for all 50 basis vec\n for itest in range(n*m + 2):\n b = np.zeros(n*m + 2, dtype=np.float64)\n b[itest] = 1.\n x, _ = mtri._triinterpolate._cg(A=mat, b=b, x0=np.ones(n * m + 2),\n tol=1.e-10)\n assert_array_almost_equal(np.dot(mat_dense, x), b)\n\n # 3) Now a simple test that summation of duplicate (i.e. with same rows,\n # same cols) entries occurs when compressed.\n vals = np.ones(17, dtype=np.float64)\n rows = np.array([0, 1, 2, 0, 0, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1],\n dtype=np.int32)\n cols = np.array([0, 1, 2, 1, 1, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2],\n dtype=np.int32)\n dim = (3, 3)\n mat = mtri._triinterpolate._Sparse_Matrix_coo(vals, rows, cols, dim)\n mat.compress_csc()\n mat_dense = mat.to_dense()\n assert_array_almost_equal(mat_dense, np.array([\n [1., 2., 0.], [2., 1., 5.], [0., 5., 1.]], dtype=np.float64))\n\n\ndef test_triinterpcubic_geom_weights():\n # Tests to check computation of weights for _DOF_estimator_geom:\n # The weight sum per triangle can be 1. (in case all angles < 90 degrees)\n # or (2*w_i) where w_i = 1-alpha_i/np.pi is the weight of apex i; alpha_i\n # is the apex angle > 90 degrees.\n (ax, ay) = (0., 1.687)\n x = np.array([ax, 0.5*ax, 0., 1.])\n y = np.array([ay, -ay, 0., 0.])\n z = np.zeros(4, dtype=np.float64)\n triangles = [[0, 2, 3], [1, 3, 2]]\n sum_w = np.zeros([4, 2]) # 4 possibilities; 2 triangles\n for theta in np.linspace(0., 2*np.pi, 14): # rotating the figure...\n x_rot = np.cos(theta)*x + np.sin(theta)*y\n y_rot = -np.sin(theta)*x + np.cos(theta)*y\n triang = mtri.Triangulation(x_rot, y_rot, triangles)\n cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')\n dof_estimator = mtri._triinterpolate._DOF_estimator_geom(cubic_geom)\n weights = dof_estimator.compute_geom_weights()\n # Testing for the 4 possibilities...\n sum_w[0, :] = np.sum(weights, 1) - 1\n for itri in range(3):\n sum_w[itri+1, :] = np.sum(weights, 1) - 2*weights[:, itri]\n assert_array_almost_equal(np.min(np.abs(sum_w), axis=0),\n np.array([0., 0.], dtype=np.float64))\n\n\ndef test_triinterp_colinear():\n # Tests interpolating inside a triangulation with horizontal colinear\n # points (refer also to the tests :func:`test_trifinder` ).\n #\n # These are not valid triangulations, but we try to deal with the\n # simplest violations (i. e. those handled by default TriFinder).\n #\n # Note that the LinearTriInterpolator and the CubicTriInterpolator with\n # kind='min_E' or 'geom' still pass a linear patch test.\n # We also test interpolation inside a flat triangle, by forcing\n # *tri_index* in a call to :meth:`_interpolate_multikeys`.\n\n # If +ve, triangulation is OK, if -ve triangulation invalid,\n # if zero have colinear points but should pass tests anyway.\n delta = 0.\n\n x0 = np.array([1.5, 0, 1, 2, 3, 1.5, 1.5])\n y0 = np.array([-1, 0, 0, 0, 0, delta, 1])\n\n # We test different affine transformations of the initial figure; to\n # avoid issues related to round-off errors we only use integer\n # coefficients (otherwise the Triangulation might become invalid even with\n # delta == 0).\n transformations = [[1, 0], [0, 1], [1, 1], [1, 2], [-2, -1], [-2, 1]]\n for transformation in transformations:\n x_rot = transformation[0]*x0 + transformation[1]*y0\n y_rot = -transformation[1]*x0 + transformation[0]*y0\n (x, y) = (x_rot, y_rot)\n z = 1.23*x - 4.79*y\n triangles = [[0, 2, 1], [0, 3, 2], [0, 4, 3], [1, 2, 5], [2, 3, 5],\n [3, 4, 5], [1, 5, 6], [4, 6, 5]]\n triang = mtri.Triangulation(x, y, triangles)\n xs = np.linspace(np.min(triang.x), np.max(triang.x), 20)\n ys = np.linspace(np.min(triang.y), np.max(triang.y), 20)\n xs, ys = np.meshgrid(xs, ys)\n xs = xs.ravel()\n ys = ys.ravel()\n mask_out = (triang.get_trifinder()(xs, ys) == -1)\n zs_target = np.ma.array(1.23*xs - 4.79*ys, mask=mask_out)\n\n linear_interp = mtri.LinearTriInterpolator(triang, z)\n cubic_min_E = mtri.CubicTriInterpolator(triang, z)\n cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')\n\n for interp in (linear_interp, cubic_min_E, cubic_geom):\n zs = interp(xs, ys)\n assert_array_almost_equal(zs_target, zs)\n\n # Testing interpolation inside the flat triangle number 4: [2, 3, 5]\n # by imposing *tri_index* in a call to :meth:`_interpolate_multikeys`\n itri = 4\n pt1 = triang.triangles[itri, 0]\n pt2 = triang.triangles[itri, 1]\n xs = np.linspace(triang.x[pt1], triang.x[pt2], 10)\n ys = np.linspace(triang.y[pt1], triang.y[pt2], 10)\n zs_target = 1.23*xs - 4.79*ys\n for interp in (linear_interp, cubic_min_E, cubic_geom):\n zs, = interp._interpolate_multikeys(\n xs, ys, tri_index=itri*np.ones(10, dtype=np.int32))\n assert_array_almost_equal(zs_target, zs)\n\n\ndef test_triinterp_transformations():\n # 1) Testing that the interpolation scheme is invariant by rotation of the\n # whole figure.\n # Note: This test is non-trivial for a CubicTriInterpolator with\n # kind='min_E'. It does fail for a non-isotropic stiffness matrix E of\n # :class:`_ReducedHCT_Element` (tested with E=np.diag([1., 1., 1.])), and\n # provides a good test for :meth:`get_Kff_and_Ff`of the same class.\n #\n # 2) Also testing that the interpolation scheme is invariant by expansion\n # of the whole figure along one axis.\n n_angles = 20\n n_radii = 10\n min_radius = 0.15\n\n def z(x, y):\n r1 = np.hypot(0.5 - x, 0.5 - y)\n theta1 = np.arctan2(0.5 - x, 0.5 - y)\n r2 = np.hypot(-x - 0.2, -y - 0.2)\n theta2 = np.arctan2(-x - 0.2, -y - 0.2)\n z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) +\n (np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) +\n 0.7*(x**2 + y**2))\n return (np.max(z)-z)/(np.max(z)-np.min(z))\n\n # First create the x and y coordinates of the points.\n radii = np.linspace(min_radius, 0.95, n_radii)\n angles = np.linspace(0 + n_angles, 2*np.pi + n_angles,\n n_angles, endpoint=False)\n angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)\n angles[:, 1::2] += np.pi/n_angles\n x0 = (radii*np.cos(angles)).flatten()\n y0 = (radii*np.sin(angles)).flatten()\n triang0 = mtri.Triangulation(x0, y0) # Delaunay triangulation\n z0 = z(x0, y0)\n\n # Then create the test points\n xs0 = np.linspace(-1., 1., 23)\n ys0 = np.linspace(-1., 1., 23)\n xs0, ys0 = np.meshgrid(xs0, ys0)\n xs0 = xs0.ravel()\n ys0 = ys0.ravel()\n\n interp_z0 = {}\n for i_angle in range(2):\n # Rotating everything\n theta = 2*np.pi / n_angles * i_angle\n x = np.cos(theta)*x0 + np.sin(theta)*y0\n y = -np.sin(theta)*x0 + np.cos(theta)*y0\n xs = np.cos(theta)*xs0 + np.sin(theta)*ys0\n ys = -np.sin(theta)*xs0 + np.cos(theta)*ys0\n triang = mtri.Triangulation(x, y, triang0.triangles)\n linear_interp = mtri.LinearTriInterpolator(triang, z0)\n cubic_min_E = mtri.CubicTriInterpolator(triang, z0)\n cubic_geom = mtri.CubicTriInterpolator(triang, z0, kind='geom')\n dic_interp = {'lin': linear_interp,\n 'min_E': cubic_min_E,\n 'geom': cubic_geom}\n # Testing that the interpolation is invariant by rotation...\n for interp_key in ['lin', 'min_E', 'geom']:\n interp = dic_interp[interp_key]\n if i_angle == 0:\n interp_z0[interp_key] = interp(xs0, ys0) # storage\n else:\n interpz = interp(xs, ys)\n matest.assert_array_almost_equal(interpz,\n interp_z0[interp_key])\n\n scale_factor = 987654.3210\n for scaled_axis in ('x', 'y'):\n # Scaling everything (expansion along scaled_axis)\n if scaled_axis == 'x':\n x = scale_factor * x0\n y = y0\n xs = scale_factor * xs0\n ys = ys0\n else:\n x = x0\n y = scale_factor * y0\n xs = xs0\n ys = scale_factor * ys0\n triang = mtri.Triangulation(x, y, triang0.triangles)\n linear_interp = mtri.LinearTriInterpolator(triang, z0)\n cubic_min_E = mtri.CubicTriInterpolator(triang, z0)\n cubic_geom = mtri.CubicTriInterpolator(triang, z0, kind='geom')\n dic_interp = {'lin': linear_interp,\n 'min_E': cubic_min_E,\n 'geom': cubic_geom}\n # Test that the interpolation is invariant by expansion along 1 axis...\n for interp_key in ['lin', 'min_E', 'geom']:\n interpz = dic_interp[interp_key](xs, ys)\n matest.assert_array_almost_equal(interpz, interp_z0[interp_key])\n\n\n@image_comparison(['tri_smooth_contouring.png'], remove_text=True, tol=0.072)\ndef test_tri_smooth_contouring():\n # Image comparison based on example tricontour_smooth_user.\n n_angles = 20\n n_radii = 10\n min_radius = 0.15\n\n def z(x, y):\n r1 = np.hypot(0.5 - x, 0.5 - y)\n theta1 = np.arctan2(0.5 - x, 0.5 - y)\n r2 = np.hypot(-x - 0.2, -y - 0.2)\n theta2 = np.arctan2(-x - 0.2, -y - 0.2)\n z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) +\n (np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) +\n 0.7*(x**2 + y**2))\n return (np.max(z)-z)/(np.max(z)-np.min(z))\n\n # First create the x and y coordinates of the points.\n radii = np.linspace(min_radius, 0.95, n_radii)\n angles = np.linspace(0 + n_angles, 2*np.pi + n_angles,\n n_angles, endpoint=False)\n angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)\n angles[:, 1::2] += np.pi/n_angles\n x0 = (radii*np.cos(angles)).flatten()\n y0 = (radii*np.sin(angles)).flatten()\n triang0 = mtri.Triangulation(x0, y0) # Delaunay triangulation\n z0 = z(x0, y0)\n triang0.set_mask(np.hypot(x0[triang0.triangles].mean(axis=1),\n y0[triang0.triangles].mean(axis=1))\n < min_radius)\n\n # Then the plot\n refiner = mtri.UniformTriRefiner(triang0)\n tri_refi, z_test_refi = refiner.refine_field(z0, subdiv=4)\n levels = np.arange(0., 1., 0.025)\n plt.triplot(triang0, lw=0.5, color='0.5')\n plt.tricontour(tri_refi, z_test_refi, levels=levels, colors="black")\n\n\n@image_comparison(['tri_smooth_gradient.png'], remove_text=True, tol=0.092)\ndef test_tri_smooth_gradient():\n # Image comparison based on example trigradient_demo.\n\n def dipole_potential(x, y):\n """An electric dipole potential V."""\n r_sq = x**2 + y**2\n theta = np.arctan2(y, x)\n z = np.cos(theta)/r_sq\n return (np.max(z)-z) / (np.max(z)-np.min(z))\n\n # Creating a Triangulation\n n_angles = 30\n n_radii = 10\n min_radius = 0.2\n radii = np.linspace(min_radius, 0.95, n_radii)\n angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)\n angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)\n angles[:, 1::2] += np.pi/n_angles\n x = (radii*np.cos(angles)).flatten()\n y = (radii*np.sin(angles)).flatten()\n V = dipole_potential(x, y)\n triang = mtri.Triangulation(x, y)\n triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),\n y[triang.triangles].mean(axis=1))\n < min_radius)\n\n # Refine data - interpolates the electrical potential V\n refiner = mtri.UniformTriRefiner(triang)\n tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)\n\n # Computes the electrical field (Ex, Ey) as gradient of -V\n tci = mtri.CubicTriInterpolator(triang, -V)\n Ex, Ey = tci.gradient(triang.x, triang.y)\n E_norm = np.hypot(Ex, Ey)\n\n # Plot the triangulation, the potential iso-contours and the vector field\n plt.figure()\n plt.gca().set_aspect('equal')\n plt.triplot(triang, color='0.8')\n\n levels = np.arange(0., 1., 0.01)\n cmap = mpl.colormaps['hot']\n plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,\n linewidths=[2.0, 1.0, 1.0, 1.0])\n # Plots direction of the electrical vector field\n plt.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm,\n units='xy', scale=10., zorder=3, color='blue',\n width=0.007, headwidth=3., headlength=4.)\n # We are leaving ax.use_sticky_margins as True, so the\n # view limits are the contour data limits.\n\n\ndef test_tritools():\n # Tests TriAnalyzer.scale_factors on masked triangulation\n # Tests circle_ratios on equilateral and right-angled triangle.\n x = np.array([0., 1., 0.5, 0., 2.])\n y = np.array([0., 0., 0.5*np.sqrt(3.), -1., 1.])\n triangles = np.array([[0, 1, 2], [0, 1, 3], [1, 2, 4]], dtype=np.int32)\n mask = np.array([False, False, True], dtype=bool)\n triang = mtri.Triangulation(x, y, triangles, mask=mask)\n analyser = mtri.TriAnalyzer(triang)\n assert_array_almost_equal(analyser.scale_factors, [1, 1/(1+3**.5/2)])\n assert_array_almost_equal(\n analyser.circle_ratios(rescale=False),\n np.ma.masked_array([0.5, 1./(1.+np.sqrt(2.)), np.nan], mask))\n\n # Tests circle ratio of a flat triangle\n x = np.array([0., 1., 2.])\n y = np.array([1., 1.+3., 1.+6.])\n triangles = np.array([[0, 1, 2]], dtype=np.int32)\n triang = mtri.Triangulation(x, y, triangles)\n analyser = mtri.TriAnalyzer(triang)\n assert_array_almost_equal(analyser.circle_ratios(), np.array([0.]))\n\n # Tests TriAnalyzer.get_flat_tri_mask\n # Creates a triangulation of [-1, 1] x [-1, 1] with contiguous groups of\n # 'flat' triangles at the 4 corners and at the center. Checks that only\n # those at the borders are eliminated by TriAnalyzer.get_flat_tri_mask\n n = 9\n\n def power(x, a):\n return np.abs(x)**a*np.sign(x)\n\n x = np.linspace(-1., 1., n+1)\n x, y = np.meshgrid(power(x, 2.), power(x, 0.25))\n x = x.ravel()\n y = y.ravel()\n\n triang = mtri.Triangulation(x, y, triangles=meshgrid_triangles(n+1))\n analyser = mtri.TriAnalyzer(triang)\n mask_flat = analyser.get_flat_tri_mask(0.2)\n verif_mask = np.zeros(162, dtype=bool)\n corners_index = [0, 1, 2, 3, 14, 15, 16, 17, 18, 19, 34, 35, 126, 127,\n 142, 143, 144, 145, 146, 147, 158, 159, 160, 161]\n verif_mask[corners_index] = True\n assert_array_equal(mask_flat, verif_mask)\n\n # Now including a hole (masked triangle) at the center. The center also\n # shall be eliminated by get_flat_tri_mask.\n mask = np.zeros(162, dtype=bool)\n mask[80] = True\n triang.set_mask(mask)\n mask_flat = analyser.get_flat_tri_mask(0.2)\n center_index = [44, 45, 62, 63, 78, 79, 80, 81, 82, 83, 98, 99, 116, 117]\n verif_mask[center_index] = True\n assert_array_equal(mask_flat, verif_mask)\n\n\ndef test_trirefine():\n # Testing subdiv=2 refinement\n n = 3\n subdiv = 2\n x = np.linspace(-1., 1., n+1)\n x, y = np.meshgrid(x, x)\n x = x.ravel()\n y = y.ravel()\n mask = np.zeros(2*n**2, dtype=bool)\n mask[n**2:] = True\n triang = mtri.Triangulation(x, y, triangles=meshgrid_triangles(n+1),\n mask=mask)\n refiner = mtri.UniformTriRefiner(triang)\n refi_triang = refiner.refine_triangulation(subdiv=subdiv)\n x_refi = refi_triang.x\n y_refi = refi_triang.y\n\n n_refi = n * subdiv**2\n x_verif = np.linspace(-1., 1., n_refi+1)\n x_verif, y_verif = np.meshgrid(x_verif, x_verif)\n x_verif = x_verif.ravel()\n y_verif = y_verif.ravel()\n ind1d = np.isin(np.around(x_verif*(2.5+y_verif), 8),\n np.around(x_refi*(2.5+y_refi), 8))\n assert_array_equal(ind1d, True)\n\n # Testing the mask of the refined triangulation\n refi_mask = refi_triang.mask\n refi_tri_barycenter_x = np.sum(refi_triang.x[refi_triang.triangles],\n axis=1) / 3.\n refi_tri_barycenter_y = np.sum(refi_triang.y[refi_triang.triangles],\n axis=1) / 3.\n tri_finder = triang.get_trifinder()\n refi_tri_indices = tri_finder(refi_tri_barycenter_x,\n refi_tri_barycenter_y)\n refi_tri_mask = triang.mask[refi_tri_indices]\n assert_array_equal(refi_mask, refi_tri_mask)\n\n # Testing that the numbering of triangles does not change the\n # interpolation result.\n x = np.asarray([0.0, 1.0, 0.0, 1.0])\n y = np.asarray([0.0, 0.0, 1.0, 1.0])\n triang = [mtri.Triangulation(x, y, [[0, 1, 3], [3, 2, 0]]),\n mtri.Triangulation(x, y, [[0, 1, 3], [2, 0, 3]])]\n z = np.hypot(x - 0.3, y - 0.4)\n # Refining the 2 triangulations and reordering the points\n xyz_data = []\n for i in range(2):\n refiner = mtri.UniformTriRefiner(triang[i])\n refined_triang, refined_z = refiner.refine_field(z, subdiv=1)\n xyz = np.dstack((refined_triang.x, refined_triang.y, refined_z))[0]\n xyz = xyz[np.lexsort((xyz[:, 1], xyz[:, 0]))]\n xyz_data += [xyz]\n assert_array_almost_equal(xyz_data[0], xyz_data[1])\n\n\n@pytest.mark.parametrize('interpolator',\n [mtri.LinearTriInterpolator,\n mtri.CubicTriInterpolator],\n ids=['linear', 'cubic'])\ndef test_trirefine_masked(interpolator):\n # Repeated points means we will have fewer triangles than points, and thus\n # get masking.\n x, y = np.mgrid[:2, :2]\n x = np.repeat(x.flatten(), 2)\n y = np.repeat(y.flatten(), 2)\n\n z = np.zeros_like(x)\n tri = mtri.Triangulation(x, y)\n refiner = mtri.UniformTriRefiner(tri)\n interp = interpolator(tri, z)\n refiner.refine_field(z, triinterpolator=interp, subdiv=2)\n\n\ndef meshgrid_triangles(n):\n """\n Return (2*(N-1)**2, 3) array of triangles to mesh (N, N)-point np.meshgrid.\n """\n tri = []\n for i in range(n-1):\n for j in range(n-1):\n a = i + j*n\n b = (i+1) + j*n\n c = i + (j+1)*n\n d = (i+1) + (j+1)*n\n tri += [[a, b, d], [a, d, c]]\n return np.array(tri, dtype=np.int32)\n\n\ndef test_triplot_return():\n # Check that triplot returns the artists it adds\n ax = plt.figure().add_subplot()\n triang = mtri.Triangulation(\n [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0],\n triangles=[[0, 1, 3], [3, 2, 0]])\n assert ax.triplot(triang, "b-") is not None, \\n 'triplot should return the artist it adds'\n\n\ndef test_trirefiner_fortran_contiguous_triangles():\n # github issue 4180. Test requires two arrays of triangles that are\n # identical except that one is C-contiguous and one is fortran-contiguous.\n triangles1 = np.array([[2, 0, 3], [2, 1, 0]])\n assert not np.isfortran(triangles1)\n\n triangles2 = np.array(triangles1, copy=True, order='F')\n assert np.isfortran(triangles2)\n\n x = np.array([0.39, 0.59, 0.43, 0.32])\n y = np.array([33.99, 34.01, 34.19, 34.18])\n triang1 = mtri.Triangulation(x, y, triangles1)\n triang2 = mtri.Triangulation(x, y, triangles2)\n\n refiner1 = mtri.UniformTriRefiner(triang1)\n refiner2 = mtri.UniformTriRefiner(triang2)\n\n fine_triang1 = refiner1.refine_triangulation(subdiv=1)\n fine_triang2 = refiner2.refine_triangulation(subdiv=1)\n\n assert_array_equal(fine_triang1.triangles, fine_triang2.triangles)\n\n\ndef test_qhull_triangle_orientation():\n # github issue 4437.\n xi = np.linspace(-2, 2, 100)\n x, y = map(np.ravel, np.meshgrid(xi, xi))\n w = (x > y - 1) & (x < -1.95) & (y > -1.2)\n x, y = x[w], y[w]\n theta = np.radians(25)\n x1 = x*np.cos(theta) - y*np.sin(theta)\n y1 = x*np.sin(theta) + y*np.cos(theta)\n\n # Calculate Delaunay triangulation using Qhull.\n triang = mtri.Triangulation(x1, y1)\n\n # Neighbors returned by Qhull.\n qhull_neighbors = triang.neighbors\n\n # Obtain neighbors using own C++ calculation.\n triang._neighbors = None\n own_neighbors = triang.neighbors\n\n assert_array_equal(qhull_neighbors, own_neighbors)\n\n\ndef test_trianalyzer_mismatched_indices():\n # github issue 4999.\n x = np.array([0., 1., 0.5, 0., 2.])\n y = np.array([0., 0., 0.5*np.sqrt(3.), -1., 1.])\n triangles = np.array([[0, 1, 2], [0, 1, 3], [1, 2, 4]], dtype=np.int32)\n mask = np.array([False, False, True], dtype=bool)\n triang = mtri.Triangulation(x, y, triangles, mask=mask)\n analyser = mtri.TriAnalyzer(triang)\n # numpy >= 1.10 raises a VisibleDeprecationWarning in the following line\n # prior to the fix.\n analyser._get_compressed_triangulation()\n\n\ndef test_tricontourf_decreasing_levels():\n # github issue 5477.\n x = [0.0, 1.0, 1.0]\n y = [0.0, 0.0, 1.0]\n z = [0.2, 0.4, 0.6]\n plt.figure()\n with pytest.raises(ValueError):\n plt.tricontourf(x, y, z, [1.0, 0.0])\n\n\ndef test_internal_cpp_api() -> None:\n # Following github issue 8197.\n from matplotlib import _tri # noqa: F401, ensure lazy-loaded module *is* loaded.\n\n # C++ Triangulation.\n with pytest.raises(\n TypeError,\n match=r'__init__\(\): incompatible constructor arguments.'):\n mpl._tri.Triangulation() # type: ignore[call-arg]\n\n with pytest.raises(\n ValueError, match=r'x and y must be 1D arrays of the same length'):\n mpl._tri.Triangulation(np.array([]), np.array([1]), np.array([[]]), (), (), (),\n False)\n\n x = np.array([0, 1, 1], dtype=np.float64)\n y = np.array([0, 0, 1], dtype=np.float64)\n with pytest.raises(\n ValueError,\n match=r'triangles must be a 2D array of shape \(\?,3\)'):\n mpl._tri.Triangulation(x, y, np.array([[0, 1]]), (), (), (), False)\n\n tris = np.array([[0, 1, 2]], dtype=np.int_)\n with pytest.raises(\n ValueError,\n match=r'mask must be a 1D array with the same length as the '\n r'triangles array'):\n mpl._tri.Triangulation(x, y, tris, np.array([0, 1]), (), (), False)\n\n with pytest.raises(\n ValueError, match=r'edges must be a 2D array with shape \(\?,2\)'):\n mpl._tri.Triangulation(x, y, tris, (), np.array([[1]]), (), False)\n\n with pytest.raises(\n ValueError,\n match=r'neighbors must be a 2D array with the same shape as the '\n r'triangles array'):\n mpl._tri.Triangulation(x, y, tris, (), (), np.array([[-1]]), False)\n\n triang = mpl._tri.Triangulation(x, y, tris, (), (), (), False)\n\n with pytest.raises(\n ValueError,\n match=r'z must be a 1D array with the same length as the '\n r'triangulation x and y arrays'):\n triang.calculate_plane_coefficients([])\n\n for mask in ([0, 1], None):\n with pytest.raises(\n ValueError,\n match=r'mask must be a 1D array with the same length as the '\n r'triangles array'):\n triang.set_mask(mask) # type: ignore[arg-type]\n\n triang.set_mask(np.array([True]))\n assert_array_equal(triang.get_edges(), np.empty((0, 2)))\n\n triang.set_mask(()) # Equivalent to Python Triangulation mask=None\n assert_array_equal(triang.get_edges(), [[1, 0], [2, 0], [2, 1]])\n\n # C++ TriContourGenerator.\n with pytest.raises(\n TypeError,\n match=r'__init__\(\): incompatible constructor arguments.'):\n mpl._tri.TriContourGenerator() # type: ignore[call-arg]\n\n with pytest.raises(\n ValueError,\n match=r'z must be a 1D array with the same length as the x and y arrays'):\n mpl._tri.TriContourGenerator(triang, np.array([1]))\n\n z = np.array([0, 1, 2])\n tcg = mpl._tri.TriContourGenerator(triang, z)\n\n with pytest.raises(\n ValueError, match=r'filled contour levels must be increasing'):\n tcg.create_filled_contour(1, 0)\n\n # C++ TrapezoidMapTriFinder.\n with pytest.raises(\n TypeError,\n match=r'__init__\(\): incompatible constructor arguments.'):\n mpl._tri.TrapezoidMapTriFinder() # type: ignore[call-arg]\n\n trifinder = mpl._tri.TrapezoidMapTriFinder(triang)\n\n with pytest.raises(\n ValueError, match=r'x and y must be array-like with same shape'):\n trifinder.find_many(np.array([0]), np.array([0, 1]))\n\n\ndef test_qhull_large_offset():\n # github issue 8682.\n x = np.asarray([0, 1, 0, 1, 0.5])\n y = np.asarray([0, 0, 1, 1, 0.5])\n\n offset = 1e10\n triang = mtri.Triangulation(x, y)\n triang_offset = mtri.Triangulation(x + offset, y + offset)\n assert len(triang.triangles) == len(triang_offset.triangles)\n\n\ndef test_tricontour_non_finite_z():\n # github issue 10167.\n x = [0, 1, 0, 1]\n y = [0, 0, 1, 1]\n triang = mtri.Triangulation(x, y)\n plt.figure()\n\n with pytest.raises(ValueError, match='z array must not contain non-finite '\n 'values within the triangulation'):\n plt.tricontourf(triang, [0, 1, 2, np.inf])\n\n with pytest.raises(ValueError, match='z array must not contain non-finite '\n 'values within the triangulation'):\n plt.tricontourf(triang, [0, 1, 2, -np.inf])\n\n with pytest.raises(ValueError, match='z array must not contain non-finite '\n 'values within the triangulation'):\n plt.tricontourf(triang, [0, 1, 2, np.nan])\n\n with pytest.raises(ValueError, match='z must not contain masked points '\n 'within the triangulation'):\n plt.tricontourf(triang, np.ma.array([0, 1, 2, 3], mask=[1, 0, 0, 0]))\n\n\ndef test_tricontourset_reuse():\n # If TriContourSet returned from one tricontour(f) call is passed as first\n # argument to another the underlying C++ contour generator will be reused.\n x = [0.0, 0.5, 1.0]\n y = [0.0, 1.0, 0.0]\n z = [1.0, 2.0, 3.0]\n fig, ax = plt.subplots()\n tcs1 = ax.tricontourf(x, y, z)\n tcs2 = ax.tricontour(x, y, z)\n assert tcs2._contour_generator != tcs1._contour_generator\n tcs3 = ax.tricontour(tcs1, z)\n assert tcs3._contour_generator == tcs1._contour_generator\n\n\n@check_figures_equal(extensions=['png'])\ndef test_triplot_with_ls(fig_test, fig_ref):\n x = [0, 2, 1]\n y = [0, 0, 1]\n data = [[0, 1, 2]]\n fig_test.subplots().triplot(x, y, data, ls='--')\n fig_ref.subplots().triplot(x, y, data, linestyle='--')\n\n\ndef test_triplot_label():\n x = [0, 2, 1]\n y = [0, 0, 1]\n data = [[0, 1, 2]]\n fig, ax = plt.subplots()\n lines, markers = ax.triplot(x, y, data, label='label')\n handles, labels = ax.get_legend_handles_labels()\n assert labels == ['label']\n assert len(handles) == 1\n assert handles[0] is lines\n\n\ndef test_tricontour_path():\n x = [0, 4, 4, 0, 2]\n y = [0, 0, 4, 4, 2]\n triang = mtri.Triangulation(x, y)\n _, ax = plt.subplots()\n\n # Line strip from boundary to boundary\n cs = ax.tricontour(triang, [1, 0, 0, 0, 0], levels=[0.5])\n paths = cs.get_paths()\n assert len(paths) == 1\n expected_vertices = [[2, 0], [1, 1], [0, 2]]\n assert_array_almost_equal(paths[0].vertices, expected_vertices)\n assert_array_equal(paths[0].codes, [1, 2, 2])\n assert_array_almost_equal(\n paths[0].to_polygons(closed_only=False), [expected_vertices])\n\n # Closed line loop inside domain\n cs = ax.tricontour(triang, [0, 0, 0, 0, 1], levels=[0.5])\n paths = cs.get_paths()\n assert len(paths) == 1\n expected_vertices = [[3, 1], [3, 3], [1, 3], [1, 1], [3, 1]]\n assert_array_almost_equal(paths[0].vertices, expected_vertices)\n assert_array_equal(paths[0].codes, [1, 2, 2, 2, 79])\n assert_array_almost_equal(paths[0].to_polygons(), [expected_vertices])\n\n\ndef test_tricontourf_path():\n x = [0, 4, 4, 0, 2]\n y = [0, 0, 4, 4, 2]\n triang = mtri.Triangulation(x, y)\n _, ax = plt.subplots()\n\n # Polygon inside domain\n cs = ax.tricontourf(triang, [0, 0, 0, 0, 1], levels=[0.5, 1.5])\n paths = cs.get_paths()\n assert len(paths) == 1\n expected_vertices = [[3, 1], [3, 3], [1, 3], [1, 1], [3, 1]]\n assert_array_almost_equal(paths[0].vertices, expected_vertices)\n assert_array_equal(paths[0].codes, [1, 2, 2, 2, 79])\n assert_array_almost_equal(paths[0].to_polygons(), [expected_vertices])\n\n # Polygon following boundary and inside domain\n cs = ax.tricontourf(triang, [1, 0, 0, 0, 0], levels=[0.5, 1.5])\n paths = cs.get_paths()\n assert len(paths) == 1\n expected_vertices = [[2, 0], [1, 1], [0, 2], [0, 0], [2, 0]]\n assert_array_almost_equal(paths[0].vertices, expected_vertices)\n assert_array_equal(paths[0].codes, [1, 2, 2, 2, 79])\n assert_array_almost_equal(paths[0].to_polygons(), [expected_vertices])\n\n # Polygon is outer boundary with hole\n cs = ax.tricontourf(triang, [0, 0, 0, 0, 1], levels=[-0.5, 0.5])\n paths = cs.get_paths()\n assert len(paths) == 1\n expected_vertices = [[0, 0], [4, 0], [4, 4], [0, 4], [0, 0],\n [1, 1], [1, 3], [3, 3], [3, 1], [1, 1]]\n assert_array_almost_equal(paths[0].vertices, expected_vertices)\n assert_array_equal(paths[0].codes, [1, 2, 2, 2, 79, 1, 2, 2, 2, 79])\n assert_array_almost_equal(paths[0].to_polygons(), np.split(expected_vertices, [5]))\n | .venv\Lib\site-packages\matplotlib\tests\test_triangulation.py | test_triangulation.py | Python | 55,289 | 0.75 | 0.08268 | 0.158598 | node-utils | 8 | 2023-08-27T22:51:32.934023 | BSD-3-Clause | true | e2cfd734a904605b83302d033dc8aa18 |
import matplotlib._type1font as t1f\nimport os.path\nimport difflib\nimport pytest\n\n\ndef test_Type1Font():\n filename = os.path.join(os.path.dirname(__file__), 'cmr10.pfb')\n font = t1f.Type1Font(filename)\n slanted = font.transform({'slant': 1})\n condensed = font.transform({'extend': 0.5})\n with open(filename, 'rb') as fd:\n rawdata = fd.read()\n assert font.parts[0] == rawdata[0x0006:0x10c5]\n assert font.parts[1] == rawdata[0x10cb:0x897f]\n assert font.parts[2] == rawdata[0x8985:0x8ba6]\n assert font.decrypted.startswith(b'dup\n/Private 18 dict dup begin')\n assert font.decrypted.endswith(b'mark currentfile closefile\n')\n assert slanted.decrypted.startswith(b'dup\n/Private 18 dict dup begin')\n assert slanted.decrypted.endswith(b'mark currentfile closefile\n')\n assert b'UniqueID 5000793' in font.parts[0]\n assert b'UniqueID 5000793' in font.decrypted\n assert font._pos['UniqueID'] == [(797, 818), (4483, 4504)]\n\n len0 = len(font.parts[0])\n for key in font._pos.keys():\n for pos0, pos1 in font._pos[key]:\n if pos0 < len0:\n data = font.parts[0][pos0:pos1]\n else:\n data = font.decrypted[pos0-len0:pos1-len0]\n assert data.startswith(f'/{key}'.encode('ascii'))\n assert {'FontType', 'FontMatrix', 'PaintType', 'ItalicAngle', 'RD'\n } < set(font._pos.keys())\n\n assert b'UniqueID 5000793' not in slanted.parts[0]\n assert b'UniqueID 5000793' not in slanted.decrypted\n assert 'UniqueID' not in slanted._pos\n assert font.prop['Weight'] == 'Medium'\n assert not font.prop['isFixedPitch']\n assert font.prop['ItalicAngle'] == 0\n assert slanted.prop['ItalicAngle'] == -45\n assert font.prop['Encoding'][5] == 'Pi'\n assert isinstance(font.prop['CharStrings']['Pi'], bytes)\n assert font._abbr['ND'] == 'ND'\n\n differ = difflib.Differ()\n diff = list(differ.compare(\n font.parts[0].decode('latin-1').splitlines(),\n slanted.parts[0].decode('latin-1').splitlines()))\n for line in (\n # Removes UniqueID\n '- /UniqueID 5000793 def',\n # Changes the font name\n '- /FontName /CMR10 def',\n '+ /FontName/CMR10_Slant_1000 def',\n # Alters FontMatrix\n '- /FontMatrix [0.001 0 0 0.001 0 0 ]readonly def',\n '+ /FontMatrix [0.001 0 0.001 0.001 0 0] readonly def',\n # Alters ItalicAngle\n '- /ItalicAngle 0 def',\n '+ /ItalicAngle -45.0 def'):\n assert line in diff, 'diff to slanted font must contain %s' % line\n\n diff = list(differ.compare(\n font.parts[0].decode('latin-1').splitlines(),\n condensed.parts[0].decode('latin-1').splitlines()))\n for line in (\n # Removes UniqueID\n '- /UniqueID 5000793 def',\n # Changes the font name\n '- /FontName /CMR10 def',\n '+ /FontName/CMR10_Extend_500 def',\n # Alters FontMatrix\n '- /FontMatrix [0.001 0 0 0.001 0 0 ]readonly def',\n '+ /FontMatrix [0.0005 0 0 0.001 0 0] readonly def'):\n assert line in diff, 'diff to condensed font must contain %s' % line\n\n\ndef test_Type1Font_2():\n filename = os.path.join(os.path.dirname(__file__),\n 'Courier10PitchBT-Bold.pfb')\n font = t1f.Type1Font(filename)\n assert font.prop['Weight'] == 'Bold'\n assert font.prop['isFixedPitch']\n assert font.prop['Encoding'][65] == 'A' # the font uses StandardEncoding\n (pos0, pos1), = font._pos['Encoding']\n assert font.parts[0][pos0:pos1] == b'/Encoding StandardEncoding'\n assert font._abbr['ND'] == '|-'\n\n\ndef test_tokenize():\n data = (b'1234/abc false -9.81 Foo <<[0 1 2]<0 1ef a\t>>>\n'\n b'(string with(nested\t\\) par)ens\\\\)')\n # 1 2 x 2 xx1\n # 1 and 2 are matching parens, x means escaped character\n n, w, num, kw, d = 'name', 'whitespace', 'number', 'keyword', 'delimiter'\n b, s = 'boolean', 'string'\n correct = [\n (num, 1234), (n, 'abc'), (w, ' '), (b, False), (w, ' '), (num, -9.81),\n (w, ' '), (kw, 'Foo'), (w, ' '), (d, '<<'), (d, '['), (num, 0),\n (w, ' '), (num, 1), (w, ' '), (num, 2), (d, ']'), (s, b'\x01\xef\xa0'),\n (d, '>>'), (w, '\n'), (s, 'string with(nested\t) par)ens\\')\n ]\n correct_no_ws = [x for x in correct if x[0] != w]\n\n def convert(tokens):\n return [(t.kind, t.value()) for t in tokens]\n\n assert convert(t1f._tokenize(data, False)) == correct\n assert convert(t1f._tokenize(data, True)) == correct_no_ws\n\n def bin_after(n):\n tokens = t1f._tokenize(data, True)\n result = []\n for _ in range(n):\n result.append(next(tokens))\n result.append(tokens.send(10))\n return convert(result)\n\n for n in range(1, len(correct_no_ws)):\n result = bin_after(n)\n assert result[:-1] == correct_no_ws[:n]\n assert result[-1][0] == 'binary'\n assert isinstance(result[-1][1], bytes)\n\n\ndef test_tokenize_errors():\n with pytest.raises(ValueError):\n list(t1f._tokenize(b'1234 (this (string) is unterminated\\)', True))\n with pytest.raises(ValueError):\n list(t1f._tokenize(b'/Foo<01234', True))\n with pytest.raises(ValueError):\n list(t1f._tokenize(b'/Foo<01234abcg>/Bar', True))\n\n\ndef test_overprecision():\n # We used to output too many digits in FontMatrix entries and\n # ItalicAngle, which could make Type-1 parsers unhappy.\n filename = os.path.join(os.path.dirname(__file__), 'cmr10.pfb')\n font = t1f.Type1Font(filename)\n slanted = font.transform({'slant': .167})\n lines = slanted.parts[0].decode('ascii').splitlines()\n matrix, = (line[line.index('[')+1:line.index(']')]\n for line in lines if '/FontMatrix' in line)\n angle, = (word\n for line in lines if '/ItalicAngle' in line\n for word in line.split() if word[0] in '-0123456789')\n # the following used to include 0.00016700000000000002\n assert matrix == '0.001 0 0.000167 0.001 0 0'\n # and here we had -9.48090361795083\n assert angle == '-9.4809'\n\n\ndef test_encrypt_decrypt_roundtrip():\n data = b'this is my plaintext \0\1\2\3'\n encrypted = t1f.Type1Font._encrypt(data, 'eexec')\n decrypted = t1f.Type1Font._decrypt(encrypted, 'eexec')\n assert encrypted != decrypted\n assert data == decrypted\n | .venv\Lib\site-packages\matplotlib\tests\test_type1font.py | test_type1font.py | Python | 6,369 | 0.95 | 0.225 | 0.092857 | react-lib | 61 | 2023-07-12T04:54:04.106257 | Apache-2.0 | true | 08259b8392c08a737d12c7ce9f5a0994 |
from datetime import datetime, timezone, timedelta\nimport platform\nfrom unittest.mock import MagicMock\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\nimport matplotlib.patches as mpatches\nimport matplotlib.units as munits\nfrom matplotlib.category import StrCategoryConverter, UnitData\nfrom matplotlib.dates import DateConverter\nimport numpy as np\nimport pytest\n\n\n# Basic class that wraps numpy array and has units\nclass Quantity:\n def __init__(self, data, units):\n self.magnitude = data\n self.units = units\n\n def to(self, new_units):\n factors = {('hours', 'seconds'): 3600, ('minutes', 'hours'): 1 / 60,\n ('minutes', 'seconds'): 60, ('feet', 'miles'): 1 / 5280.,\n ('feet', 'inches'): 12, ('miles', 'inches'): 12 * 5280}\n if self.units != new_units:\n mult = factors[self.units, new_units]\n return Quantity(mult * self.magnitude, new_units)\n else:\n return Quantity(self.magnitude, self.units)\n\n def __copy__(self):\n return Quantity(self.magnitude, self.units)\n\n def __getattr__(self, attr):\n return getattr(self.magnitude, attr)\n\n def __getitem__(self, item):\n if np.iterable(self.magnitude):\n return Quantity(self.magnitude[item], self.units)\n else:\n return Quantity(self.magnitude, self.units)\n\n def __array__(self):\n return np.asarray(self.magnitude)\n\n\n@pytest.fixture\ndef quantity_converter():\n # Create an instance of the conversion interface and\n # mock so we can check methods called\n qc = munits.ConversionInterface()\n\n def convert(value, unit, axis):\n if hasattr(value, 'units'):\n return value.to(unit).magnitude\n elif np.iterable(value):\n try:\n return [v.to(unit).magnitude for v in value]\n except AttributeError:\n return [Quantity(v, axis.get_units()).to(unit).magnitude\n for v in value]\n else:\n return Quantity(value, axis.get_units()).to(unit).magnitude\n\n def default_units(value, axis):\n if hasattr(value, 'units'):\n return value.units\n elif np.iterable(value):\n for v in value:\n if hasattr(v, 'units'):\n return v.units\n return None\n\n qc.convert = MagicMock(side_effect=convert)\n qc.axisinfo = MagicMock(side_effect=lambda u, a:\n munits.AxisInfo(label=u, default_limits=(0, 100)))\n qc.default_units = MagicMock(side_effect=default_units)\n return qc\n\n\n# Tests that the conversion machinery works properly for classes that\n# work as a facade over numpy arrays (like pint)\n@image_comparison(['plot_pint.png'], style='mpl20',\n tol=0 if platform.machine() == 'x86_64' else 0.03)\ndef test_numpy_facade(quantity_converter):\n # use former defaults to match existing baseline image\n plt.rcParams['axes.formatter.limits'] = -7, 7\n\n # Register the class\n munits.registry[Quantity] = quantity_converter\n\n # Simple test\n y = Quantity(np.linspace(0, 30), 'miles')\n x = Quantity(np.linspace(0, 5), 'hours')\n\n fig, ax = plt.subplots()\n fig.subplots_adjust(left=0.15) # Make space for label\n ax.plot(x, y, 'tab:blue')\n ax.axhline(Quantity(26400, 'feet'), color='tab:red')\n ax.axvline(Quantity(120, 'minutes'), color='tab:green')\n ax.yaxis.set_units('inches')\n ax.xaxis.set_units('seconds')\n\n assert quantity_converter.convert.called\n assert quantity_converter.axisinfo.called\n assert quantity_converter.default_units.called\n\n\n# Tests gh-8908\n@image_comparison(['plot_masked_units.png'], remove_text=True, style='mpl20',\n tol=0 if platform.machine() == 'x86_64' else 0.02)\ndef test_plot_masked_units():\n data = np.linspace(-5, 5)\n data_masked = np.ma.array(data, mask=(data > -2) & (data < 2))\n data_masked_units = Quantity(data_masked, 'meters')\n\n fig, ax = plt.subplots()\n ax.plot(data_masked_units)\n\n\ndef test_empty_set_limits_with_units(quantity_converter):\n # Register the class\n munits.registry[Quantity] = quantity_converter\n\n fig, ax = plt.subplots()\n ax.set_xlim(Quantity(-1, 'meters'), Quantity(6, 'meters'))\n ax.set_ylim(Quantity(-1, 'hours'), Quantity(16, 'hours'))\n\n\n@image_comparison(['jpl_bar_units.png'],\n savefig_kwarg={'dpi': 120}, style='mpl20')\ndef test_jpl_bar_units():\n import matplotlib.testing.jpl_units as units\n units.register()\n\n day = units.Duration("ET", 24.0 * 60.0 * 60.0)\n x = [0 * units.km, 1 * units.km, 2 * units.km]\n w = [1 * day, 2 * day, 3 * day]\n b = units.Epoch("ET", dt=datetime(2009, 4, 26))\n fig, ax = plt.subplots()\n ax.bar(x, w, bottom=b)\n ax.set_ylim([b - 1 * day, b + w[-1] + (1.001) * day])\n\n\n@image_comparison(['jpl_barh_units.png'],\n savefig_kwarg={'dpi': 120}, style='mpl20')\ndef test_jpl_barh_units():\n import matplotlib.testing.jpl_units as units\n units.register()\n\n day = units.Duration("ET", 24.0 * 60.0 * 60.0)\n x = [0 * units.km, 1 * units.km, 2 * units.km]\n w = [1 * day, 2 * day, 3 * day]\n b = units.Epoch("ET", dt=datetime(2009, 4, 26))\n\n fig, ax = plt.subplots()\n ax.barh(x, w, left=b)\n ax.set_xlim([b - 1 * day, b + w[-1] + (1.001) * day])\n\n\ndef test_jpl_datetime_units_consistent():\n import matplotlib.testing.jpl_units as units\n units.register()\n\n dt = datetime(2009, 4, 26)\n jpl = units.Epoch("ET", dt=dt)\n dt_conv = munits.registry.get_converter(dt).convert(dt, None, None)\n jpl_conv = munits.registry.get_converter(jpl).convert(jpl, None, None)\n assert dt_conv == jpl_conv\n\n\ndef test_empty_arrays():\n # Check that plotting an empty array with a dtype works\n plt.scatter(np.array([], dtype='datetime64[ns]'), np.array([]))\n\n\ndef test_scatter_element0_masked():\n times = np.arange('2005-02', '2005-03', dtype='datetime64[D]')\n y = np.arange(len(times), dtype=float)\n y[0] = np.nan\n fig, ax = plt.subplots()\n ax.scatter(times, y)\n fig.canvas.draw()\n\n\ndef test_errorbar_mixed_units():\n x = np.arange(10)\n y = [datetime(2020, 5, i * 2 + 1) for i in x]\n fig, ax = plt.subplots()\n ax.errorbar(x, y, timedelta(days=0.5))\n fig.canvas.draw()\n\n\n@check_figures_equal(extensions=["png"])\ndef test_subclass(fig_test, fig_ref):\n class subdate(datetime):\n pass\n\n fig_test.subplots().plot(subdate(2000, 1, 1), 0, "o")\n fig_ref.subplots().plot(datetime(2000, 1, 1), 0, "o")\n\n\ndef test_shared_axis_quantity(quantity_converter):\n munits.registry[Quantity] = quantity_converter\n x = Quantity(np.linspace(0, 1, 10), "hours")\n y1 = Quantity(np.linspace(1, 2, 10), "feet")\n y2 = Quantity(np.linspace(3, 4, 10), "feet")\n fig, (ax1, ax2) = plt.subplots(2, 1, sharex='all', sharey='all')\n ax1.plot(x, y1)\n ax2.plot(x, y2)\n assert ax1.xaxis.get_units() == ax2.xaxis.get_units() == "hours"\n assert ax2.yaxis.get_units() == ax2.yaxis.get_units() == "feet"\n ax1.xaxis.set_units("seconds")\n ax2.yaxis.set_units("inches")\n assert ax1.xaxis.get_units() == ax2.xaxis.get_units() == "seconds"\n assert ax1.yaxis.get_units() == ax2.yaxis.get_units() == "inches"\n\n\ndef test_shared_axis_datetime():\n # datetime uses dates.DateConverter\n y1 = [datetime(2020, i, 1, tzinfo=timezone.utc) for i in range(1, 13)]\n y2 = [datetime(2021, i, 1, tzinfo=timezone.utc) for i in range(1, 13)]\n fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n ax1.plot(y1)\n ax2.plot(y2)\n ax1.yaxis.set_units(timezone(timedelta(hours=5)))\n assert ax2.yaxis.units == timezone(timedelta(hours=5))\n\n\ndef test_shared_axis_categorical():\n # str uses category.StrCategoryConverter\n d1 = {"a": 1, "b": 2}\n d2 = {"a": 3, "b": 4}\n fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)\n ax1.plot(d1.keys(), d1.values())\n ax2.plot(d2.keys(), d2.values())\n ax1.xaxis.set_units(UnitData(["c", "d"]))\n assert "c" in ax2.xaxis.get_units()._mapping.keys()\n\n\ndef test_explicit_converter():\n d1 = {"a": 1, "b": 2}\n str_cat_converter = StrCategoryConverter()\n str_cat_converter_2 = StrCategoryConverter()\n date_converter = DateConverter()\n\n # Explicit is set\n fig1, ax1 = plt.subplots()\n ax1.xaxis.set_converter(str_cat_converter)\n assert ax1.xaxis.get_converter() == str_cat_converter\n # Explicit not overridden by implicit\n ax1.plot(d1.keys(), d1.values())\n assert ax1.xaxis.get_converter() == str_cat_converter\n # No error when called twice with equivalent input\n ax1.xaxis.set_converter(str_cat_converter)\n # Error when explicit called twice\n with pytest.raises(RuntimeError):\n ax1.xaxis.set_converter(str_cat_converter_2)\n\n fig2, ax2 = plt.subplots()\n ax2.plot(d1.keys(), d1.values())\n\n # No error when equivalent type is used\n ax2.xaxis.set_converter(str_cat_converter)\n\n fig3, ax3 = plt.subplots()\n ax3.plot(d1.keys(), d1.values())\n\n # Warn when implicit overridden\n with pytest.warns():\n ax3.xaxis.set_converter(date_converter)\n\n\ndef test_empty_default_limits(quantity_converter):\n munits.registry[Quantity] = quantity_converter\n fig, ax1 = plt.subplots()\n ax1.xaxis.update_units(Quantity([10], "miles"))\n fig.draw_without_rendering()\n assert ax1.get_xlim() == (0, 100)\n ax1.yaxis.update_units(Quantity([10], "miles"))\n fig.draw_without_rendering()\n assert ax1.get_ylim() == (0, 100)\n\n fig, ax = plt.subplots()\n ax.axhline(30)\n ax.plot(Quantity(np.arange(0, 3), "miles"),\n Quantity(np.arange(0, 6, 2), "feet"))\n fig.draw_without_rendering()\n assert ax.get_xlim() == (0, 2)\n assert ax.get_ylim() == (0, 30)\n\n fig, ax = plt.subplots()\n ax.axvline(30)\n ax.plot(Quantity(np.arange(0, 3), "miles"),\n Quantity(np.arange(0, 6, 2), "feet"))\n fig.draw_without_rendering()\n assert ax.get_xlim() == (0, 30)\n assert ax.get_ylim() == (0, 4)\n\n fig, ax = plt.subplots()\n ax.xaxis.update_units(Quantity([10], "miles"))\n ax.axhline(30)\n fig.draw_without_rendering()\n assert ax.get_xlim() == (0, 100)\n assert ax.get_ylim() == (28.5, 31.5)\n\n fig, ax = plt.subplots()\n ax.yaxis.update_units(Quantity([10], "miles"))\n ax.axvline(30)\n fig.draw_without_rendering()\n assert ax.get_ylim() == (0, 100)\n assert ax.get_xlim() == (28.5, 31.5)\n\n\n# test array-like objects...\nclass Kernel:\n def __init__(self, array):\n self._array = np.asanyarray(array)\n\n def __array__(self, dtype=None, copy=None):\n if dtype is not None and dtype != self._array.dtype:\n if copy is not None and not copy:\n raise ValueError(\n f"Converting array from {self._array.dtype} to "\n f"{dtype} requires a copy"\n )\n\n arr = np.asarray(self._array, dtype=dtype)\n return (arr if not copy else np.copy(arr))\n\n @property\n def shape(self):\n return self._array.shape\n\n\ndef test_plot_kernel():\n # just a smoketest that fail\n kernel = Kernel([1, 2, 3, 4, 5])\n plt.plot(kernel)\n\n\ndef test_connection_patch_units(pd):\n # tests that this doesn't raise an error\n fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(10, 5))\n x = pd.Timestamp('2017-01-01T12')\n ax1.axvline(x)\n y = "test test"\n ax2.axhline(y)\n arr = mpatches.ConnectionPatch((x, 0), (0, y),\n coordsA='data', coordsB='data',\n axesA=ax1, axesB=ax2)\n fig.add_artist(arr)\n fig.draw_without_rendering()\n | .venv\Lib\site-packages\matplotlib\tests\test_units.py | test_units.py | Python | 11,675 | 0.95 | 0.152975 | 0.078292 | react-lib | 18 | 2024-01-03T23:54:45.015822 | BSD-3-Clause | true | 3b0bf206b628f39e701cdf4c30a2d704 |
from tempfile import TemporaryFile\n\nimport numpy as np\nfrom packaging.version import parse as parse_version\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib import dviread\nfrom matplotlib.testing import _has_tex_package\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\nfrom matplotlib.testing._markers import needs_usetex\nimport matplotlib.pyplot as plt\n\n\npytestmark = needs_usetex\n\n\n@image_comparison(\n baseline_images=['test_usetex'],\n extensions=['pdf', 'png'],\n style="mpl20")\ndef test_usetex():\n mpl.rcParams['text.usetex'] = True\n fig, ax = plt.subplots()\n kwargs = {"verticalalignment": "baseline", "size": 24,\n "bbox": dict(pad=0, edgecolor="k", facecolor="none")}\n ax.text(0.2, 0.7,\n # the \LaTeX macro exercises character sizing and placement,\n # \left[ ... \right\} draw some variable-height characters,\n # \sqrt and \frac draw horizontal rules, \mathrm changes the font\n r'\LaTeX\ $\left[\int\limits_e^{2e}'\n r'\sqrt\frac{\log^3 x}{x}\,\mathrm{d}x \right\}$',\n **kwargs)\n ax.text(0.2, 0.3, "lg", **kwargs)\n ax.text(0.4, 0.3, r"$\frac{1}{2}\pi$", **kwargs)\n ax.text(0.6, 0.3, "$p^{3^A}$", **kwargs)\n ax.text(0.8, 0.3, "$p_{3_2}$", **kwargs)\n for x in {t.get_position()[0] for t in ax.texts}:\n ax.axvline(x)\n for y in {t.get_position()[1] for t in ax.texts}:\n ax.axhline(y)\n ax.set_axis_off()\n\n\n@check_figures_equal()\ndef test_empty(fig_test, fig_ref):\n mpl.rcParams['text.usetex'] = True\n fig_test.text(.5, .5, "% a comment")\n\n\n@check_figures_equal()\ndef test_unicode_minus(fig_test, fig_ref):\n mpl.rcParams['text.usetex'] = True\n fig_test.text(.5, .5, "$-$")\n fig_ref.text(.5, .5, "\N{MINUS SIGN}")\n\n\ndef test_mathdefault():\n plt.rcParams["axes.formatter.use_mathtext"] = True\n fig = plt.figure()\n fig.add_subplot().set_xlim(-1, 1)\n # Check that \mathdefault commands generated by tickers don't cause\n # problems when later switching usetex on.\n mpl.rcParams['text.usetex'] = True\n fig.canvas.draw()\n\n\n@image_comparison(['eqnarray.png'])\ndef test_multiline_eqnarray():\n text = (\n r'\begin{eqnarray*}'\n r'foo\\'\n r'bar\\'\n r'baz\\'\n r'\end{eqnarray*}'\n )\n\n fig = plt.figure(figsize=(1, 1))\n fig.text(0.5, 0.5, text, usetex=True,\n horizontalalignment='center', verticalalignment='center')\n\n\n@pytest.mark.parametrize("fontsize", [8, 10, 12])\ndef test_minus_no_descent(fontsize):\n # Test special-casing of minus descent in DviFont._height_depth_of, by\n # checking that overdrawing a 1 and a -1 results in an overall height\n # equivalent to drawing either of them separately.\n mpl.style.use("mpl20")\n mpl.rcParams['font.size'] = fontsize\n heights = {}\n fig = plt.figure()\n for vals in [(1,), (-1,), (-1, 1)]:\n fig.clear()\n for x in vals:\n fig.text(.5, .5, f"${x}$", usetex=True)\n fig.canvas.draw()\n # The following counts the number of non-fully-blank pixel rows.\n heights[vals] = ((np.array(fig.canvas.buffer_rgba())[..., 0] != 255)\n .any(axis=1).sum())\n assert len({*heights.values()}) == 1\n\n\n@pytest.mark.parametrize('pkg', ['xcolor', 'chemformula'])\ndef test_usetex_packages(pkg):\n if not _has_tex_package(pkg):\n pytest.skip(f'{pkg} is not available')\n mpl.rcParams['text.usetex'] = True\n\n fig = plt.figure()\n text = fig.text(0.5, 0.5, "Some text 0123456789")\n fig.canvas.draw()\n\n mpl.rcParams['text.latex.preamble'] = (\n r'\PassOptionsToPackage{dvipsnames}{xcolor}\usepackage{%s}' % pkg)\n fig = plt.figure()\n text2 = fig.text(0.5, 0.5, "Some text 0123456789")\n fig.canvas.draw()\n np.testing.assert_array_equal(text2.get_window_extent(),\n text.get_window_extent())\n\n\n@pytest.mark.parametrize(\n "preamble",\n [r"\usepackage[full]{textcomp}", r"\usepackage{underscore}"],\n)\ndef test_latex_pkg_already_loaded(preamble):\n plt.rcParams["text.latex.preamble"] = preamble\n fig = plt.figure()\n fig.text(.5, .5, "hello, world", usetex=True)\n fig.canvas.draw()\n\n\ndef test_usetex_with_underscore():\n plt.rcParams["text.usetex"] = True\n df = {"a_b": range(5)[::-1], "c": range(5)}\n fig, ax = plt.subplots()\n ax.plot("c", "a_b", data=df)\n ax.legend()\n ax.text(0, 0, "foo_bar", usetex=True)\n plt.draw()\n\n\n@pytest.mark.flaky(reruns=3) # Tends to hit a TeX cache lock on AppVeyor.\n@pytest.mark.parametrize("fmt", ["pdf", "svg"])\ndef test_missing_psfont(fmt, monkeypatch):\n """An error is raised if a TeX font lacks a Type-1 equivalent"""\n monkeypatch.setattr(\n dviread.PsfontsMap, '__getitem__',\n lambda self, k: dviread.PsFont(\n texname=b'texfont', psname=b'Some Font',\n effects=None, encoding=None, filename=None))\n mpl.rcParams['text.usetex'] = True\n fig, ax = plt.subplots()\n ax.text(0.5, 0.5, 'hello')\n with TemporaryFile() as tmpfile, pytest.raises(ValueError):\n fig.savefig(tmpfile, format=fmt)\n\n\ntry:\n _old_gs_version = mpl._get_executable_info('gs').version < parse_version('9.55')\nexcept mpl.ExecutableNotFoundError:\n _old_gs_version = True\n\n\n@image_comparison(baseline_images=['rotation'], extensions=['eps', 'pdf', 'png', 'svg'],\n style='mpl20', tol=3.91 if _old_gs_version else 0)\ndef test_rotation():\n mpl.rcParams['text.usetex'] = True\n\n fig = plt.figure()\n ax = fig.add_axes([0, 0, 1, 1])\n ax.set(xlim=[-0.5, 5], xticks=[], ylim=[-0.5, 3], yticks=[], frame_on=False)\n\n text = {val: val[0] for val in ['top', 'center', 'bottom', 'left', 'right']}\n text['baseline'] = 'B'\n text['center_baseline'] = 'C'\n\n for i, va in enumerate(['top', 'center', 'bottom', 'baseline', 'center_baseline']):\n for j, ha in enumerate(['left', 'center', 'right']):\n for k, angle in enumerate([0, 90, 180, 270]):\n k //= 2\n x = i + k / 2\n y = j + k / 2\n ax.plot(x, y, '+', c=f'C{k}', markersize=20, markeredgewidth=0.5)\n # 'My' checks full height letters plus descenders.\n ax.text(x, y, f"$\\mathrm{{My {text[ha]}{text[va]} {angle}}}$",\n rotation=angle, horizontalalignment=ha, verticalalignment=va)\n | .venv\Lib\site-packages\matplotlib\tests\test_usetex.py | test_usetex.py | Python | 6,405 | 0.95 | 0.13369 | 0.071895 | python-kit | 171 | 2024-09-14T09:14:22.140278 | Apache-2.0 | true | 655734f1d04b272ad4641efdadfd46ea |
import functools\nimport io\nimport operator\nfrom unittest import mock\n\nfrom matplotlib.backend_bases import MouseEvent\nimport matplotlib.colors as mcolors\nimport matplotlib.widgets as widgets\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\nfrom matplotlib.testing.widgets import (click_and_drag, do_event, get_ax,\n mock_event, noop)\n\nimport numpy as np\nfrom numpy.testing import assert_allclose\n\nimport pytest\n\n\n@pytest.fixture\ndef ax():\n return get_ax()\n\n\ndef test_save_blitted_widget_as_pdf():\n from matplotlib.widgets import CheckButtons, RadioButtons\n from matplotlib.cbook import _get_running_interactive_framework\n if _get_running_interactive_framework() not in ['headless', None]:\n pytest.xfail("Callback exceptions are not raised otherwise.")\n\n fig, ax = plt.subplots(\n nrows=2, ncols=2, figsize=(5, 2), width_ratios=[1, 2]\n )\n default_rb = RadioButtons(ax[0, 0], ['Apples', 'Oranges'])\n styled_rb = RadioButtons(\n ax[0, 1], ['Apples', 'Oranges'],\n label_props={'color': ['red', 'orange'],\n 'fontsize': [16, 20]},\n radio_props={'edgecolor': ['red', 'orange'],\n 'facecolor': ['mistyrose', 'peachpuff']}\n )\n\n default_cb = CheckButtons(ax[1, 0], ['Apples', 'Oranges'],\n actives=[True, True])\n styled_cb = CheckButtons(\n ax[1, 1], ['Apples', 'Oranges'],\n actives=[True, True],\n label_props={'color': ['red', 'orange'],\n 'fontsize': [16, 20]},\n frame_props={'edgecolor': ['red', 'orange'],\n 'facecolor': ['mistyrose', 'peachpuff']},\n check_props={'color': ['darkred', 'darkorange']}\n )\n\n ax[0, 0].set_title('Default')\n ax[0, 1].set_title('Stylized')\n # force an Agg render\n fig.canvas.draw()\n # force a pdf save\n with io.BytesIO() as result_after:\n fig.savefig(result_after, format='pdf')\n\n\n@pytest.mark.parametrize('kwargs', [\n dict(),\n dict(useblit=True, button=1),\n dict(minspanx=10, minspany=10, spancoords='pixels'),\n dict(props=dict(fill=True)),\n])\ndef test_rectangle_selector(ax, kwargs):\n onselect = mock.Mock(spec=noop, return_value=None)\n\n tool = widgets.RectangleSelector(ax, onselect=onselect, **kwargs)\n do_event(tool, 'press', xdata=100, ydata=100, button=1)\n do_event(tool, 'onmove', xdata=199, ydata=199, button=1)\n\n # purposely drag outside of axis for release\n do_event(tool, 'release', xdata=250, ydata=250, button=1)\n\n if kwargs.get('drawtype', None) not in ['line', 'none']:\n assert_allclose(tool.geometry,\n [[100., 100, 199, 199, 100],\n [100, 199, 199, 100, 100]],\n err_msg=tool.geometry)\n\n onselect.assert_called_once()\n (epress, erelease), kwargs = onselect.call_args\n assert epress.xdata == 100\n assert epress.ydata == 100\n assert erelease.xdata == 199\n assert erelease.ydata == 199\n assert kwargs == {}\n\n\n@pytest.mark.parametrize('spancoords', ['data', 'pixels'])\n@pytest.mark.parametrize('minspanx, x1', [[0, 10], [1, 10.5], [1, 11]])\n@pytest.mark.parametrize('minspany, y1', [[0, 10], [1, 10.5], [1, 11]])\ndef test_rectangle_minspan(ax, spancoords, minspanx, x1, minspany, y1):\n\n onselect = mock.Mock(spec=noop, return_value=None)\n\n x0, y0 = (10, 10)\n if spancoords == 'pixels':\n minspanx, minspany = (ax.transData.transform((x1, y1)) -\n ax.transData.transform((x0, y0)))\n\n tool = widgets.RectangleSelector(ax, onselect=onselect, interactive=True,\n spancoords=spancoords,\n minspanx=minspanx, minspany=minspany)\n # Too small to create a selector\n click_and_drag(tool, start=(x0, x1), end=(y0, y1))\n assert not tool._selection_completed\n onselect.assert_not_called()\n\n click_and_drag(tool, start=(20, 20), end=(30, 30))\n assert tool._selection_completed\n onselect.assert_called_once()\n\n # Too small to create a selector. Should clear existing selector, and\n # trigger onselect because there was a preexisting selector\n onselect.reset_mock()\n click_and_drag(tool, start=(x0, y0), end=(x1, y1))\n assert not tool._selection_completed\n onselect.assert_called_once()\n (epress, erelease), kwargs = onselect.call_args\n assert epress.xdata == x0\n assert epress.ydata == y0\n assert erelease.xdata == x1\n assert erelease.ydata == y1\n assert kwargs == {}\n\n\n@pytest.mark.parametrize('drag_from_anywhere, new_center',\n [[True, (60, 75)],\n [False, (30, 20)]])\ndef test_rectangle_drag(ax, drag_from_anywhere, new_center):\n tool = widgets.RectangleSelector(ax, interactive=True,\n drag_from_anywhere=drag_from_anywhere)\n # Create rectangle\n click_and_drag(tool, start=(0, 10), end=(100, 120))\n assert tool.center == (50, 65)\n # Drag inside rectangle, but away from centre handle\n #\n # If drag_from_anywhere == True, this will move the rectangle by (10, 10),\n # giving it a new center of (60, 75)\n #\n # If drag_from_anywhere == False, this will create a new rectangle with\n # center (30, 20)\n click_and_drag(tool, start=(25, 15), end=(35, 25))\n assert tool.center == new_center\n # Check that in both cases, dragging outside the rectangle draws a new\n # rectangle\n click_and_drag(tool, start=(175, 185), end=(185, 195))\n assert tool.center == (180, 190)\n\n\ndef test_rectangle_selector_set_props_handle_props(ax):\n tool = widgets.RectangleSelector(ax, interactive=True,\n props=dict(facecolor='b', alpha=0.2),\n handle_props=dict(alpha=0.5))\n # Create rectangle\n click_and_drag(tool, start=(0, 10), end=(100, 120))\n\n artist = tool._selection_artist\n assert artist.get_facecolor() == mcolors.to_rgba('b', alpha=0.2)\n tool.set_props(facecolor='r', alpha=0.3)\n assert artist.get_facecolor() == mcolors.to_rgba('r', alpha=0.3)\n\n for artist in tool._handles_artists:\n assert artist.get_markeredgecolor() == 'black'\n assert artist.get_alpha() == 0.5\n tool.set_handle_props(markeredgecolor='r', alpha=0.3)\n for artist in tool._handles_artists:\n assert artist.get_markeredgecolor() == 'r'\n assert artist.get_alpha() == 0.3\n\n\ndef test_rectangle_resize(ax):\n tool = widgets.RectangleSelector(ax, interactive=True)\n # Create rectangle\n click_and_drag(tool, start=(0, 10), end=(100, 120))\n assert tool.extents == (0.0, 100.0, 10.0, 120.0)\n\n # resize NE handle\n extents = tool.extents\n xdata, ydata = extents[1], extents[3]\n xdata_new, ydata_new = xdata + 10, ydata + 5\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))\n assert tool.extents == (extents[0], xdata_new, extents[2], ydata_new)\n\n # resize E handle\n extents = tool.extents\n xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2\n xdata_new, ydata_new = xdata + 10, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))\n assert tool.extents == (extents[0], xdata_new, extents[2], extents[3])\n\n # resize W handle\n extents = tool.extents\n xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2\n xdata_new, ydata_new = xdata + 15, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))\n assert tool.extents == (xdata_new, extents[1], extents[2], extents[3])\n\n # resize SW handle\n extents = tool.extents\n xdata, ydata = extents[0], extents[2]\n xdata_new, ydata_new = xdata + 20, ydata + 25\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))\n assert tool.extents == (xdata_new, extents[1], ydata_new, extents[3])\n\n\ndef test_rectangle_add_state(ax):\n tool = widgets.RectangleSelector(ax, interactive=True)\n # Create rectangle\n click_and_drag(tool, start=(70, 65), end=(125, 130))\n\n with pytest.raises(ValueError):\n tool.add_state('unsupported_state')\n\n with pytest.raises(ValueError):\n tool.add_state('clear')\n tool.add_state('move')\n tool.add_state('square')\n tool.add_state('center')\n\n\n@pytest.mark.parametrize('add_state', [True, False])\ndef test_rectangle_resize_center(ax, add_state):\n tool = widgets.RectangleSelector(ax, interactive=True)\n # Create rectangle\n click_and_drag(tool, start=(70, 65), end=(125, 130))\n assert tool.extents == (70.0, 125.0, 65.0, 130.0)\n\n if add_state:\n tool.add_state('center')\n use_key = None\n else:\n use_key = 'control'\n\n # resize NE handle\n extents = tool.extents\n xdata, ydata = extents[1], extents[3]\n xdiff, ydiff = 10, 5\n xdata_new, ydata_new = xdata + xdiff, ydata + ydiff\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),\n key=use_key)\n assert tool.extents == (extents[0] - xdiff, xdata_new,\n extents[2] - ydiff, ydata_new)\n\n # resize E handle\n extents = tool.extents\n xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2\n xdiff = 10\n xdata_new, ydata_new = xdata + xdiff, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),\n key=use_key)\n assert tool.extents == (extents[0] - xdiff, xdata_new,\n extents[2], extents[3])\n\n # resize E handle negative diff\n extents = tool.extents\n xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2\n xdiff = -20\n xdata_new, ydata_new = xdata + xdiff, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),\n key=use_key)\n assert tool.extents == (extents[0] - xdiff, xdata_new,\n extents[2], extents[3])\n\n # resize W handle\n extents = tool.extents\n xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2\n xdiff = 15\n xdata_new, ydata_new = xdata + xdiff, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),\n key=use_key)\n assert tool.extents == (xdata_new, extents[1] - xdiff,\n extents[2], extents[3])\n\n # resize W handle negative diff\n extents = tool.extents\n xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2\n xdiff = -25\n xdata_new, ydata_new = xdata + xdiff, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),\n key=use_key)\n assert tool.extents == (xdata_new, extents[1] - xdiff,\n extents[2], extents[3])\n\n # resize SW handle\n extents = tool.extents\n xdata, ydata = extents[0], extents[2]\n xdiff, ydiff = 20, 25\n xdata_new, ydata_new = xdata + xdiff, ydata + ydiff\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),\n key=use_key)\n assert tool.extents == (xdata_new, extents[1] - xdiff,\n ydata_new, extents[3] - ydiff)\n\n\n@pytest.mark.parametrize('add_state', [True, False])\ndef test_rectangle_resize_square(ax, add_state):\n tool = widgets.RectangleSelector(ax, interactive=True)\n # Create rectangle\n click_and_drag(tool, start=(70, 65), end=(120, 115))\n assert tool.extents == (70.0, 120.0, 65.0, 115.0)\n\n if add_state:\n tool.add_state('square')\n use_key = None\n else:\n use_key = 'shift'\n\n # resize NE handle\n extents = tool.extents\n xdata, ydata = extents[1], extents[3]\n xdiff, ydiff = 10, 5\n xdata_new, ydata_new = xdata + xdiff, ydata + ydiff\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),\n key=use_key)\n assert tool.extents == (extents[0], xdata_new,\n extents[2], extents[3] + xdiff)\n\n # resize E handle\n extents = tool.extents\n xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2\n xdiff = 10\n xdata_new, ydata_new = xdata + xdiff, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),\n key=use_key)\n assert tool.extents == (extents[0], xdata_new,\n extents[2], extents[3] + xdiff)\n\n # resize E handle negative diff\n extents = tool.extents\n xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2\n xdiff = -20\n xdata_new, ydata_new = xdata + xdiff, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),\n key=use_key)\n assert tool.extents == (extents[0], xdata_new,\n extents[2], extents[3] + xdiff)\n\n # resize W handle\n extents = tool.extents\n xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2\n xdiff = 15\n xdata_new, ydata_new = xdata + xdiff, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),\n key=use_key)\n assert tool.extents == (xdata_new, extents[1],\n extents[2], extents[3] - xdiff)\n\n # resize W handle negative diff\n extents = tool.extents\n xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2\n xdiff = -25\n xdata_new, ydata_new = xdata + xdiff, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),\n key=use_key)\n assert tool.extents == (xdata_new, extents[1],\n extents[2], extents[3] - xdiff)\n\n # resize SW handle\n extents = tool.extents\n xdata, ydata = extents[0], extents[2]\n xdiff, ydiff = 20, 25\n xdata_new, ydata_new = xdata + xdiff, ydata + ydiff\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),\n key=use_key)\n assert tool.extents == (extents[0] + ydiff, extents[1],\n ydata_new, extents[3])\n\n\ndef test_rectangle_resize_square_center(ax):\n tool = widgets.RectangleSelector(ax, interactive=True)\n # Create rectangle\n click_and_drag(tool, start=(70, 65), end=(120, 115))\n tool.add_state('square')\n tool.add_state('center')\n assert_allclose(tool.extents, (70.0, 120.0, 65.0, 115.0))\n\n # resize NE handle\n extents = tool.extents\n xdata, ydata = extents[1], extents[3]\n xdiff, ydiff = 10, 5\n xdata_new, ydata_new = xdata + xdiff, ydata + ydiff\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))\n assert_allclose(tool.extents, (extents[0] - xdiff, xdata_new,\n extents[2] - xdiff, extents[3] + xdiff))\n\n # resize E handle\n extents = tool.extents\n xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2\n xdiff = 10\n xdata_new, ydata_new = xdata + xdiff, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))\n assert_allclose(tool.extents, (extents[0] - xdiff, xdata_new,\n extents[2] - xdiff, extents[3] + xdiff))\n\n # resize E handle negative diff\n extents = tool.extents\n xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2\n xdiff = -20\n xdata_new, ydata_new = xdata + xdiff, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))\n assert_allclose(tool.extents, (extents[0] - xdiff, xdata_new,\n extents[2] - xdiff, extents[3] + xdiff))\n\n # resize W handle\n extents = tool.extents\n xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2\n xdiff = 5\n xdata_new, ydata_new = xdata + xdiff, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))\n assert_allclose(tool.extents, (xdata_new, extents[1] - xdiff,\n extents[2] + xdiff, extents[3] - xdiff))\n\n # resize W handle negative diff\n extents = tool.extents\n xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2\n xdiff = -25\n xdata_new, ydata_new = xdata + xdiff, ydata\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))\n assert_allclose(tool.extents, (xdata_new, extents[1] - xdiff,\n extents[2] + xdiff, extents[3] - xdiff))\n\n # resize SW handle\n extents = tool.extents\n xdata, ydata = extents[0], extents[2]\n xdiff, ydiff = 20, 25\n xdata_new, ydata_new = xdata + xdiff, ydata + ydiff\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))\n assert_allclose(tool.extents, (extents[0] + ydiff, extents[1] - ydiff,\n ydata_new, extents[3] - ydiff))\n\n\n@pytest.mark.parametrize('selector_class',\n [widgets.RectangleSelector, widgets.EllipseSelector])\ndef test_rectangle_rotate(ax, selector_class):\n tool = selector_class(ax, interactive=True)\n # Draw rectangle\n click_and_drag(tool, start=(100, 100), end=(130, 140))\n assert tool.extents == (100, 130, 100, 140)\n assert len(tool._state) == 0\n\n # Rotate anticlockwise using top-right corner\n do_event(tool, 'on_key_press', key='r')\n assert tool._state == {'rotate'}\n assert len(tool._state) == 1\n click_and_drag(tool, start=(130, 140), end=(120, 145))\n do_event(tool, 'on_key_press', key='r')\n assert len(tool._state) == 0\n # Extents shouldn't change (as shape of rectangle hasn't changed)\n assert tool.extents == (100, 130, 100, 140)\n assert_allclose(tool.rotation, 25.56, atol=0.01)\n tool.rotation = 45\n assert tool.rotation == 45\n # Corners should move\n assert_allclose(tool.corners,\n np.array([[118.53, 139.75, 111.46, 90.25],\n [95.25, 116.46, 144.75, 123.54]]), atol=0.01)\n\n # Scale using top-right corner\n click_and_drag(tool, start=(110, 145), end=(110, 160))\n assert_allclose(tool.extents, (100, 139.75, 100, 151.82), atol=0.01)\n\n if selector_class == widgets.RectangleSelector:\n with pytest.raises(ValueError):\n tool._selection_artist.rotation_point = 'unvalid_value'\n\n\ndef test_rectangle_add_remove_set(ax):\n tool = widgets.RectangleSelector(ax, interactive=True)\n # Draw rectangle\n click_and_drag(tool, start=(100, 100), end=(130, 140))\n assert tool.extents == (100, 130, 100, 140)\n assert len(tool._state) == 0\n for state in ['rotate', 'square', 'center']:\n tool.add_state(state)\n assert len(tool._state) == 1\n tool.remove_state(state)\n assert len(tool._state) == 0\n\n\n@pytest.mark.parametrize('use_data_coordinates', [False, True])\ndef test_rectangle_resize_square_center_aspect(ax, use_data_coordinates):\n ax.set_aspect(0.8)\n\n tool = widgets.RectangleSelector(ax, interactive=True,\n use_data_coordinates=use_data_coordinates)\n # Create rectangle\n click_and_drag(tool, start=(70, 65), end=(120, 115))\n assert tool.extents == (70.0, 120.0, 65.0, 115.0)\n tool.add_state('square')\n tool.add_state('center')\n\n if use_data_coordinates:\n # resize E handle\n extents = tool.extents\n xdata, ydata, width = extents[1], extents[3], extents[1] - extents[0]\n xdiff, ycenter = 10, extents[2] + (extents[3] - extents[2]) / 2\n xdata_new, ydata_new = xdata + xdiff, ydata\n ychange = width / 2 + xdiff\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))\n assert_allclose(tool.extents, [extents[0] - xdiff, xdata_new,\n ycenter - ychange, ycenter + ychange])\n else:\n # resize E handle\n extents = tool.extents\n xdata, ydata = extents[1], extents[3]\n xdiff = 10\n xdata_new, ydata_new = xdata + xdiff, ydata\n ychange = xdiff * 1 / tool._aspect_ratio_correction\n click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))\n assert_allclose(tool.extents, [extents[0] - xdiff, xdata_new,\n 46.25, 133.75])\n\n\ndef test_ellipse(ax):\n """For ellipse, test out the key modifiers"""\n tool = widgets.EllipseSelector(ax, grab_range=10, interactive=True)\n tool.extents = (100, 150, 100, 150)\n\n # drag the rectangle\n click_and_drag(tool, start=(125, 125), end=(145, 145))\n assert tool.extents == (120, 170, 120, 170)\n\n # create from center\n click_and_drag(tool, start=(100, 100), end=(125, 125), key='control')\n assert tool.extents == (75, 125, 75, 125)\n\n # create a square\n click_and_drag(tool, start=(10, 10), end=(35, 30), key='shift')\n extents = [int(e) for e in tool.extents]\n assert extents == [10, 35, 10, 35]\n\n # create a square from center\n click_and_drag(tool, start=(100, 100), end=(125, 130), key='ctrl+shift')\n extents = [int(e) for e in tool.extents]\n assert extents == [70, 130, 70, 130]\n\n assert tool.geometry.shape == (2, 73)\n assert_allclose(tool.geometry[:, 0], [70., 100])\n\n\ndef test_rectangle_handles(ax):\n tool = widgets.RectangleSelector(ax, grab_range=10, interactive=True,\n handle_props={'markerfacecolor': 'r',\n 'markeredgecolor': 'b'})\n tool.extents = (100, 150, 100, 150)\n\n assert_allclose(tool.corners, ((100, 150, 150, 100), (100, 100, 150, 150)))\n assert tool.extents == (100, 150, 100, 150)\n assert_allclose(tool.edge_centers,\n ((100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150)))\n assert tool.extents == (100, 150, 100, 150)\n\n # grab a corner and move it\n click_and_drag(tool, start=(100, 100), end=(120, 120))\n assert tool.extents == (120, 150, 120, 150)\n\n # grab the center and move it\n click_and_drag(tool, start=(132, 132), end=(120, 120))\n assert tool.extents == (108, 138, 108, 138)\n\n # create a new rectangle\n click_and_drag(tool, start=(10, 10), end=(100, 100))\n assert tool.extents == (10, 100, 10, 100)\n\n # Check that marker_props worked.\n assert mcolors.same_color(\n tool._corner_handles.artists[0].get_markerfacecolor(), 'r')\n assert mcolors.same_color(\n tool._corner_handles.artists[0].get_markeredgecolor(), 'b')\n\n\n@pytest.mark.parametrize('interactive', [True, False])\ndef test_rectangle_selector_onselect(ax, interactive):\n # check when press and release events take place at the same position\n onselect = mock.Mock(spec=noop, return_value=None)\n\n tool = widgets.RectangleSelector(ax, onselect=onselect, interactive=interactive)\n # move outside of axis\n click_and_drag(tool, start=(100, 110), end=(150, 120))\n\n onselect.assert_called_once()\n assert tool.extents == (100.0, 150.0, 110.0, 120.0)\n\n onselect.reset_mock()\n click_and_drag(tool, start=(10, 100), end=(10, 100))\n onselect.assert_called_once()\n\n\n@pytest.mark.parametrize('ignore_event_outside', [True, False])\ndef test_rectangle_selector_ignore_outside(ax, ignore_event_outside):\n onselect = mock.Mock(spec=noop, return_value=None)\n\n tool = widgets.RectangleSelector(ax, onselect=onselect,\n ignore_event_outside=ignore_event_outside)\n click_and_drag(tool, start=(100, 110), end=(150, 120))\n onselect.assert_called_once()\n assert tool.extents == (100.0, 150.0, 110.0, 120.0)\n\n onselect.reset_mock()\n # Trigger event outside of span\n click_and_drag(tool, start=(150, 150), end=(160, 160))\n if ignore_event_outside:\n # event have been ignored and span haven't changed.\n onselect.assert_not_called()\n assert tool.extents == (100.0, 150.0, 110.0, 120.0)\n else:\n # A new shape is created\n onselect.assert_called_once()\n assert tool.extents == (150.0, 160.0, 150.0, 160.0)\n\n\n@pytest.mark.parametrize('orientation, onmove_callback, kwargs', [\n ('horizontal', False, dict(minspan=10, useblit=True)),\n ('vertical', True, dict(button=1)),\n ('horizontal', False, dict(props=dict(fill=True))),\n ('horizontal', False, dict(interactive=True)),\n])\ndef test_span_selector(ax, orientation, onmove_callback, kwargs):\n onselect = mock.Mock(spec=noop, return_value=None)\n onmove = mock.Mock(spec=noop, return_value=None)\n if onmove_callback:\n kwargs['onmove_callback'] = onmove\n\n # While at it, also test that span selectors work in the presence of twin axes on\n # top of the axes that contain the selector. Note that we need to unforce the axes\n # aspect here, otherwise the twin axes forces the original axes' limits (to respect\n # aspect=1) which makes some of the values below go out of bounds.\n ax.set_aspect("auto")\n tax = ax.twinx()\n\n tool = widgets.SpanSelector(ax, onselect, orientation, **kwargs)\n do_event(tool, 'press', xdata=100, ydata=100, button=1)\n # move outside of axis\n do_event(tool, 'onmove', xdata=199, ydata=199, button=1)\n do_event(tool, 'release', xdata=250, ydata=250, button=1)\n\n onselect.assert_called_once_with(100, 199)\n if onmove_callback:\n onmove.assert_called_once_with(100, 199)\n\n\n@pytest.mark.parametrize('interactive', [True, False])\ndef test_span_selector_onselect(ax, interactive):\n onselect = mock.Mock(spec=noop, return_value=None)\n\n tool = widgets.SpanSelector(ax, onselect, 'horizontal',\n interactive=interactive)\n # move outside of axis\n click_and_drag(tool, start=(100, 100), end=(150, 100))\n onselect.assert_called_once()\n assert tool.extents == (100, 150)\n\n onselect.reset_mock()\n click_and_drag(tool, start=(10, 100), end=(10, 100))\n onselect.assert_called_once()\n\n\n@pytest.mark.parametrize('ignore_event_outside', [True, False])\ndef test_span_selector_ignore_outside(ax, ignore_event_outside):\n onselect = mock.Mock(spec=noop, return_value=None)\n onmove = mock.Mock(spec=noop, return_value=None)\n\n tool = widgets.SpanSelector(ax, onselect, 'horizontal',\n onmove_callback=onmove,\n ignore_event_outside=ignore_event_outside)\n click_and_drag(tool, start=(100, 100), end=(125, 125))\n onselect.assert_called_once()\n onmove.assert_called_once()\n assert tool.extents == (100, 125)\n\n onselect.reset_mock()\n onmove.reset_mock()\n # Trigger event outside of span\n click_and_drag(tool, start=(150, 150), end=(160, 160))\n if ignore_event_outside:\n # event have been ignored and span haven't changed.\n onselect.assert_not_called()\n onmove.assert_not_called()\n assert tool.extents == (100, 125)\n else:\n # A new shape is created\n onselect.assert_called_once()\n onmove.assert_called_once()\n assert tool.extents == (150, 160)\n\n\n@pytest.mark.parametrize('drag_from_anywhere', [True, False])\ndef test_span_selector_drag(ax, drag_from_anywhere):\n # Create span\n tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal',\n interactive=True,\n drag_from_anywhere=drag_from_anywhere)\n click_and_drag(tool, start=(10, 10), end=(100, 120))\n assert tool.extents == (10, 100)\n # Drag inside span\n #\n # If drag_from_anywhere == True, this will move the span by 10,\n # giving new value extents = 20, 110\n #\n # If drag_from_anywhere == False, this will create a new span with\n # value extents = 25, 35\n click_and_drag(tool, start=(25, 15), end=(35, 25))\n if drag_from_anywhere:\n assert tool.extents == (20, 110)\n else:\n assert tool.extents == (25, 35)\n\n # Check that in both cases, dragging outside the span draws a new span\n click_and_drag(tool, start=(175, 185), end=(185, 195))\n assert tool.extents == (175, 185)\n\n\ndef test_span_selector_direction(ax):\n tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal',\n interactive=True)\n assert tool.direction == 'horizontal'\n assert tool._edge_handles.direction == 'horizontal'\n\n with pytest.raises(ValueError):\n tool = widgets.SpanSelector(ax, onselect=noop,\n direction='invalid_direction')\n\n tool.direction = 'vertical'\n assert tool.direction == 'vertical'\n assert tool._edge_handles.direction == 'vertical'\n\n with pytest.raises(ValueError):\n tool.direction = 'invalid_string'\n\n\ndef test_span_selector_set_props_handle_props(ax):\n tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal',\n interactive=True,\n props=dict(facecolor='b', alpha=0.2),\n handle_props=dict(alpha=0.5))\n # Create rectangle\n click_and_drag(tool, start=(0, 10), end=(100, 120))\n\n artist = tool._selection_artist\n assert artist.get_facecolor() == mcolors.to_rgba('b', alpha=0.2)\n tool.set_props(facecolor='r', alpha=0.3)\n assert artist.get_facecolor() == mcolors.to_rgba('r', alpha=0.3)\n\n for artist in tool._handles_artists:\n assert artist.get_color() == 'b'\n assert artist.get_alpha() == 0.5\n tool.set_handle_props(color='r', alpha=0.3)\n for artist in tool._handles_artists:\n assert artist.get_color() == 'r'\n assert artist.get_alpha() == 0.3\n\n\n@pytest.mark.parametrize('selector', ['span', 'rectangle'])\ndef test_selector_clear(ax, selector):\n kwargs = dict(ax=ax, interactive=True)\n if selector == 'span':\n Selector = widgets.SpanSelector\n kwargs['direction'] = 'horizontal'\n kwargs['onselect'] = noop\n else:\n Selector = widgets.RectangleSelector\n\n tool = Selector(**kwargs)\n click_and_drag(tool, start=(10, 10), end=(100, 120))\n\n # press-release event outside the selector to clear the selector\n click_and_drag(tool, start=(130, 130), end=(130, 130))\n assert not tool._selection_completed\n\n kwargs['ignore_event_outside'] = True\n tool = Selector(**kwargs)\n assert tool.ignore_event_outside\n click_and_drag(tool, start=(10, 10), end=(100, 120))\n\n # press-release event outside the selector ignored\n click_and_drag(tool, start=(130, 130), end=(130, 130))\n assert tool._selection_completed\n\n do_event(tool, 'on_key_press', key='escape')\n assert not tool._selection_completed\n\n\n@pytest.mark.parametrize('selector', ['span', 'rectangle'])\ndef test_selector_clear_method(ax, selector):\n if selector == 'span':\n tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal',\n interactive=True,\n ignore_event_outside=True)\n else:\n tool = widgets.RectangleSelector(ax, interactive=True)\n click_and_drag(tool, start=(10, 10), end=(100, 120))\n assert tool._selection_completed\n assert tool.get_visible()\n if selector == 'span':\n assert tool.extents == (10, 100)\n\n tool.clear()\n assert not tool._selection_completed\n assert not tool.get_visible()\n\n # Do another cycle of events to make sure we can\n click_and_drag(tool, start=(10, 10), end=(50, 120))\n assert tool._selection_completed\n assert tool.get_visible()\n if selector == 'span':\n assert tool.extents == (10, 50)\n\n\ndef test_span_selector_add_state(ax):\n tool = widgets.SpanSelector(ax, noop, 'horizontal',\n interactive=True)\n\n with pytest.raises(ValueError):\n tool.add_state('unsupported_state')\n with pytest.raises(ValueError):\n tool.add_state('center')\n with pytest.raises(ValueError):\n tool.add_state('square')\n\n tool.add_state('move')\n\n\ndef test_tool_line_handle(ax):\n positions = [20, 30, 50]\n tool_line_handle = widgets.ToolLineHandles(ax, positions, 'horizontal',\n useblit=False)\n\n for artist in tool_line_handle.artists:\n assert not artist.get_animated()\n assert not artist.get_visible()\n\n tool_line_handle.set_visible(True)\n tool_line_handle.set_animated(True)\n\n for artist in tool_line_handle.artists:\n assert artist.get_animated()\n assert artist.get_visible()\n\n assert tool_line_handle.positions == positions\n\n\n@pytest.mark.parametrize('direction', ("horizontal", "vertical"))\ndef test_span_selector_bound(direction):\n fig, ax = plt.subplots(1, 1)\n ax.plot([10, 20], [10, 30])\n fig.canvas.draw()\n x_bound = ax.get_xbound()\n y_bound = ax.get_ybound()\n\n tool = widgets.SpanSelector(ax, print, direction, interactive=True)\n assert ax.get_xbound() == x_bound\n assert ax.get_ybound() == y_bound\n\n bound = x_bound if direction == 'horizontal' else y_bound\n assert tool._edge_handles.positions == list(bound)\n\n press_data = (10.5, 11.5)\n move_data = (11, 13) # Updating selector is done in onmove\n release_data = move_data\n click_and_drag(tool, start=press_data, end=move_data)\n\n assert ax.get_xbound() == x_bound\n assert ax.get_ybound() == y_bound\n\n index = 0 if direction == 'horizontal' else 1\n handle_positions = [press_data[index], release_data[index]]\n assert tool._edge_handles.positions == handle_positions\n\n\n@pytest.mark.backend('QtAgg', skip_on_importerror=True)\ndef test_span_selector_animated_artists_callback():\n """Check that the animated artists changed in callbacks are updated."""\n x = np.linspace(0, 2 * np.pi, 100)\n values = np.sin(x)\n\n fig, ax = plt.subplots()\n ln, = ax.plot(x, values, animated=True)\n ln2, = ax.plot([], animated=True)\n\n # spin the event loop to let the backend process any pending operations\n # before drawing artists\n # See blitting tutorial\n plt.pause(0.1)\n ax.draw_artist(ln)\n fig.canvas.blit(fig.bbox)\n\n def mean(vmin, vmax):\n # Return mean of values in x between *vmin* and *vmax*\n indmin, indmax = np.searchsorted(x, (vmin, vmax))\n v = values[indmin:indmax].mean()\n ln2.set_data(x, np.full_like(x, v))\n\n span = widgets.SpanSelector(ax, mean, direction='horizontal',\n onmove_callback=mean,\n interactive=True,\n drag_from_anywhere=True,\n useblit=True)\n\n # Add span selector and check that the line is draw after it was updated\n # by the callback\n press_data = [1, 2]\n move_data = [2, 2]\n do_event(span, 'press', xdata=press_data[0], ydata=press_data[1], button=1)\n do_event(span, 'onmove', xdata=move_data[0], ydata=move_data[1], button=1)\n assert span._get_animated_artists() == (ln, ln2)\n assert ln.stale is False\n assert ln2.stale\n assert_allclose(ln2.get_ydata(), 0.9547335049088455)\n span.update()\n assert ln2.stale is False\n\n # Change span selector and check that the line is drawn/updated after its\n # value was updated by the callback\n press_data = [4, 0]\n move_data = [5, 2]\n release_data = [5, 2]\n do_event(span, 'press', xdata=press_data[0], ydata=press_data[1], button=1)\n do_event(span, 'onmove', xdata=move_data[0], ydata=move_data[1], button=1)\n assert ln.stale is False\n assert ln2.stale\n assert_allclose(ln2.get_ydata(), -0.9424150707548072)\n do_event(span, 'release', xdata=release_data[0],\n ydata=release_data[1], button=1)\n assert ln2.stale is False\n\n\ndef test_snapping_values_span_selector(ax):\n def onselect(*args):\n pass\n\n tool = widgets.SpanSelector(ax, onselect, direction='horizontal',)\n snap_function = tool._snap\n\n snap_values = np.linspace(0, 5, 11)\n values = np.array([-0.1, 0.1, 0.2, 0.5, 0.6, 0.7, 0.9, 4.76, 5.0, 5.5])\n expect = np.array([00.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 5.00, 5.0, 5.0])\n values = snap_function(values, snap_values)\n assert_allclose(values, expect)\n\n\ndef test_span_selector_snap(ax):\n def onselect(vmin, vmax):\n ax._got_onselect = True\n\n snap_values = np.arange(50) * 4\n\n tool = widgets.SpanSelector(ax, onselect, direction='horizontal',\n snap_values=snap_values)\n tool.extents = (17, 35)\n assert tool.extents == (16, 36)\n\n tool.snap_values = None\n assert tool.snap_values is None\n tool.extents = (17, 35)\n assert tool.extents == (17, 35)\n\n\ndef test_span_selector_extents(ax):\n tool = widgets.SpanSelector(\n ax, lambda a, b: None, "horizontal", ignore_event_outside=True\n )\n tool.extents = (5, 10)\n\n assert tool.extents == (5, 10)\n assert tool._selection_completed\n\n # Since `ignore_event_outside=True`, this event should be ignored\n press_data = (12, 14)\n release_data = (20, 14)\n click_and_drag(tool, start=press_data, end=release_data)\n\n assert tool.extents == (5, 10)\n\n\n@pytest.mark.parametrize('kwargs', [\n dict(),\n dict(useblit=False, props=dict(color='red')),\n dict(useblit=True, button=1),\n])\ndef test_lasso_selector(ax, kwargs):\n onselect = mock.Mock(spec=noop, return_value=None)\n\n tool = widgets.LassoSelector(ax, onselect=onselect, **kwargs)\n do_event(tool, 'press', xdata=100, ydata=100, button=1)\n do_event(tool, 'onmove', xdata=125, ydata=125, button=1)\n do_event(tool, 'release', xdata=150, ydata=150, button=1)\n\n onselect.assert_called_once_with([(100, 100), (125, 125), (150, 150)])\n\n\ndef test_lasso_selector_set_props(ax):\n onselect = mock.Mock(spec=noop, return_value=None)\n\n tool = widgets.LassoSelector(ax, onselect=onselect,\n props=dict(color='b', alpha=0.2))\n\n artist = tool._selection_artist\n assert mcolors.same_color(artist.get_color(), 'b')\n assert artist.get_alpha() == 0.2\n tool.set_props(color='r', alpha=0.3)\n assert mcolors.same_color(artist.get_color(), 'r')\n assert artist.get_alpha() == 0.3\n\n\ndef test_lasso_set_props(ax):\n onselect = mock.Mock(spec=noop, return_value=None)\n tool = widgets.Lasso(ax, (100, 100), onselect)\n line = tool.line\n assert mcolors.same_color(line.get_color(), 'black')\n assert line.get_linestyle() == '-'\n assert line.get_lw() == 2\n tool = widgets.Lasso(ax, (100, 100), onselect, props=dict(\n linestyle='-', color='darkblue', alpha=0.2, lw=1))\n\n line = tool.line\n assert mcolors.same_color(line.get_color(), 'darkblue')\n assert line.get_alpha() == 0.2\n assert line.get_lw() == 1\n assert line.get_linestyle() == '-'\n line.set_color('r')\n line.set_alpha(0.3)\n assert mcolors.same_color(line.get_color(), 'r')\n assert line.get_alpha() == 0.3\n\n\ndef test_CheckButtons(ax):\n labels = ('a', 'b', 'c')\n check = widgets.CheckButtons(ax, labels, (True, False, True))\n assert check.get_status() == [True, False, True]\n check.set_active(0)\n assert check.get_status() == [False, False, True]\n assert check.get_checked_labels() == ['c']\n check.clear()\n assert check.get_status() == [False, False, False]\n assert check.get_checked_labels() == []\n\n for invalid_index in [-1, len(labels), len(labels)+5]:\n with pytest.raises(ValueError):\n check.set_active(index=invalid_index)\n\n for invalid_value in ['invalid', -1]:\n with pytest.raises(TypeError):\n check.set_active(1, state=invalid_value)\n\n cid = check.on_clicked(lambda: None)\n check.disconnect(cid)\n\n\n@pytest.mark.parametrize("toolbar", ["none", "toolbar2", "toolmanager"])\ndef test_TextBox(ax, toolbar):\n # Avoid "toolmanager is provisional" warning.\n plt.rcParams._set("toolbar", toolbar)\n\n submit_event = mock.Mock(spec=noop, return_value=None)\n text_change_event = mock.Mock(spec=noop, return_value=None)\n tool = widgets.TextBox(ax, '')\n tool.on_submit(submit_event)\n tool.on_text_change(text_change_event)\n\n assert tool.text == ''\n\n do_event(tool, '_click')\n\n tool.set_val('x**2')\n\n assert tool.text == 'x**2'\n assert text_change_event.call_count == 1\n\n tool.begin_typing()\n tool.stop_typing()\n\n assert submit_event.call_count == 2\n\n do_event(tool, '_click', xdata=.5, ydata=.5) # Ensure the click is in the axes.\n do_event(tool, '_keypress', key='+')\n do_event(tool, '_keypress', key='5')\n\n assert text_change_event.call_count == 3\n\n\ndef test_RadioButtons(ax):\n radio = widgets.RadioButtons(ax, ('Radio 1', 'Radio 2', 'Radio 3'))\n radio.set_active(1)\n assert radio.value_selected == 'Radio 2'\n assert radio.index_selected == 1\n radio.clear()\n assert radio.value_selected == 'Radio 1'\n assert radio.index_selected == 0\n\n\n@image_comparison(['check_radio_buttons.png'], style='mpl20', remove_text=True)\ndef test_check_radio_buttons_image():\n ax = get_ax()\n fig = ax.get_figure(root=False)\n fig.subplots_adjust(left=0.3)\n\n rax1 = fig.add_axes((0.05, 0.7, 0.2, 0.15))\n rb1 = widgets.RadioButtons(rax1, ('Radio 1', 'Radio 2', 'Radio 3'))\n\n rax2 = fig.add_axes((0.05, 0.5, 0.2, 0.15))\n cb1 = widgets.CheckButtons(rax2, ('Check 1', 'Check 2', 'Check 3'),\n (False, True, True))\n\n rax3 = fig.add_axes((0.05, 0.3, 0.2, 0.15))\n rb3 = widgets.RadioButtons(\n rax3, ('Radio 1', 'Radio 2', 'Radio 3'),\n label_props={'fontsize': [8, 12, 16],\n 'color': ['red', 'green', 'blue']},\n radio_props={'edgecolor': ['red', 'green', 'blue'],\n 'facecolor': ['mistyrose', 'palegreen', 'lightblue']})\n\n rax4 = fig.add_axes((0.05, 0.1, 0.2, 0.15))\n cb4 = widgets.CheckButtons(\n rax4, ('Check 1', 'Check 2', 'Check 3'), (False, True, True),\n label_props={'fontsize': [8, 12, 16],\n 'color': ['red', 'green', 'blue']},\n frame_props={'edgecolor': ['red', 'green', 'blue'],\n 'facecolor': ['mistyrose', 'palegreen', 'lightblue']},\n check_props={'color': ['red', 'green', 'blue']})\n\n\n@check_figures_equal(extensions=["png"])\ndef test_radio_buttons(fig_test, fig_ref):\n widgets.RadioButtons(fig_test.subplots(), ["tea", "coffee"])\n ax = fig_ref.add_subplot(xticks=[], yticks=[])\n ax.scatter([.15, .15], [2/3, 1/3], transform=ax.transAxes,\n s=(plt.rcParams["font.size"] / 2) ** 2, c=["C0", "none"])\n ax.text(.25, 2/3, "tea", transform=ax.transAxes, va="center")\n ax.text(.25, 1/3, "coffee", transform=ax.transAxes, va="center")\n\n\n@check_figures_equal(extensions=['png'])\ndef test_radio_buttons_props(fig_test, fig_ref):\n label_props = {'color': ['red'], 'fontsize': [24]}\n radio_props = {'facecolor': 'green', 'edgecolor': 'blue', 'linewidth': 2}\n\n widgets.RadioButtons(fig_ref.subplots(), ['tea', 'coffee'],\n label_props=label_props, radio_props=radio_props)\n\n cb = widgets.RadioButtons(fig_test.subplots(), ['tea', 'coffee'])\n cb.set_label_props(label_props)\n # Setting the label size automatically increases default marker size, so we\n # need to do that here as well.\n cb.set_radio_props({**radio_props, 's': (24 / 2)**2})\n\n\ndef test_radio_button_active_conflict(ax):\n with pytest.warns(UserWarning,\n match=r'Both the \*activecolor\* parameter'):\n rb = widgets.RadioButtons(ax, ['tea', 'coffee'], activecolor='red',\n radio_props={'facecolor': 'green'})\n # *radio_props*' facecolor wins over *activecolor*\n assert mcolors.same_color(rb._buttons.get_facecolor(), ['green', 'none'])\n\n\n@check_figures_equal(extensions=['png'])\ndef test_radio_buttons_activecolor_change(fig_test, fig_ref):\n widgets.RadioButtons(fig_ref.subplots(), ['tea', 'coffee'],\n activecolor='green')\n\n # Test property setter.\n cb = widgets.RadioButtons(fig_test.subplots(), ['tea', 'coffee'],\n activecolor='red')\n cb.activecolor = 'green'\n\n\n@check_figures_equal(extensions=["png"])\ndef test_check_buttons(fig_test, fig_ref):\n widgets.CheckButtons(fig_test.subplots(), ["tea", "coffee"], [True, True])\n ax = fig_ref.add_subplot(xticks=[], yticks=[])\n ax.scatter([.15, .15], [2/3, 1/3], marker='s', transform=ax.transAxes,\n s=(plt.rcParams["font.size"] / 2) ** 2, c=["none", "none"])\n ax.scatter([.15, .15], [2/3, 1/3], marker='x', transform=ax.transAxes,\n s=(plt.rcParams["font.size"] / 2) ** 2, c=["k", "k"])\n ax.text(.25, 2/3, "tea", transform=ax.transAxes, va="center")\n ax.text(.25, 1/3, "coffee", transform=ax.transAxes, va="center")\n\n\n@check_figures_equal(extensions=['png'])\ndef test_check_button_props(fig_test, fig_ref):\n label_props = {'color': ['red'], 'fontsize': [24]}\n frame_props = {'facecolor': 'green', 'edgecolor': 'blue', 'linewidth': 2}\n check_props = {'facecolor': 'red', 'linewidth': 2}\n\n widgets.CheckButtons(fig_ref.subplots(), ['tea', 'coffee'], [True, True],\n label_props=label_props, frame_props=frame_props,\n check_props=check_props)\n\n cb = widgets.CheckButtons(fig_test.subplots(), ['tea', 'coffee'],\n [True, True])\n cb.set_label_props(label_props)\n # Setting the label size automatically increases default marker size, so we\n # need to do that here as well.\n cb.set_frame_props({**frame_props, 's': (24 / 2)**2})\n # FIXME: Axes.scatter promotes facecolor to edgecolor on unfilled markers,\n # but Collection.update doesn't do that (it forgot the marker already).\n # This means we cannot pass facecolor to both setters directly.\n check_props['edgecolor'] = check_props.pop('facecolor')\n cb.set_check_props({**check_props, 's': (24 / 2)**2})\n\n\ndef test_slider_slidermin_slidermax_invalid():\n fig, ax = plt.subplots()\n # test min/max with floats\n with pytest.raises(ValueError):\n widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,\n slidermin=10.0)\n with pytest.raises(ValueError):\n widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,\n slidermax=10.0)\n\n\ndef test_slider_slidermin_slidermax():\n fig, ax = plt.subplots()\n slider_ = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,\n valinit=5.0)\n\n slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,\n valinit=1.0, slidermin=slider_)\n assert slider.val == slider_.val\n\n slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,\n valinit=10.0, slidermax=slider_)\n assert slider.val == slider_.val\n\n\ndef test_slider_valmin_valmax():\n fig, ax = plt.subplots()\n slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,\n valinit=-10.0)\n assert slider.val == slider.valmin\n\n slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,\n valinit=25.0)\n assert slider.val == slider.valmax\n\n\ndef test_slider_valstep_snapping():\n fig, ax = plt.subplots()\n slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,\n valinit=11.4, valstep=1)\n assert slider.val == 11\n\n slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,\n valinit=11.4, valstep=[0, 1, 5.5, 19.7])\n assert slider.val == 5.5\n\n\ndef test_slider_horizontal_vertical():\n fig, ax = plt.subplots()\n slider = widgets.Slider(ax=ax, label='', valmin=0, valmax=24,\n valinit=12, orientation='horizontal')\n slider.set_val(10)\n assert slider.val == 10\n # check the dimension of the slider patch in axes units\n box = slider.poly.get_extents().transformed(ax.transAxes.inverted())\n assert_allclose(box.bounds, [0, .25, 10/24, .5])\n\n fig, ax = plt.subplots()\n slider = widgets.Slider(ax=ax, label='', valmin=0, valmax=24,\n valinit=12, orientation='vertical')\n slider.set_val(10)\n assert slider.val == 10\n # check the dimension of the slider patch in axes units\n box = slider.poly.get_extents().transformed(ax.transAxes.inverted())\n assert_allclose(box.bounds, [.25, 0, .5, 10/24])\n\n\ndef test_slider_reset():\n fig, ax = plt.subplots()\n slider = widgets.Slider(ax=ax, label='', valmin=0, valmax=1, valinit=.5)\n slider.set_val(0.75)\n slider.reset()\n assert slider.val == 0.5\n\n\n@pytest.mark.parametrize("orientation", ["horizontal", "vertical"])\ndef test_range_slider(orientation):\n if orientation == "vertical":\n idx = [1, 0, 3, 2]\n else:\n idx = [0, 1, 2, 3]\n\n fig, ax = plt.subplots()\n\n slider = widgets.RangeSlider(\n ax=ax, label="", valmin=0.0, valmax=1.0, orientation=orientation,\n valinit=[0.1, 0.34]\n )\n box = slider.poly.get_extents().transformed(ax.transAxes.inverted())\n assert_allclose(box.get_points().flatten()[idx], [0.1, 0.25, 0.34, 0.75])\n\n # Check initial value is set correctly\n assert_allclose(slider.val, (0.1, 0.34))\n\n def handle_positions(slider):\n if orientation == "vertical":\n return [h.get_ydata()[0] for h in slider._handles]\n else:\n return [h.get_xdata()[0] for h in slider._handles]\n\n slider.set_val((0.4, 0.6))\n assert_allclose(slider.val, (0.4, 0.6))\n assert_allclose(handle_positions(slider), (0.4, 0.6))\n\n box = slider.poly.get_extents().transformed(ax.transAxes.inverted())\n assert_allclose(box.get_points().flatten()[idx], [0.4, .25, 0.6, .75])\n\n slider.set_val((0.2, 0.1))\n assert_allclose(slider.val, (0.1, 0.2))\n assert_allclose(handle_positions(slider), (0.1, 0.2))\n\n slider.set_val((-1, 10))\n assert_allclose(slider.val, (0, 1))\n assert_allclose(handle_positions(slider), (0, 1))\n\n slider.reset()\n assert_allclose(slider.val, (0.1, 0.34))\n assert_allclose(handle_positions(slider), (0.1, 0.34))\n\n\n@pytest.mark.parametrize("orientation", ["horizontal", "vertical"])\ndef test_range_slider_same_init_values(orientation):\n if orientation == "vertical":\n idx = [1, 0, 3, 2]\n else:\n idx = [0, 1, 2, 3]\n\n fig, ax = plt.subplots()\n\n slider = widgets.RangeSlider(\n ax=ax, label="", valmin=0.0, valmax=1.0, orientation=orientation,\n valinit=[0, 0]\n )\n box = slider.poly.get_extents().transformed(ax.transAxes.inverted())\n assert_allclose(box.get_points().flatten()[idx], [0, 0.25, 0, 0.75])\n\n\ndef check_polygon_selector(event_sequence, expected_result, selections_count,\n **kwargs):\n """\n Helper function to test Polygon Selector.\n\n Parameters\n ----------\n event_sequence : list of tuples (etype, dict())\n A sequence of events to perform. The sequence is a list of tuples\n where the first element of the tuple is an etype (e.g., 'onmove',\n 'press', etc.), and the second element of the tuple is a dictionary of\n the arguments for the event (e.g., xdata=5, key='shift', etc.).\n expected_result : list of vertices (xdata, ydata)\n The list of vertices that are expected to result from the event\n sequence.\n selections_count : int\n Wait for the tool to call its `onselect` function `selections_count`\n times, before comparing the result to the `expected_result`\n **kwargs\n Keyword arguments are passed to PolygonSelector.\n """\n ax = get_ax()\n\n onselect = mock.Mock(spec=noop, return_value=None)\n\n tool = widgets.PolygonSelector(ax, onselect=onselect, **kwargs)\n\n for (etype, event_args) in event_sequence:\n do_event(tool, etype, **event_args)\n\n assert onselect.call_count == selections_count\n assert onselect.call_args == ((expected_result, ), {})\n\n\ndef polygon_place_vertex(xdata, ydata):\n return [('onmove', dict(xdata=xdata, ydata=ydata)),\n ('press', dict(xdata=xdata, ydata=ydata)),\n ('release', dict(xdata=xdata, ydata=ydata))]\n\n\ndef polygon_remove_vertex(xdata, ydata):\n return [('onmove', dict(xdata=xdata, ydata=ydata)),\n ('press', dict(xdata=xdata, ydata=ydata, button=3)),\n ('release', dict(xdata=xdata, ydata=ydata, button=3))]\n\n\n@pytest.mark.parametrize('draw_bounding_box', [False, True])\ndef test_polygon_selector(draw_bounding_box):\n check_selector = functools.partial(\n check_polygon_selector, draw_bounding_box=draw_bounding_box)\n\n # Simple polygon\n expected_result = [(50, 50), (150, 50), (50, 150)]\n event_sequence = [\n *polygon_place_vertex(50, 50),\n *polygon_place_vertex(150, 50),\n *polygon_place_vertex(50, 150),\n *polygon_place_vertex(50, 50),\n ]\n check_selector(event_sequence, expected_result, 1)\n\n # Move first vertex before completing the polygon.\n expected_result = [(75, 50), (150, 50), (50, 150)]\n event_sequence = [\n *polygon_place_vertex(50, 50),\n *polygon_place_vertex(150, 50),\n ('on_key_press', dict(key='control')),\n ('onmove', dict(xdata=50, ydata=50)),\n ('press', dict(xdata=50, ydata=50)),\n ('onmove', dict(xdata=75, ydata=50)),\n ('release', dict(xdata=75, ydata=50)),\n ('on_key_release', dict(key='control')),\n *polygon_place_vertex(50, 150),\n *polygon_place_vertex(75, 50),\n ]\n check_selector(event_sequence, expected_result, 1)\n\n # Move first two vertices at once before completing the polygon.\n expected_result = [(50, 75), (150, 75), (50, 150)]\n event_sequence = [\n *polygon_place_vertex(50, 50),\n *polygon_place_vertex(150, 50),\n ('on_key_press', dict(key='shift')),\n ('onmove', dict(xdata=100, ydata=100)),\n ('press', dict(xdata=100, ydata=100)),\n ('onmove', dict(xdata=100, ydata=125)),\n ('release', dict(xdata=100, ydata=125)),\n ('on_key_release', dict(key='shift')),\n *polygon_place_vertex(50, 150),\n *polygon_place_vertex(50, 75),\n ]\n check_selector(event_sequence, expected_result, 1)\n\n # Move first vertex after completing the polygon.\n expected_result = [(75, 50), (150, 50), (50, 150)]\n event_sequence = [\n *polygon_place_vertex(50, 50),\n *polygon_place_vertex(150, 50),\n *polygon_place_vertex(50, 150),\n *polygon_place_vertex(50, 50),\n ('onmove', dict(xdata=50, ydata=50)),\n ('press', dict(xdata=50, ydata=50)),\n ('onmove', dict(xdata=75, ydata=50)),\n ('release', dict(xdata=75, ydata=50)),\n ]\n check_selector(event_sequence, expected_result, 2)\n\n # Move all vertices after completing the polygon.\n expected_result = [(75, 75), (175, 75), (75, 175)]\n event_sequence = [\n *polygon_place_vertex(50, 50),\n *polygon_place_vertex(150, 50),\n *polygon_place_vertex(50, 150),\n *polygon_place_vertex(50, 50),\n ('on_key_press', dict(key='shift')),\n ('onmove', dict(xdata=100, ydata=100)),\n ('press', dict(xdata=100, ydata=100)),\n ('onmove', dict(xdata=125, ydata=125)),\n ('release', dict(xdata=125, ydata=125)),\n ('on_key_release', dict(key='shift')),\n ]\n check_selector(event_sequence, expected_result, 2)\n\n # Try to move a vertex and move all before placing any vertices.\n expected_result = [(50, 50), (150, 50), (50, 150)]\n event_sequence = [\n ('on_key_press', dict(key='control')),\n ('onmove', dict(xdata=100, ydata=100)),\n ('press', dict(xdata=100, ydata=100)),\n ('onmove', dict(xdata=125, ydata=125)),\n ('release', dict(xdata=125, ydata=125)),\n ('on_key_release', dict(key='control')),\n ('on_key_press', dict(key='shift')),\n ('onmove', dict(xdata=100, ydata=100)),\n ('press', dict(xdata=100, ydata=100)),\n ('onmove', dict(xdata=125, ydata=125)),\n ('release', dict(xdata=125, ydata=125)),\n ('on_key_release', dict(key='shift')),\n *polygon_place_vertex(50, 50),\n *polygon_place_vertex(150, 50),\n *polygon_place_vertex(50, 150),\n *polygon_place_vertex(50, 50),\n ]\n check_selector(event_sequence, expected_result, 1)\n\n # Try to place vertex out-of-bounds, then reset, and start a new polygon.\n expected_result = [(50, 50), (150, 50), (50, 150)]\n event_sequence = [\n *polygon_place_vertex(50, 50),\n *polygon_place_vertex(250, 50),\n ('on_key_press', dict(key='escape')),\n ('on_key_release', dict(key='escape')),\n *polygon_place_vertex(50, 50),\n *polygon_place_vertex(150, 50),\n *polygon_place_vertex(50, 150),\n *polygon_place_vertex(50, 50),\n ]\n check_selector(event_sequence, expected_result, 1)\n\n\n@pytest.mark.parametrize('draw_bounding_box', [False, True])\ndef test_polygon_selector_set_props_handle_props(ax, draw_bounding_box):\n tool = widgets.PolygonSelector(ax,\n props=dict(color='b', alpha=0.2),\n handle_props=dict(alpha=0.5),\n draw_bounding_box=draw_bounding_box)\n\n event_sequence = [\n *polygon_place_vertex(50, 50),\n *polygon_place_vertex(150, 50),\n *polygon_place_vertex(50, 150),\n *polygon_place_vertex(50, 50),\n ]\n\n for (etype, event_args) in event_sequence:\n do_event(tool, etype, **event_args)\n\n artist = tool._selection_artist\n assert artist.get_color() == 'b'\n assert artist.get_alpha() == 0.2\n tool.set_props(color='r', alpha=0.3)\n assert artist.get_color() == 'r'\n assert artist.get_alpha() == 0.3\n\n for artist in tool._handles_artists:\n assert artist.get_color() == 'b'\n assert artist.get_alpha() == 0.5\n tool.set_handle_props(color='r', alpha=0.3)\n for artist in tool._handles_artists:\n assert artist.get_color() == 'r'\n assert artist.get_alpha() == 0.3\n\n\n@check_figures_equal(extensions=['png'])\ndef test_rect_visibility(fig_test, fig_ref):\n # Check that requesting an invisible selector makes it invisible\n ax_test = fig_test.subplots()\n _ = fig_ref.subplots()\n\n tool = widgets.RectangleSelector(ax_test, props={'visible': False})\n tool.extents = (0.2, 0.8, 0.3, 0.7)\n\n\n# Change the order that the extra point is inserted in\n@pytest.mark.parametrize('idx', [1, 2, 3])\n@pytest.mark.parametrize('draw_bounding_box', [False, True])\ndef test_polygon_selector_remove(idx, draw_bounding_box):\n verts = [(50, 50), (150, 50), (50, 150)]\n event_sequence = [polygon_place_vertex(*verts[0]),\n polygon_place_vertex(*verts[1]),\n polygon_place_vertex(*verts[2]),\n # Finish the polygon\n polygon_place_vertex(*verts[0])]\n # Add an extra point\n event_sequence.insert(idx, polygon_place_vertex(200, 200))\n # Remove the extra point\n event_sequence.append(polygon_remove_vertex(200, 200))\n # Flatten list of lists\n event_sequence = functools.reduce(operator.iadd, event_sequence, [])\n check_polygon_selector(event_sequence, verts, 2,\n draw_bounding_box=draw_bounding_box)\n\n\n@pytest.mark.parametrize('draw_bounding_box', [False, True])\ndef test_polygon_selector_remove_first_point(draw_bounding_box):\n verts = [(50, 50), (150, 50), (50, 150)]\n event_sequence = [\n *polygon_place_vertex(*verts[0]),\n *polygon_place_vertex(*verts[1]),\n *polygon_place_vertex(*verts[2]),\n *polygon_place_vertex(*verts[0]),\n *polygon_remove_vertex(*verts[0]),\n ]\n check_polygon_selector(event_sequence, verts[1:], 2,\n draw_bounding_box=draw_bounding_box)\n\n\n@pytest.mark.parametrize('draw_bounding_box', [False, True])\ndef test_polygon_selector_redraw(ax, draw_bounding_box):\n verts = [(50, 50), (150, 50), (50, 150)]\n event_sequence = [\n *polygon_place_vertex(*verts[0]),\n *polygon_place_vertex(*verts[1]),\n *polygon_place_vertex(*verts[2]),\n *polygon_place_vertex(*verts[0]),\n # Polygon completed, now remove first two verts.\n *polygon_remove_vertex(*verts[1]),\n *polygon_remove_vertex(*verts[2]),\n # At this point the tool should be reset so we can add more vertices.\n *polygon_place_vertex(*verts[1]),\n ]\n\n tool = widgets.PolygonSelector(ax, draw_bounding_box=draw_bounding_box)\n for (etype, event_args) in event_sequence:\n do_event(tool, etype, **event_args)\n # After removing two verts, only one remains, and the\n # selector should be automatically resete\n assert tool.verts == verts[0:2]\n\n\n@pytest.mark.parametrize('draw_bounding_box', [False, True])\n@check_figures_equal(extensions=['png'])\ndef test_polygon_selector_verts_setter(fig_test, fig_ref, draw_bounding_box):\n verts = [(0.1, 0.4), (0.5, 0.9), (0.3, 0.2)]\n ax_test = fig_test.add_subplot()\n\n tool_test = widgets.PolygonSelector(ax_test, draw_bounding_box=draw_bounding_box)\n tool_test.verts = verts\n assert tool_test.verts == verts\n\n ax_ref = fig_ref.add_subplot()\n tool_ref = widgets.PolygonSelector(ax_ref, draw_bounding_box=draw_bounding_box)\n event_sequence = [\n *polygon_place_vertex(*verts[0]),\n *polygon_place_vertex(*verts[1]),\n *polygon_place_vertex(*verts[2]),\n *polygon_place_vertex(*verts[0]),\n ]\n for (etype, event_args) in event_sequence:\n do_event(tool_ref, etype, **event_args)\n\n\ndef test_polygon_selector_box(ax):\n # Create a diamond (adjusting axes lims s.t. the diamond lies within axes limits).\n ax.set(xlim=(-10, 50), ylim=(-10, 50))\n verts = [(20, 0), (0, 20), (20, 40), (40, 20)]\n event_sequence = [\n *polygon_place_vertex(*verts[0]),\n *polygon_place_vertex(*verts[1]),\n *polygon_place_vertex(*verts[2]),\n *polygon_place_vertex(*verts[3]),\n *polygon_place_vertex(*verts[0]),\n ]\n\n # Create selector\n tool = widgets.PolygonSelector(ax, draw_bounding_box=True)\n for (etype, event_args) in event_sequence:\n do_event(tool, etype, **event_args)\n\n # In order to trigger the correct callbacks, trigger events on the canvas\n # instead of the individual tools\n t = ax.transData\n canvas = ax.get_figure(root=True).canvas\n\n # Scale to half size using the top right corner of the bounding box\n MouseEvent(\n "button_press_event", canvas, *t.transform((40, 40)), 1)._process()\n MouseEvent(\n "motion_notify_event", canvas, *t.transform((20, 20)))._process()\n MouseEvent(\n "button_release_event", canvas, *t.transform((20, 20)), 1)._process()\n np.testing.assert_allclose(\n tool.verts, [(10, 0), (0, 10), (10, 20), (20, 10)])\n\n # Move using the center of the bounding box\n MouseEvent(\n "button_press_event", canvas, *t.transform((10, 10)), 1)._process()\n MouseEvent(\n "motion_notify_event", canvas, *t.transform((30, 30)))._process()\n MouseEvent(\n "button_release_event", canvas, *t.transform((30, 30)), 1)._process()\n np.testing.assert_allclose(\n tool.verts, [(30, 20), (20, 30), (30, 40), (40, 30)])\n\n # Remove a point from the polygon and check that the box extents update\n np.testing.assert_allclose(\n tool._box.extents, (20.0, 40.0, 20.0, 40.0))\n\n MouseEvent(\n "button_press_event", canvas, *t.transform((30, 20)), 3)._process()\n MouseEvent(\n "button_release_event", canvas, *t.transform((30, 20)), 3)._process()\n np.testing.assert_allclose(\n tool.verts, [(20, 30), (30, 40), (40, 30)])\n np.testing.assert_allclose(\n tool._box.extents, (20.0, 40.0, 30.0, 40.0))\n\n\ndef test_polygon_selector_clear_method(ax):\n onselect = mock.Mock(spec=noop, return_value=None)\n tool = widgets.PolygonSelector(ax, onselect)\n\n for result in ([(50, 50), (150, 50), (50, 150), (50, 50)],\n [(50, 50), (100, 50), (50, 150), (50, 50)]):\n for x, y in result:\n for etype, event_args in polygon_place_vertex(x, y):\n do_event(tool, etype, **event_args)\n\n artist = tool._selection_artist\n\n assert tool._selection_completed\n assert tool.get_visible()\n assert artist.get_visible()\n np.testing.assert_equal(artist.get_xydata(), result)\n assert onselect.call_args == ((result[:-1],), {})\n\n tool.clear()\n assert not tool._selection_completed\n np.testing.assert_equal(artist.get_xydata(), [(0, 0)])\n\n\n@pytest.mark.parametrize("horizOn", [False, True])\n@pytest.mark.parametrize("vertOn", [False, True])\ndef test_MultiCursor(horizOn, vertOn):\n fig = plt.figure()\n (ax1, ax3) = fig.subplots(2, sharex=True)\n ax2 = plt.figure().subplots()\n\n # useblit=false to avoid having to draw the figure to cache the renderer\n multi = widgets.MultiCursor(\n None, (ax1, ax2), useblit=False, horizOn=horizOn, vertOn=vertOn\n )\n\n # Only two of the axes should have a line drawn on them.\n assert len(multi.vlines) == 2\n assert len(multi.hlines) == 2\n\n # mock a motion_notify_event\n # Can't use `do_event` as that helper requires the widget\n # to have a single .ax attribute.\n event = mock_event(ax1, xdata=.5, ydata=.25)\n multi.onmove(event)\n # force a draw + draw event to exercise clear\n fig.canvas.draw()\n\n # the lines in the first two ax should both move\n for l in multi.vlines:\n assert l.get_xdata() == (.5, .5)\n for l in multi.hlines:\n assert l.get_ydata() == (.25, .25)\n # The relevant lines get turned on after move.\n assert len([line for line in multi.vlines if line.get_visible()]) == (\n 2 if vertOn else 0)\n assert len([line for line in multi.hlines if line.get_visible()]) == (\n 2 if horizOn else 0)\n\n # After toggling settings, the opposite lines should be visible after move.\n multi.horizOn = not multi.horizOn\n multi.vertOn = not multi.vertOn\n event = mock_event(ax1, xdata=.5, ydata=.25)\n multi.onmove(event)\n assert len([line for line in multi.vlines if line.get_visible()]) == (\n 0 if vertOn else 2)\n assert len([line for line in multi.hlines if line.get_visible()]) == (\n 0 if horizOn else 2)\n\n # test a move event in an Axes not part of the MultiCursor\n # the lines in ax1 and ax2 should not have moved.\n event = mock_event(ax3, xdata=.75, ydata=.75)\n multi.onmove(event)\n for l in multi.vlines:\n assert l.get_xdata() == (.5, .5)\n for l in multi.hlines:\n assert l.get_ydata() == (.25, .25)\n | .venv\Lib\site-packages\matplotlib\tests\test_widgets.py | test_widgets.py | Python | 66,435 | 0.75 | 0.077317 | 0.14107 | awesome-app | 369 | 2025-04-04T08:32:02.254367 | BSD-3-Clause | true | 9564785e15963bf88c1657bada457e67 |
from pathlib import Path\n\n\n# Check that the test directories exist.\nif not (Path(__file__).parent / 'baseline_images').exists():\n raise OSError(\n 'The baseline image directory does not exist. '\n 'This is most likely because the test data is not installed. '\n 'You may need to install matplotlib from source to get the '\n 'test data.')\n | .venv\Lib\site-packages\matplotlib\tests\__init__.py | __init__.py | Python | 366 | 0.95 | 0.1 | 0.125 | python-kit | 962 | 2023-09-04T10:04:56.400817 | MIT | true | 6a144190764d74d04b8003d5a73f36a5 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\conftest.cpython-313.pyc | conftest.cpython-313.pyc | Other | 388 | 0.7 | 0 | 0 | react-lib | 815 | 2023-12-26T18:25:57.688401 | GPL-3.0 | true | 873a5855c733070111023802333aa4f7 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_afm.cpython-313.pyc | test_afm.cpython-313.pyc | Other | 5,229 | 0.8 | 0 | 0.012195 | node-utils | 124 | 2024-09-25T00:32:58.150902 | GPL-3.0 | true | 43bacf4ac6a363b918fc8123c137866c |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_agg.cpython-313.pyc | test_agg.cpython-313.pyc | Other | 20,193 | 0.8 | 0 | 0.060773 | vue-tools | 473 | 2023-11-30T22:40:41.252093 | MIT | true | 2f25ab21e42176aed6bd14e5bb5aff10 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_agg_filter.cpython-313.pyc | test_agg_filter.cpython-313.pyc | Other | 1,508 | 0.8 | 0 | 0 | vue-tools | 644 | 2025-04-24T18:40:50.601766 | GPL-3.0 | true | 0202eb855df8a92d666255658ceb5f14 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_animation.cpython-313.pyc | test_animation.cpython-313.pyc | Other | 28,515 | 0.95 | 0.003401 | 0.010753 | react-lib | 343 | 2024-10-11T02:51:56.019953 | Apache-2.0 | true | 68713278c8836cf59f8d1c5be5a5db5f |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_api.cpython-313.pyc | test_api.cpython-313.pyc | Other | 11,215 | 0.95 | 0.011494 | 0 | react-lib | 976 | 2024-09-13T01:22:59.291623 | Apache-2.0 | true | 8d800b5a9dbe02926e839efc663e76dd |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_arrow_patches.cpython-313.pyc | test_arrow_patches.cpython-313.pyc | Other | 9,003 | 0.95 | 0.028302 | 0.030612 | python-kit | 954 | 2024-08-11T22:03:06.845530 | BSD-3-Clause | true | 4f838e6b33c2d28b51f26ceec40128cf |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_artist.cpython-313.pyc | test_artist.cpython-313.pyc | Other | 30,942 | 0.8 | 0.00813 | 0.039301 | awesome-app | 806 | 2023-10-11T18:03:46.257927 | MIT | true | 43018b29d9aa587299c6a0e99b89cfe8 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_axis.cpython-313.pyc | test_axis.cpython-313.pyc | Other | 2,455 | 0.8 | 0 | 0 | awesome-app | 557 | 2024-10-27T16:53:14.576992 | MIT | true | 6161a47759bb50501be316d758e18ef8 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backends_interactive.cpython-313.pyc | test_backends_interactive.cpython-313.pyc | Other | 39,702 | 0.95 | 0.006289 | 0.017182 | node-utils | 540 | 2025-06-24T20:41:05.336285 | MIT | true | 6cfe6fcedddd7ed7b153c86d846e8458 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_bases.cpython-313.pyc | test_backend_bases.cpython-313.pyc | Other | 35,380 | 0.95 | 0.00274 | 0.029762 | awesome-app | 704 | 2024-05-21T09:24:28.646771 | BSD-3-Clause | true | a5abbbaa07cd804df19fde9a2e15273e |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_cairo.cpython-313.pyc | test_backend_cairo.cpython-313.pyc | Other | 2,504 | 0.8 | 0 | 0.064516 | vue-tools | 185 | 2023-09-23T09:38:13.933554 | MIT | true | 9dcfda1f3a0fa3baf9862d5d1ce5cbe2 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_gtk3.cpython-313.pyc | test_backend_gtk3.cpython-313.pyc | Other | 4,774 | 0.95 | 0 | 0.021739 | react-lib | 303 | 2024-11-25T14:48:27.665081 | MIT | true | 77e8c288aad09f53d87683e97410ea65 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_inline.cpython-313.pyc | test_backend_inline.cpython-313.pyc | Other | 2,599 | 0.95 | 0 | 0 | awesome-app | 385 | 2024-02-05T11:46:57.198266 | BSD-3-Clause | true | ba13090cc585454ee3f5f56a0aa50351 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_macosx.cpython-313.pyc | test_backend_macosx.cpython-313.pyc | Other | 4,256 | 0.7 | 0 | 0.047619 | vue-tools | 443 | 2024-10-12T07:58:28.430752 | GPL-3.0 | true | 98c2b730d218be6c5b898ea1b163ab2b |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_nbagg.cpython-313.pyc | test_backend_nbagg.cpython-313.pyc | Other | 2,276 | 0.95 | 0 | 0 | awesome-app | 778 | 2025-03-17T22:52:46.973587 | GPL-3.0 | true | 051ec04077d122a27493e7975133c51d |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_pdf.cpython-313.pyc | test_backend_pdf.cpython-313.pyc | Other | 26,307 | 0.95 | 0.007782 | 0.046025 | node-utils | 672 | 2024-04-29T03:44:39.814074 | Apache-2.0 | true | e3e896aaf9aedc40190a25bc2bafe44d |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_pgf.cpython-313.pyc | test_backend_pgf.cpython-313.pyc | Other | 21,432 | 0.95 | 0 | 0.037838 | node-utils | 679 | 2024-12-16T04:48:15.329498 | MIT | true | d6ac327f8fca36dbf6a683da1bfbb73f |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_ps.cpython-313.pyc | test_backend_ps.cpython-313.pyc | Other | 21,351 | 0.8 | 0.011696 | 0.037736 | vue-tools | 444 | 2024-05-11T18:37:33.423521 | GPL-3.0 | true | 3613651188b7c2b595b8be8638eafd80 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_qt.cpython-313.pyc | test_backend_qt.cpython-313.pyc | Other | 19,515 | 0.95 | 0.005405 | 0.023529 | awesome-app | 84 | 2024-08-23T15:23:19.621625 | MIT | true | 87b6d3bf887e5295d8c719ffbfc77e06 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_registry.cpython-313.pyc | test_backend_registry.cpython-313.pyc | Other | 8,839 | 0.95 | 0 | 0 | awesome-app | 139 | 2024-06-07T19:35:27.396488 | Apache-2.0 | true | 93d968bac9c07e745f57b711f2ccf58a |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_svg.cpython-313.pyc | test_backend_svg.cpython-313.pyc | Other | 38,044 | 0.8 | 0.028777 | 0.033248 | vue-tools | 967 | 2024-03-15T03:09:31.515852 | GPL-3.0 | true | ce91f558f6b4f685ebf692a2c6e66612 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_template.cpython-313.pyc | test_backend_template.cpython-313.pyc | Other | 3,795 | 0.8 | 0 | 0 | node-utils | 683 | 2024-12-12T20:54:44.315460 | Apache-2.0 | true | 6733a6ffdd829d323e4e450daabc5a79 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_tk.cpython-313.pyc | test_backend_tk.cpython-313.pyc | Other | 13,885 | 0.95 | 0 | 0.027778 | react-lib | 616 | 2024-09-21T19:58:56.925314 | MIT | true | 4a423b77244338de8c2ef263c6e0a232 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_tools.cpython-313.pyc | test_backend_tools.cpython-313.pyc | Other | 853 | 0.7 | 0 | 0 | react-lib | 288 | 2024-07-22T21:15:39.354591 | BSD-3-Clause | true | 4e86ac60bee462c5e5c93058ba86fcf8 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_backend_webagg.cpython-313.pyc | test_backend_webagg.cpython-313.pyc | Other | 1,766 | 0.95 | 0 | 0 | react-lib | 232 | 2023-07-19T07:30:02.407763 | GPL-3.0 | true | 47fecc6af80f4e9a6e5873830aab1874 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_basic.cpython-313.pyc | test_basic.cpython-313.pyc | Other | 1,824 | 0.95 | 0 | 0 | node-utils | 879 | 2023-09-14T12:44:23.219808 | MIT | true | d2d8d6a6e70dc2b0d58b792fbf0be091 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_bbox_tight.cpython-313.pyc | test_bbox_tight.cpython-313.pyc | Other | 9,917 | 0.8 | 0 | 0.026667 | python-kit | 998 | 2025-06-10T19:55:40.913174 | Apache-2.0 | true | 3efd9ca3d8b0aa3b57b023ad11453868 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_bezier.cpython-313.pyc | test_bezier.cpython-313.pyc | Other | 672 | 0.8 | 0 | 0 | vue-tools | 228 | 2024-09-03T04:25:05.619199 | Apache-2.0 | true | 62ec0723b5aa908c893d005d466f723a |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_category.cpython-313.pyc | test_category.cpython-313.pyc | Other | 24,207 | 0.95 | 0.004587 | 0.004926 | vue-tools | 34 | 2023-10-08T03:06:52.429534 | GPL-3.0 | true | fbd3ab87ff03c6c2fddd40a619671cf4 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_cbook.cpython-313.pyc | test_cbook.cpython-313.pyc | Other | 59,645 | 0.6 | 0 | 0.034623 | vue-tools | 512 | 2024-01-17T17:51:09.287899 | MIT | true | 9849fca6155c6cb70f25c9435b8ba6d4 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_collections.cpython-313.pyc | test_collections.cpython-313.pyc | Other | 80,329 | 0.6 | 0 | 0.010695 | awesome-app | 346 | 2024-01-14T21:25:44.966378 | MIT | true | 0412cb325779b2589d20d9cb97750674 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_colorbar.cpython-313.pyc | test_colorbar.cpython-313.pyc | Other | 72,735 | 0.75 | 0.020968 | 0.010256 | awesome-app | 753 | 2023-12-27T01:38:13.108706 | MIT | true | 95a0b73882308a1e48dcc1e5e35aea42 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_colors.cpython-313.pyc | test_colors.cpython-313.pyc | Other | 95,892 | 0.6 | 0.012761 | 0.031439 | vue-tools | 459 | 2024-02-26T22:09:37.667815 | MIT | true | 7e60bfcd094b2c344c33eefdc4496f1b |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_compare_images.cpython-313.pyc | test_compare_images.cpython-313.pyc | Other | 2,106 | 0.7 | 0.071429 | 0 | awesome-app | 642 | 2023-07-23T13:11:18.751159 | Apache-2.0 | true | f441cdc92143cebc8b5de4d85f7b6c7f |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_constrainedlayout.cpython-313.pyc | test_constrainedlayout.cpython-313.pyc | Other | 40,455 | 0.8 | 0.036957 | 0.053269 | python-kit | 188 | 2024-06-04T22:02:28.130961 | BSD-3-Clause | true | 1b64bee8a079cecc2999409dad576373 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_container.cpython-313.pyc | test_container.cpython-313.pyc | Other | 1,748 | 0.8 | 0 | 0 | python-kit | 808 | 2024-08-22T22:43:00.231713 | Apache-2.0 | true | 1a27ff3b6c1fdd209894def54eacaa44 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_contour.cpython-313.pyc | test_contour.cpython-313.pyc | Other | 52,343 | 0.8 | 0 | 0.011719 | vue-tools | 794 | 2024-12-02T17:42:40.612974 | GPL-3.0 | true | 3d849b8b6a16e5424f439e30f186e0d4 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_cycles.cpython-313.pyc | test_cycles.cpython-313.pyc | Other | 13,523 | 0.8 | 0 | 0.006098 | vue-tools | 228 | 2023-10-21T19:20:47.326633 | Apache-2.0 | true | 41071ec11f5674f7d39aa2401c334022 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_dates.cpython-313.pyc | test_dates.cpython-313.pyc | Other | 80,715 | 0.75 | 0.005008 | 0.024306 | awesome-app | 956 | 2025-01-10T05:52:30.381888 | MIT | true | 1b26fceeaf7e2cd5b9af545b006121e0 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_datetime.cpython-313.pyc | test_datetime.cpython-313.pyc | Other | 57,931 | 0.6 | 0.027739 | 0.001468 | react-lib | 219 | 2024-01-31T19:37:36.065936 | Apache-2.0 | true | fdc1201a3cc9db5ced1fe754a517a42c |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_determinism.cpython-313.pyc | test_determinism.cpython-313.pyc | Other | 10,752 | 0.95 | 0.04 | 0.008475 | python-kit | 513 | 2024-02-06T07:36:27.880344 | Apache-2.0 | true | b3f7e68a73c04c8f52adf4345a28c089 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_doc.cpython-313.pyc | test_doc.cpython-313.pyc | Other | 1,337 | 0.85 | 0.064516 | 0 | awesome-app | 979 | 2023-10-07T06:39:23.908612 | Apache-2.0 | true | b6cb1e64e01de17b57bd61334aba1cba |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_dviread.cpython-313.pyc | test_dviread.cpython-313.pyc | Other | 4,885 | 0.8 | 0 | 0 | vue-tools | 366 | 2024-03-23T13:21:31.267186 | BSD-3-Clause | true | 1e99342296f91c4fd8fe5cf6b5bcf1d6 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_figure.cpython-313.pyc | test_figure.cpython-313.pyc | Other | 108,640 | 0.75 | 0.001614 | 0.064899 | vue-tools | 187 | 2024-11-18T10:23:26.166220 | Apache-2.0 | true | d1e7f94c9ce4a31e1f405bf17546ccb5 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_fontconfig_pattern.cpython-313.pyc | test_fontconfig_pattern.cpython-313.pyc | Other | 2,831 | 0.8 | 0.043478 | 0 | awesome-app | 364 | 2024-07-12T03:17:39.837778 | Apache-2.0 | true | b82725e61217c7f492ce975e2949cbcf |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_font_manager.cpython-313.pyc | test_font_manager.cpython-313.pyc | Other | 23,506 | 0.95 | 0.004673 | 0.039024 | awesome-app | 230 | 2024-09-24T22:11:25.134308 | Apache-2.0 | true | acb394e9a816421d328557e779d2bc43 |
\n\n | .venv\Lib\site-packages\matplotlib\tests\__pycache__\test_ft2font.cpython-313.pyc | test_ft2font.cpython-313.pyc | Other | 46,894 | 0.95 | 0.011475 | 0.003497 | awesome-app | 763 | 2023-11-02T00:33:01.644026 | BSD-3-Clause | true | a54f37c9b4460ec246d3b9437edcd216 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.