rgwfuncs 0.0.56__py3-none-any.whl → 0.0.57__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rgwfuncs/__init__.py CHANGED
@@ -1,7 +1,7 @@
1
1
  # This file is automatically generated
2
2
  # Dynamically importing functions from modules
3
3
 
4
- from .algebra_lib import cancel_polynomial_expression, compute_constant_expression, compute_constant_expression_involving_matrices, compute_constant_expression_involving_ordered_series, compute_prime_factors, expand_polynomial_expression, factor_polynomial_expression, plot_polynomial_functions, python_polynomial_expression_to_latex, simplify_polynomial_expression, solve_homogeneous_polynomial_expression
4
+ from .algebra_lib import cancel_polynomial_expression, compute_constant_expression, compute_constant_expression_involving_matrices, compute_constant_expression_involving_ordered_series, compute_prime_factors, expand_polynomial_expression, factor_polynomial_expression, plot_polynomial_functions, plot_x_points_of_polynomial_functions, python_polynomial_expression_to_latex, simplify_polynomial_expression, solve_homogeneous_polynomial_expression
5
5
  from .df_lib import append_columns, append_percentile_classification_column, append_ranged_classification_column, append_ranged_date_classification_column, append_rows, append_xgb_labels, append_xgb_logistic_regression_predictions, append_xgb_regression_predictions, bag_union_join, bottom_n_unique_values, cascade_sort, delete_rows, drop_duplicates, drop_duplicates_retain_first, drop_duplicates_retain_last, filter_dataframe, filter_indian_mobiles, first_n_rows, from_raw_data, insert_dataframe_in_sqlite_database, last_n_rows, left_join, limit_dataframe, load_data_from_path, load_data_from_query, load_data_from_sqlite_path, mask_against_dataframe, mask_against_dataframe_converse, numeric_clean, order_columns, print_correlation, print_dataframe, print_memory_usage, print_n_frequency_cascading, print_n_frequency_linear, rename_columns, retain_columns, right_join, send_data_to_email, send_data_to_slack, send_dataframe_via_telegram, sync_dataframe_to_sqlite_database, top_n_unique_values, union_join, update_rows
6
6
  from .docs_lib import docs
7
7
  from .interactive_shell_lib import interactive_shell
