Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /pfun-health_pfun-cma-model /pfun_cma_model /cli.py
| import argparse | |
| import asyncio | |
| from typing import Literal, Optional | |
| import json | |
| import os | |
| from pathlib import Path | |
| import click | |
| import pandas as pd | |
| from pfun_common.settings import get_settings | |
| from pfun_cma_model.misc.pathdefs import PFunDataPaths | |
| def process_kwds(ctx, param, value): | |
| """Process the keyword arguments passed to the CLI commands | |
| Used by CLI commands: fit_model, run_param_grid. | |
| """ | |
| if param.name not in ["opts"]: | |
| click.secho( | |
| f"Unexpected parameter '{param.name}' in process_kwds callback. Expected 'opts' or 'extra_args'.", | |
| fg="yellow", | |
| bold=False, | |
| ) | |
| return value | |
| value = list(value) | |
| # NOTE: Intentionally not using enumerate (to avoid mutability issues with tuples) | |
| for i in range(len(value)): # pylint: disable=consider-using-enumerate | |
| value[i] = list(value[i]) | |
| if value[i][1].isnumeric(): | |
| try: | |
| new = int(value[i][1]) | |
| except ValueError: | |
| new = float(value[i][1]) | |
| value[i][1] = new | |
| return value | |
| def cli(ctx): | |
| """Command line interface for the pfun-cma-model package. | |
| This CLI provides commands to fit the PFun CMA model, run parameter grid searches, | |
| launch the application, and run benchmarks. | |
| """ | |
| # Set up the context object with default paths | |
| # for sample data and output directory | |
| ctx.ensure_object(dict) | |
| ctx.obj["sample_data_fpath"] = PFunDataPaths().sample_data_fpath | |
| import pfun_path_helper as pph # type: ignore | |
| ctx.obj["output_dir"] = os.path.abspath(os.path.join(pph.get_lib_path("pfun_cma_model"), "../results")) | |
| def process_extra_args(ctx, param, value): | |
| """Process the extra arguments passed to the 'launch' CLI command.""" | |
| if param.name != "extra_args": | |
| click.secho( | |
| f"Unexpected parameter '{param.name}' in process_extra_args callback. Expected 'extra_args'.", | |
| fg="yellow", | |
| bold=False, | |
| ) | |
| return value | |
| keys = [] | |
| for arg in value: | |
| if arg.startswith("--"): | |
| keys.append(arg.lstrip("-").replace("-", "_")) | |
| values = [] | |
| for i in range(len(value)): | |
| if value[i].startswith("--"): | |
| if i + 1 < len(value) and not value[i + 1].startswith("--"): | |
| values.append(value[i + 1]) | |
| else: | |
| values.append("true") # handle flags without values | |
| kwds = dict(zip(keys, values)) | |
| return kwds | |
| def launch(ctx, host, port, reload, extra_args): | |
| """Launch the application. | |
| Additional arguments to pass to the application (e.g. '--ssl-certfile | |
| certs/example.crt --ssl-keyfile certs/example.key'). | |
| These will be passed through to the underlying server (i.e., uvicorn) when launching the app. | |
| """ | |
| from pfun_cma_model.main import run_app | |
| run_app(host, port, reload=reload, debug=True, extra_args=extra_args) | |
| fit_result_global = None | |
| OutputFigureFormatType = Literal["png", "svg"] | |
| def fit_model(ctx, input_fpath, output_dir, output_ftype, n, plot, opts, model_config): | |
| global fit_result_global | |
| model_config = json.loads(model_config) | |
| if input_fpath is None: | |
| input_fpath = ctx.obj["sample_data_fpath"] | |
| from pfun_cma_model.misc.pathdefs import PFunDataPaths | |
| pfun_data_paths = PFunDataPaths() | |
| pfun_data_paths.download_sample_data(overwrite=True) | |
| click.secho( | |
| f"...sample data downloaded to: '{pfun_data_paths.sample_data_fpath}'", | |
| fg="green", | |
| bold=True, | |
| ) | |
| if output_dir is None: | |
| output_dir = ctx.obj["output_dir"] | |
| # read the input dataset | |
| data = pd.read_csv(input_fpath) | |
| # fit the model | |
| from pfun_cma_model.engine.fit import fit_model as call_fit_model | |
| fit_result = call_fit_model(data, n=n, plot=plot, opts=opts, **model_config) | |
| fit_result_global = fit_result | |
| # write fitted model parameters (with the corresponding time-series solution) to disk | |
| output_fpath = os.path.join(output_dir, "fit_result.json") | |
| with open(output_fpath, "w", encoding="utf8") as f: | |
| f.write(fit_result.model_dump_json()) | |
| click.secho(f"...wrote fitted model params to: '{output_fpath}'") | |
| # plot the results (if '--plot' is indicated) | |
| if plot is True: | |
| click.secho("Plotting...", bold=True) | |
| # set the matplotlib backend based on the output figure type | |
| import matplotlib | |
| matplotlib.use( | |
| { | |
| "png": "Agg", | |
| "svg": "svg", | |
| }[output_ftype] | |
| ) | |
| click.secho(f"Set matplotlib backend: {output_ftype}", bold=True) | |
| import matplotlib.pyplot as plt | |
| from pfun_cma_model.engine.cma_plot import CMAPlotSolnConfig, CMAPlotDataConfig | |
| click.secho("Formatted data (from fit_result):", bold=True) | |
| click.secho(fit_result.formatted_data.head().to_string()) | |
| fig, _ = CMAPlotDataConfig().plot( | |
| df=fit_result.formatted_data, | |
| plot_cols=[ | |
| "G", | |
| ], | |
| ) | |
| fig_output_fpath = os.path.join(output_dir, f"fit_result.{output_ftype}") | |
| fig.savefig(fig_output_fpath, format=output_ftype) | |
| click.secho(f"...saved plot to: '{fig_output_fpath}'") | |
| click.confirm("[enter] to exit...", default=True, abort=True, show_default=False) | |
| plt.close("all") | |
| def generate_scenario(ctx, query): | |
| """Generate a realistic pfun scenario (using selected LLM backend).""" | |
| from pfun_cma_model.llm import generate_scenario as gen_scene | |
| click.secho(f"Generating a scenario from prompt:\n\t'{query[:20]}...'\n") | |
| try: | |
| loop = asyncio.get_running_loop() | |
| generated_scenario = loop.run_until_complete(gen_scene(query=query)) | |
| except RuntimeError: | |
| # get the pydantic-validated scenario | |
| generated_scenario = asyncio.run(gen_scene(query=query)) | |
| # dump to JSON, pretty-print the output for CLI | |
| if not hasattr(generated_scenario, "model_dump"): | |
| response = generated_scenario | |
| else: | |
| response = generated_scenario.model_dump() # type: ignore | |
| if generated_scenario.used_fallback_health_info: | |
| click.secho( | |
| "Warning: LLM response omitted health_info; substituted fixed sample " | |
| "profile (used_fallback_health_info=True)", | |
| err=True, | |
| fg="yellow", | |
| bold=True, | |
| ) | |
| output_json_formatted = json.dumps(response, indent=4) | |
| click.secho( | |
| output_json_formatted.encode("utf8").decode("unicode_escape"), | |
| fg="green", | |
| bold=True, | |
| ) | |
| # # # #################### | |
| # Save result to database. | |
| # # # #################### | |
| df_result = pd.DataFrame([response], index=[0]) | |
| df_result.to_parquet(os.path.join(ctx.obj["output_dir"], "cma_recs.parquet")) | |
| # save the generated params, recommendations to the results duckdb database | |
| from pfun_cma_model.db import save2duckdb | |
| db_path = Path(__file__).parent.parent.joinpath("results", "duckdb-local.db") | |
| save2duckdb(df_result, db_path=str(db_path), table_id="cma_recs") | |
| click.secho("...successfully saved result to the database.", fg="green", bold=True) | |
| def run_param_grid(ctx, n, m, params): | |
| """Run a parameter grid search for the PFun CMA model.""" | |
| click.secho(f"Output directory: {ctx.obj['output_dir']}") | |
| click.secho("Running parameter grid search for the PFun CMA model...") | |
| # create the output file path | |
| if not os.path.exists(ctx.obj["output_dir"]): | |
| os.makedirs(ctx.obj["output_dir"]) | |
| # create the parameter grid | |
| from pfun_cma_model.engine.grid import PFunCMAParamsGrid, get_cma_grid_db_path | |
| pkeys_included = params | |
| import logging | |
| logging.debug(f"{pkeys_included}") | |
| click.secho("Included parameter keys:", fg="yellow", bold=True) | |
| if not pkeys_included: | |
| click.secho(" + [all]", fg="yellow") | |
| else: | |
| for pkey in pkeys_included: | |
| click.secho(f" + {pkey}", fg="yellow") | |
| pfun_grid = PFunCMAParamsGrid(N=n, m=m, keys=pkeys_included, include_mealtimes=True) # parameter keys to include | |
| # run the grid search | |
| Nparam = len(pfun_grid.pgrid) | |
| click.secho(f"Running a parameter grid search of size: {Nparam:02d}...") | |
| pfun_grid.run() # perform the operation in-place | |
| # get the grid results as a dataframe | |
| df_grid: pd.DataFrame = pfun_grid.collection # type: ignore | |
| # save to duckdb database | |
| from pfun_cma_model.db import save2duckdb | |
| db_fpath = str(get_cma_grid_db_path()) | |
| table_id = "cma_pgrid" | |
| save2duckdb(df_grid, db_path=db_fpath, table_id=table_id) | |
| click.secho(f"...done (saved to '{db_fpath}').", fg="green", bold=True) | |
| # save to parquet | |
| parquet_fpath = Path(ctx.obj["output_dir"]).joinpath(f"param_grid_{n:02d}x{m:02d}.parquet") | |
| df_grid.to_parquet(str(parquet_fpath)) | |
| click.secho("...done (saved to '').", fg="green", bold=True) | |
| def download_sample_data(ctx, overwrite=False): | |
| """Download the sample data for the pfun-cma-model package.""" | |
| click.secho("Downloading sample data for the pfun-cma-model package...") | |
| if overwrite: | |
| click.secho( | |
| "Overwrite is enabled; existing files will be replaced if they exist.", | |
| fg="yellow", | |
| bold=True, | |
| ) | |
| from pfun_cma_model.misc.pathdefs import PFunDataPaths | |
| pfun_data_paths = PFunDataPaths() | |
| pfun_data_paths.download_sample_data(overwrite=overwrite) | |
| click.secho( | |
| f"...sample data downloaded to: '{pfun_data_paths.sample_data_fpath}'", | |
| fg="green", | |
| bold=True, | |
| ) | |
| def version(): | |
| """Print the version of the pfun-cma-model package.""" | |
| import pfun_cma_model | |
| click.secho(f"pfun-cma-model version: {pfun_cma_model.__version__}", bold=True) | |
| def run_doctests(): | |
| """Run the doctests for the pfun-cma-model cli.""" | |
| import doctest | |
| doctest.testmod() | |
| def benchmark(sizes, repeats, implementations, output, params, warmup, threshold): | |
| """Run benchmark tests comparing Python CMA engine vs. C extension.""" | |
| from pfun_cma_model.engine.benchmark import ( | |
| _parse_sizes, _parse_implementations, _parse_params, benchmark as run_benchmark | |
| ) | |
| try: | |
| benchmark_sizes = _parse_sizes(sizes) | |
| impls = _parse_implementations(implementations) | |
| custom_params = _parse_params(params) | |
| except ValueError as e: | |
| click.secho(f"Error: {e}", fg="red", bold=True) | |
| return | |
| # Run benchmark with parsed arguments | |
| results = run_benchmark( | |
| sizes=benchmark_sizes, | |
| n_repeats=repeats, | |
| implementations=impls, | |
| custom_params=custom_params, | |
| n_warmup=warmup, | |
| threshold=threshold, | |
| ) | |
| # Output results to file if requested | |
| if output: | |
| try: | |
| import json | |
| with open(output, 'w') as f: | |
| json.dump(results, f, indent=2) | |
| click.secho(f"\nResults saved to: {output}", fg="green", bold=True) | |
| except Exception as e: | |
| click.secho(f"Error saving results to {output}: {e}", fg="red", bold=True) | |
| if __name__ == "__main__": | |
| cli() # type: ignore | |
Xet Storage Details
- Size:
- 14.7 kB
- Xet hash:
- 48296d7fc8d5cefe8af457d36fccada24fe2d276e7e6e29bb520286743aba9d3
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.