rgwfuncs/algebra_lib.py CHANGED
@@ -744,11 +744,11 @@ def plot_polynomial_functions(
744
744
  show_legend : bool
745
745
  Whether to add a legend to the plot (defaults to True).
746
746
  open_file : bool
747
- If saving to path is not desirable, opens the SVG as a temp file;
748
- otherwise opens the file from the actual location using the system's
747
+ If saving to path is not desirable, opens the SVG as a temp file;
748
+ otherwise opens the file from the actual location using the system's
749
749
  default viewer (defaults to False).
750
750
  save_path : Optional[str]
751
- If specified, saves the output string as a .svg at the indicated path
751
+ If specified, saves the output string as a .svg at the indicated path
752
752
  (defaults to None).
753
753
 
754
754
  Returns
@@ -899,3 +899,166 @@ def plot_polynomial_functions(
899
899
 
900
900
  return svg_string
901
901
 
902
+
903
+ def plot_x_points_of_polynomial_functions(
904
+ functions: List[Dict[str, Dict[str, Any]]],
905
+ zoom: float = 10.0,
906
+ show_legend: bool = True,
907
+ open_file: bool = False,
908
+ save_path: Optional[str] = None,
909
+ ) -> str:
910
+ """
911
+ Plots one or more expressions described by a list of dictionaries. For each
912
+ item in the list, the function evaluates the given Python/NumPy expression
913
+ at the specified x-values (converted to NumPy arrays if they are Python lists)
914
+ and plots the resulting points on a single figure.
915
+
916
+ Parameters
917
+ ----------
918
+ functions : List[Dict[str, Dict[str, Any]]] A list of one or more items,
919
+ each of which has exactly one key-value pair:
920
+ - Key (`str`): A valid Python/NumPy expression (e.g., `x**2`,
921
+ `np.sin(x)`, `x - a`).
922
+ - Value (`Dict[str, Any]`): Must assign `x` a value
923
+ zoom : float, optional
924
+ Determines the numeric axis range from -zoom..+zoom in both x and y
925
+ (default is 10.0).
926
+ show_legend : bool, optional
927
+ Whether to include a legend in the plot (default is True).
928
+ open_file : bool, optional
929
+ If saving to path is not desirable, opens the SVG as a temp file;
930
+ otherwise opens the file from the indicated path using the system's
931
+ default viewer (defaults to False).
932
+ save_path : Optional[str], optional
933
+ If specified, saves the output SVG at the given path (defaults to None).
934
+
935
+ Returns
936
+ -------
937
+ str
938
+ The raw SVG markup of the resulting scatter plot.
939
+
940
+ """
941
+ def latexify_expression(expr_str: str) -> str:
942
+ # Regex to locate np.diff(...) with an optional second argument
943
+ DIFF_PATTERN = r"np\.diff\s*\(\s*([^,\)]+)(?:,\s*(\d+))?\)"
944
+
945
+ def diff_replacer(match: re.Match) -> str:
946
+ inside = match.group(1).strip()
947
+ exponent = match.group(2)
948
+ inside_no_np = inside.replace("np.", "")
949
+ if exponent:
950
+ return rf"\Delta^{exponent}\left({inside_no_np}\right)"
951
+ else:
952
+ return rf"\Delta\left({inside_no_np}\right)"
953
+
954
+ expr_tmp = re.sub(DIFF_PATTERN, diff_replacer, expr_str)
955
+ expr_tmp = expr_tmp.replace("np.", "")
956
+
957
+ # Attempt to convert basic Pythonic polynomial expressions into LaTeX
958
+ try:
959
+ from python_latex_helpers import python_polynomial_expression_to_latex
960
+ latex_expr = python_polynomial_expression_to_latex(expr_tmp)
961
+ return latex_expr
962
+ except Exception:
963
+ # Fallback: naive ** -> ^
964
+ return expr_tmp.replace("**", "^")
965
+
966
+ def handle_open_and_save(svg_string: str, open_it: bool, path: Optional[str]) -> None:
967
+ # Save the SVG to a file if a path is provided
968
+ if path:
969
+ try:
970
+ with open(path, 'w', encoding='utf-8') as file:
971
+ file.write(svg_string)
972
+ print(f"[INFO] SVG saved to: {path}")
973
+ except IOError as e:
974
+ print(f"[ERROR] Failed to save SVG to {path}. IOError: {e}")
975
+
976
+ # Handle opening the file if requested
977
+ if open_it and path:
978
+ result = subprocess.run(["xdg-open", path], stderr=subprocess.DEVNULL)
979
+ if result.returncode != 0:
980
+ print("[ERROR] Failed to open the SVG file with the default viewer.")
981
+ elif open_it:
982
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".svg") as tmpfile:
983
+ temp_svg_path = tmpfile.name
984
+ tmpfile.write(svg_string.encode('utf-8'))
985
+ result = subprocess.run(["xdg-open", temp_svg_path], stderr=subprocess.DEVNULL)
986
+ if result.returncode != 0:
987
+ print("[ERROR] Failed to open the SVG file with the default viewer.")
988
+
989
+ # Set up a buffer for the SVG output
990
+ buffer = BytesIO()
991
+ fig, ax = plt.subplots()
992
+
993
+ # Iterate over each expression-substitution dictionary
994
+ for item in functions:
995
+ # Each entry in 'functions' must have exactly one key-value pair
996
+ if len(item) != 1:
997
+ print("[WARNING] Skipping invalid item. It must have exactly 1 expression->substitutions pair.")
998
+ continue
999
+
1000
+ expression, sub_dict = next(iter(item.items()))
1001
+
1002
+ # Ensure 'x' is present
1003
+ if "x" not in sub_dict:
1004
+ print(f"[WARNING] Skipping '{expression}' because there is no 'x' key.")
1005
+ continue
1006
+
1007
+ x_vals = sub_dict["x"]
1008
+ # Convert to numpy array if needed
1009
+ if not isinstance(x_vals, np.ndarray):
1010
+ x_vals = np.array(x_vals)
1011
+
1012
+ # Evaluate expression with the given variables
1013
+ try:
1014
+ eval_context = {"np": np}
1015
+ eval_context.update(sub_dict) # put all user-provided variables in the context
1016
+ y_vals = eval(expression, {"np": np}, eval_context)
1017
+ except Exception as e:
1018
+ print(f"[ERROR] Could not evaluate expression '{expression}': {e}")
1019
+ continue
1020
+
1021
+ # Convert y-values to a numpy array if needed
1022
+ if not isinstance(y_vals, np.ndarray):
1023
+ y_vals = np.array(y_vals)
1024
+
1025
+ # Prepare label (LaTeXified)
1026
+ label_expr = latexify_expression(expression)
1027
+
1028
+ # Scatter plot
1029
+ ax.scatter(x_vals, y_vals, label=rf"${label_expr}$")
1030
+
1031
+ # Configure axes
1032
+ ax.set_xlim(-zoom, zoom)
1033
+ ax.set_ylim(-zoom, zoom)
1034
+
1035
+ # Place spines at center (optional styling preference)
1036
+ ax.spines['left'].set_position('zero')
1037
+ ax.spines['bottom'].set_position('zero')
1038
+ ax.spines['right'].set_color('none')
1039
+ ax.spines['top'].set_color('none')
1040
+ ax.xaxis.set_ticks_position('bottom')
1041
+ ax.yaxis.set_ticks_position('left')
1042
+ ax.set_aspect('equal', 'box')
1043
+ ax.grid(True)
1044
+
1045
+ # If requested, show the legend
1046
+ if show_legend:
1047
+ leg = ax.legend(
1048
+ loc='upper center',
1049
+ bbox_to_anchor=(0.5, -0.03),
1050
+ fancybox=True,
1051
+ shadow=True,
1052
+ ncol=1
1053
+ )
1054
+ plt.savefig(buffer, format='svg', bbox_inches='tight', bbox_extra_artists=[leg])
1055
+ else:
1056
+ plt.savefig(buffer, format='svg', bbox_inches='tight')
1057
+
1058
+ plt.close(fig)
1059
+ svg_string = buffer.getvalue().decode('utf-8')
1060
+
1061
+ # Optionally open/save the file
1062
+ handle_open_and_save(svg_string, open_file, save_path)
1063
+
1064
+ return svg_string
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: rgwfuncs
3
- Version: 0.0.56
3
+ Version: 0.0.57
4
4
  Summary: A functional programming paradigm for mathematical modelling and data science
5
5
  Home-page: https://github.com/ryangerardwilson/rgwfunc
6
6
  Author: Ryan Gerard Wilson
@@ -541,19 +541,60 @@ This function plots polynomial functions described by a list of expressions and
541
541
  {"x**2/(2 + a) + a": {"x": np.linspace(-3, 4, 101), "a": 1.23}},
542
542
  {"np.diff(x**3, 2)": {"x": np.linspace(-2, 2, 10)}}
543
543
  ],
544
- zoom=2
544
+ zoom=2,
545
+ open_file=True,
546
+ save_path="plot_polynomial_functions_example_1.svg"
545
547
  )
546
548
 
547
- # Write the SVG to an actual file
548
- with open("plot.svg", "w", encoding="utf-8") as file:
549
- file.write(plot_svg_string)
550
-
551
549
  • Displaying the SVG:
552
550
 
553
551
  ![Plot](./media/plot_polynomial_functions_example_1.svg)
554
552
 
555
553
  --------------------------------------------------------------------------------
556
554
 
555
+ media/plot_x_points_of_polynomial_functions_example_5.svg
556
+
557
+ ### 12. `plot_x_points_of_polynomial_functions`
558
+
559
+ This function plots one or more expressions described by a list of dictionaries. For each item in the list, the function evaluates the given Python/NumPy expression at the specified x-values (converted to NumPy arrays if they are Python lists) and plots the resulting points on a single figure.
560
+
561
+ • Parameters:
562
+ - `functions` (`List[Dict[str, Dict[str, Any]]]`): A list of one or more items, each of which has exactly one key-value pair:
563
+ - Key (`str`): A valid Python/NumPy expression (e.g., `x**2`, `np.sin(x)`, `x - a`).
564
+ - Value (`Dict[str, Any]`): Must assign `x` a value
565
+ - `zoom` (`float`): Numeric range from -zoom to +zoom on both x and y axes (default 10.0).
566
+ - `show_legend` (`bool`): If True, includes a legend (default True).
567
+ - `open_file` (bool):
568
+ - If True and `save_path` is given, opens that file with the system viewer.
569
+ - If True and `save_path` is None, writes to a temporary file and opens it (default False).
570
+ - `save_path` (`Optional[str]`): If specified, writes the resulting SVG to this path (default None).
571
+
572
+ • Returns:
573
+ - `str`: The raw SVG markup of the resulting scatter plot.
574
+
575
+ • Example:
576
+
577
+ from rgwfuncs import plot_x_points_of_polynomial_functions
578
+ import numpy as np
579
+
580
+ svg_output = plot_x_points_of_polynomial_functions(
581
+ functions=[
582
+ {"x**2": {"x": np.array([-2, -1, 0, 1, 2])}},
583
+ {"np.sin(x)": {"x": np.linspace(0, 2*np.pi, 5)}},
584
+ {"x - 3": {"x": np.array([-2, 0, 2, 4, 6])}}
585
+ ],
586
+ zoom=6,
587
+ show_legend=True,
588
+ open_file=True,
589
+ save_path="plot_x_points_of_polynomial_functions_example_5.svg"
590
+ )
591
+
592
+ • Displaying the SVG:
593
+
594
+ ![Plot](./media/plot_x_points_of_polynomial_functions_example_5.svg)
595
+
596
+ --------------------------------------------------------------------------------
597
+
557
598
  ## String Based Functions
558
599
 
559
600
  ### 1. send_telegram_message
@@ -0,0 +1,12 @@
1
+ rgwfuncs/__init__.py,sha256=-rcdj4_9zq82h0Tl00S9GvEqDYh7yhPCNhnhBs3mZCg,1676
2
+ rgwfuncs/algebra_lib.py,sha256=rKFITfpWfgdBswnbMUuS41XgndEt-jUVz2ObO_ik7eM,42234
3
+ rgwfuncs/df_lib.py,sha256=qqRQdakheLy8wMZRBfHwKyIp8DmdZIWfAiLKWgq03QU,68977
4
+ rgwfuncs/docs_lib.py,sha256=y3wSAOPO3qsA4HZ7xAtW8HimM8w-c8hjcEzMRLJ96ao,1960
5
+ rgwfuncs/interactive_shell_lib.py,sha256=A7EWsYxAfDev_N0-2GjRvAtp0bAwBPHIczXb8Gu9fzI,1107
6
+ rgwfuncs/str_lib.py,sha256=rtAdRlnSJIu3JhI-tA_A0wCiPK2m-zn5RoGpBxv_g-4,2228
7
+ rgwfuncs-0.0.57.dist-info/LICENSE,sha256=7EI8xVBu6h_7_JlVw-yPhhOZlpY9hP8wal7kHtqKT_E,1074
8
+ rgwfuncs-0.0.57.dist-info/METADATA,sha256=DaC1s1J3mT_4GEnxmmCq6CA418CbkuAT0myFCDNpbik,59010
9
+ rgwfuncs-0.0.57.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
10
+ rgwfuncs-0.0.57.dist-info/entry_points.txt,sha256=j-c5IOPIQ0252EaOV6j6STio56sbXl2C4ym_fQ0lXx0,43
11
+ rgwfuncs-0.0.57.dist-info/top_level.txt,sha256=aGuVIzWsKiV1f2gCb6mynx0zx5ma0B1EwPGFKVEMTi4,9
12
+ rgwfuncs-0.0.57.dist-info/RECORD,,
@@ -1,12 +0,0 @@
1
- rgwfuncs/__init__.py,sha256=JjkuVeRV_Bkw8vnqSbJsRcYQRm4iCI3futR86cf3tRI,1637
2
- rgwfuncs/algebra_lib.py,sha256=b6I553GoY9n6oXinvNzY6P6CvI6za_Bc69PbkaYEqpo,35955
3
- rgwfuncs/df_lib.py,sha256=qqRQdakheLy8wMZRBfHwKyIp8DmdZIWfAiLKWgq03QU,68977
4
- rgwfuncs/docs_lib.py,sha256=y3wSAOPO3qsA4HZ7xAtW8HimM8w-c8hjcEzMRLJ96ao,1960
5
- rgwfuncs/interactive_shell_lib.py,sha256=A7EWsYxAfDev_N0-2GjRvAtp0bAwBPHIczXb8Gu9fzI,1107
6
- rgwfuncs/str_lib.py,sha256=rtAdRlnSJIu3JhI-tA_A0wCiPK2m-zn5RoGpBxv_g-4,2228
7
- rgwfuncs-0.0.56.dist-info/LICENSE,sha256=7EI8xVBu6h_7_JlVw-yPhhOZlpY9hP8wal7kHtqKT_E,1074
8
- rgwfuncs-0.0.56.dist-info/METADATA,sha256=mAxOqfOPI-cMo-FpTnKHUC_Hi-yoPDb2xHjQdpKN41U,57136
9
- rgwfuncs-0.0.56.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
10
- rgwfuncs-0.0.56.dist-info/entry_points.txt,sha256=j-c5IOPIQ0252EaOV6j6STio56sbXl2C4ym_fQ0lXx0,43
11
- rgwfuncs-0.0.56.dist-info/top_level.txt,sha256=aGuVIzWsKiV1f2gCb6mynx0zx5ma0B1EwPGFKVEMTi4,9
12
- rgwfuncs-0.0.56.dist-info/RECORD,,