### Example: dargs doc Source: https://github.com/deepmodeling/dargs/blob/master/docs/cli.md An example demonstrating how to use the 'dargs doc' command to retrieve documentation for a specific function or argument. ```bash dargs doc dargs._test.test_arguments [arg_path] ``` -------------------------------- ### dargs.sphinx.setup() Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Setup function for the dargs Sphinx extension. ```APIDOC ## dargs.sphinx.setup() ### Description Setup function for the dargs Sphinx extension. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### Sphinx Setup Function for dargs Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md The setup function for the dargs Sphinx extension, which is called by Sphinx to initialize the extension. ```python def setup(app: Any) -> dict[str, bool]: """Setup sphinx app.""" pass ``` -------------------------------- ### Example: Splitting Large Configs with $ref Source: https://github.com/deepmodeling/dargs/blob/master/docs/ref.md This example demonstrates how to split a large configuration into reusable pieces using the $ref feature. The contents of `model_defaults.json` are loaded first, and then local keys like `hidden_size` override or add to the loaded values. ```json { "model": { "$ref": "model_defaults.json", "hidden_size": 256 } } ``` -------------------------------- ### Install and Run DP-GUI Source: https://github.com/deepmodeling/dargs/blob/master/docs/dpgui.md Install the DP-GUI Python package using pip and then run the 'dpgui' command to serve the graphical interface. DP-GUI will automatically load the arguments exposed via the 'dpgui' entry point. ```sh pip install dpgui dpgui ``` -------------------------------- ### Example: dargs check Source: https://github.com/deepmodeling/dargs/blob/master/docs/cli.md An example demonstrating how to use the 'dargs check' command to validate a JSON file against a specific function. ```bash dargs check -f dargs._test.test_arguments test_arguments.json ``` -------------------------------- ### Specify JSON Schema in a JSON File Source: https://github.com/deepmodeling/dargs/blob/master/docs/json_schema.md This example demonstrates how to directly reference a JSON schema within a JSON file using the '$schema' key. This is an alternative method supported by VS Code for schema mapping. ```json { "$schema": "./deepmd.json", "model": {} } ``` -------------------------------- ### Get 'Did You Mean' Error Message Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Provides a helpful error message suggesting a correct choice when a user provides an invalid option. This function is useful for improving user experience in command-line interfaces. ```python >>> did_you_mean('optin', ['option1', 'option2']) 'Did you mean option1?' ``` -------------------------------- ### Configure DP-GUI Entry Point in pyproject.toml Source: https://github.com/deepmodeling/dargs/blob/master/docs/dpgui.md Add a 'dpgui' entry point to your pyproject.toml file to expose Dargs Arguments to DP-GUI. The entry point maps a display name to a Python callable that returns an Argument or a list of Arguments. ```toml [project.entry-points."dpgui"] "Test Argument" = "dargs.sphinx:_test_argument" ``` -------------------------------- ### dargs.cli.main Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md The main entry point for the dargs command-line interface. ```APIDOC ## dargs.cli.main ### Description Main entry point for the command line interface. ### Returns * **None** ``` -------------------------------- ### dargs.cli.doc_cli Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Prints documentation for an Argument, either for a specific argument path or all top-level arguments. ```APIDOC ## dargs.cli.doc_cli ### Description Print documentation for an Argument. ### Parameters * **func** (str) - Required - Function that returns an Argument or list of Arguments. E.g., dargs._test.test_arguments. * **arg** (str | None) - Optional - Argument path (e.g., ‘base/sub1’). If not provided, prints all top-level arguments. * **kwargs** (Any) - Optional - Additional keyword arguments. ### Returns * **None** ``` -------------------------------- ### dargs.sphinx.DargsDirective.run() Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Executes the DargsDirective and returns generated content. ```APIDOC ## dargs.sphinx.DargsDirective.run() ### Description Executes the DargsDirective and returns generated content. ### Method (Not specified, likely a method call) ### Endpoint (Not applicable, this is a class method) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### dargs.sphinx.DargsDomain.initial_data Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Initial data for the DargsDomain. ```APIDOC ## dargs.sphinx.DargsDomain.initial_data ### Description Initial data for the DargsDomain. ### Method (Not specified, likely an attribute access) ### Endpoint (Not applicable, this is a class attribute) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### Enable $ref Loading in dargs Methods Source: https://github.com/deepmodeling/dargs/blob/master/docs/ref.md To enable loading configuration from external files using the $ref key, pass `allow_ref=True` to the relevant dargs methods. This is required because the feature is disabled by default for security reasons. ```python argument.check(data, allow_ref=True) argument.normalize(data, allow_ref=True) argument.check_value(value, allow_ref=True) argument.normalize_value(value, allow_ref=True) ``` -------------------------------- ### Define and Check Argument Structure Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Instantiate an Argument with nested sub-fields and then check a dictionary against this structure. This is useful for validating complex configurations. ```python >>> ca = Argument("base", dict, [Argument("sub", int)]) >>> ca.check({"base": {"sub1": 1}}) >>> ca.check_value({"sub1": 1}) ``` -------------------------------- ### dargs.cli module Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Provides command-line interface utilities for dargs. ```APIDOC ## Module: dargs.cli ### Description This module provides functions for interacting with the `dargs` library via the command-line interface. ### Functions - `check_cli(args)`: Processes command-line arguments for checking. - `doc_cli(args)`: Processes command-line arguments for documentation generation. - `main()`: The main entry point for the `dargs` CLI. - `main_parser()`: Creates and returns the main argument parser for the `dargs` CLI. ``` -------------------------------- ### dargs CLI Usage Source: https://github.com/deepmodeling/dargs/blob/master/docs/cli.md Shows the main usage of the dargs command-line tool, listing available sub-commands. ```bash usage: dargs [-h] [--version] {check,doc} ... ``` -------------------------------- ### Configure Sphinx Extensions Source: https://github.com/deepmodeling/dargs/blob/master/docs/sphinx.md Add 'dargs.sphinx' to your Sphinx project's conf.py file to enable the dargs directive. ```python extensions = [ 'dargs.sphinx', ] ``` -------------------------------- ### Render JSON with Argument in Jupyter Notebook Source: https://github.com/deepmodeling/dargs/blob/master/docs/nb.ipynb Use `dargs.notebook.JSON` to render a JSON string with an associated argument in a Jupyter Notebook. The documentation for each argument key will appear on hover. ```python from __future__ import annotations from dargs.notebook import JSON from dargs.sphinx import _test_argument jstr = """ { "test_argument": "test1", "test_list": [ 1, 2, 3 ], "test_variant": "test_variant_argument", "test_repeat_list": [ {"test_repeat_item": false}, {"test_repeat_item": true} ], "test_repeat_dict": { "test1": {"test_repeat_item": false}, "test2": {"test_repeat_item": true} }, "_comment": "This is an example data" } """ JSON(jstr, _test_argument()) ``` -------------------------------- ### gen_doc Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Generates a documentation string for the current Argument, including its nested structure. ```APIDOC ## gen_doc ### Description Generates a documentation string for the current Argument. This method can be used to create human-readable descriptions of argument structures, including nested fields and variants. ### Method `gen_doc(path: list[str] | None = None, **kwargs: Any) -> str` ### Parameters * **path** (list[str] | None, optional) - The current path within the nested structure. Defaults to `None`. * **`**kwargs`** (Any) - Additional keyword arguments to influence document generation. ``` -------------------------------- ### dargs.cli.main_parser Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Creates and returns the main argument parser for the dargs command-line interface. ```APIDOC ## dargs.cli.main_parser ### Description Create the main parser for the command line interface. ### Returns * **argparse.ArgumentParser** - The main parser. ``` -------------------------------- ### dargs.sphinx.DargsDomain.directives Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md A dictionary of directives supported by the DargsDomain. ```APIDOC ## dargs.sphinx.DargsDomain.directives ### Description A dictionary of directives supported by the DargsDomain. ### Method (Not specified, likely an attribute access) ### Endpoint (Not applicable, this is a class attribute) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### Variant.gen_doc Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Generates documentation string for the Variant, including its choices and parameters. ```APIDOC ## gen_doc(path: list[str] | None = None, showflag: bool = False, **kwargs: Any) -> str ### Description Generate documentation string for the Variant. ### Parameters * **path** (list[str] | None) - Optional - The current path in the structure. * **showflag** (bool) - Optional - Whether to show the flag name. Defaults to False. * **kwargs** (Any) - Additional keyword arguments for documentation generation. ``` -------------------------------- ### dargs.sphinx.DargsDomain.roles Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md A dictionary of roles supported by the DargsDomain. ```APIDOC ## dargs.sphinx.DargsDomain.roles ### Description A dictionary of roles supported by the DargsDomain. ### Method (Not specified, likely an attribute access) ### Endpoint (Not applicable, this is a class attribute) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### dargs.sphinx.DargsObject.add_target_and_index() Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Adds a target and index for a DargsObject. ```APIDOC ## dargs.sphinx.DargsObject.add_target_and_index() ### Description Adds a target and index for a DargsObject. ### Method (Not specified, likely a method call) ### Endpoint (Not applicable, this is a class method) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### dargs.sphinx.DargsObject.handle_signature() Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Handles the signature for a DargsObject. ```APIDOC ## dargs.sphinx.DargsObject.handle_signature() ### Description Handles the signature for a DargsObject. ### Method (Not specified, likely a method call) ### Endpoint (Not applicable, this is a class method) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### gen_doc_head Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Generates the header part of the documentation string for the current Argument. ```APIDOC ## gen_doc_head ### Description Generates the header section of the documentation string for the current Argument. This usually contains the argument's name and type information. ### Method `gen_doc_head(path: list[str] | None = None, **kwargs: Any) -> str` ### Parameters * **path** (list[str] | None, optional) - The current path within the nested structure. Defaults to `None`. * **`**kwargs`** (Any) - Additional keyword arguments to influence document generation. ``` -------------------------------- ### Generate JSON Schema from Arguments Source: https://github.com/deepmodeling/dargs/blob/master/docs/json_schema.md This snippet demonstrates how to generate a JSON schema from a dargs Argument object and save it to a file. It requires importing `json`, `Argument`, `generate_json_schema`, and `gen_args`. ```python import json from dargs import Argument from dargs.json_schema import generate_json_schema from deepmd.utils.argcheck import gen_args a = Argument("DeePMD-kit", dtype=dict, sub_fields=gen_args()) schema = generate_json_schema(a) with open("deepmd.json", "w") as f: json.dump(schema, f, indent=2) ``` -------------------------------- ### dargs.dargs module - Argument Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Detailed API for the Argument class within the dargs.dargs submodule. ```APIDOC ## Class: Argument (in dargs.dargs) ### Description This class, located in the `dargs.dargs` submodule, represents an argument with methods for configuration, validation, and documentation. ### Methods - `Argument.I()`: (Internal use or specific context) - `Argument.add_subfield(name, field)`: Adds a subfield to the argument. - `Argument.add_subvariant(name, variant)`: Adds a subvariant to the argument. - `Argument.check()`: Checks the validity of the argument. - `Argument.check_value(value)`: Checks the validity of a given value for the argument. - `Argument.extend_subfields(subfields)`: Extends the argument with multiple subfields. - `Argument.extend_subvariants(variants)`: Extends the argument with multiple subvariants. - `Argument.flatten_sub()`: Flattens the sub-structure of the argument. - `Argument.gen_doc()`: Generates documentation for the argument. - `Argument.gen_doc_body()`: Generates the body part of the argument's documentation. - `Argument.gen_doc_head()`: Generates the head part of the argument's documentation. - `Argument.gen_doc_path()`: Generates the path part of the argument's documentation. - `Argument.normalize()`: Normalizes the argument. - `Argument.normalize_value(value)`: Normalizes a given value for the argument. - `Argument.set_dtype(dtype)`: Sets the data type for the argument. - `Argument.set_repeat(repeat)`: Sets the repetition behavior for the argument. - `Argument.traverse()`: Traverses the argument structure. - `Argument.traverse_value(value)`: Traverses the value within the argument structure. ``` -------------------------------- ### dargs doc Sub-command Usage Source: https://github.com/deepmodeling/dargs/blob/master/docs/cli.md Details the usage of the 'doc' sub-command, which prints documentation for a given function or argument. ```bash dargs doc [-h] func [arg] ``` -------------------------------- ### dargs.sphinx.DargsDomain.name Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md The name of the DargsDomain. ```APIDOC ## dargs.sphinx.DargsDomain.name ### Description The name of the DargsDomain. ### Method (Not specified, likely an attribute access) ### Endpoint (Not applicable, this is a class attribute) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### Variant.gen_doc_flag Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Generates a documentation string specifically for the flag associated with the Variant. ```APIDOC ## gen_doc_flag(path: list[str] | None = None, **kwargs: Any) -> str ### Description Generate documentation string for the flag of the Variant. ### Parameters * **path** (list[str] | None) - Optional - The current path in the structure. * **kwargs** (Any) - Additional keyword arguments for documentation generation. ``` -------------------------------- ### dargs.sphinx.DargsDomain.object_types Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md A dictionary of object types supported by the DargsDomain. ```APIDOC ## dargs.sphinx.DargsDomain.object_types ### Description A dictionary of object types supported by the DargsDomain. ### Method (Not specified, likely an attribute access) ### Endpoint (Not applicable, this is a class attribute) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### traverse Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Traverses the argument structure, applying hooks to keys, values, sub-arguments, and variants. ```APIDOC ## traverse ### Description Traverses the argument structure, applying specified hook functions at different points (keys, values, sub-arguments, variants). This is useful for inspecting or modifying the argument tree. ### Method `traverse(argdict: dict, key_hook: Callable[[Argument, dict, List[str]], None] = , value_hook: Callable[[Argument, Any, List[str]], None] = , sub_hook: Callable[[Argument, dict, List[str]], None] = , variant_hook: Callable[[Variant, dict, List[str]], None] = , path: list[str] | None = None, allow_ref: bool = False) -> None` ### Parameters * **argdict** (dict) - The dictionary representing the argument structure to traverse. * **key_hook** (Callable, optional) - A hook function called for each key encountered. Defaults to a dummy hook. * **value_hook** (Callable, optional) - A hook function called for each value encountered. Defaults to a dummy hook. * **sub_hook** (Callable, optional) - A hook function called for each sub-argument encountered. Defaults to a dummy hook. * **variant_hook** (Callable, optional) - A hook function called for each variant encountered. Defaults to a dummy hook. * **path** (list[str] | None, optional) - The current path within the nested structure. Defaults to `None`. * **allow_ref** (bool, optional) - If true, allows loading values from external files using the `$ref` key. Defaults to `False`. ``` -------------------------------- ### dargs.sphinx.DargsDomain.label Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md The label for the DargsDomain. ```APIDOC ## dargs.sphinx.DargsDomain.label ### Description The label for the DargsDomain. ### Method (Not specified, likely an attribute access) ### Endpoint (Not applicable, this is a class attribute) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### dargs.dargs.did_you_mean() Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Provides a 'did you mean?' suggestion, likely for typos in arguments. ```APIDOC ## dargs.dargs.did_you_mean() ### Description Provides a 'did you mean?' suggestion, likely for typos in arguments. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### Check Instance Against Annotation Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md A flexible type checking function that works similarly to isinstance but supports arbitrary type annotations. This is useful for validating arguments against complex type hints. ```python >>> isinstance_annotation(value, dtype) ``` -------------------------------- ### gen_doc_path Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Generates the path component of the documentation string for the current Argument. ```APIDOC ## gen_doc_path ### Description Generates the path component of the documentation string for the current Argument, indicating its position within a nested structure. ### Method `gen_doc_path(path: list[str] | None = None, **kwargs: Any) -> str` ### Parameters * **path** (list[str] | None, optional) - The current path within the nested structure. Defaults to `None`. * **`**kwargs`** (Any) - Additional keyword arguments to influence document generation. ``` -------------------------------- ### dargs.sphinx.DargsDirective.option_spec Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Specifies the options for the DargsDirective. ```APIDOC ## dargs.sphinx.DargsDirective.option_spec ### Description Specifies the options for the DargsDirective. ### Method (Not specified, likely an attribute access) ### Endpoint (Not applicable, this is a class attribute) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### dargs.cli.check_cli Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Normalizes and checks input data specifically for command-line interface usage. It takes a function to generate argument information and a list of file objects. ```APIDOC ## dargs.cli.check_cli ### Description Normalize and check input data. ### Parameters * **func** (str) - Required - Function that returns an Argument object. E.g., dargs._test.test_arguments. * **jdata** (list[IO]) - Required - File object(s) that contain the JSON data. * **strict** (bool) - Required - If True, raise an error if the key is not pre-defined. * **allow_ref** (bool) - Optional - If True, allow loading from external files via the `$ref` key. Defaults to False. * **kwargs** (Any) - Optional - Additional keyword arguments. ### Returns * **dict** - Normalized data. ``` -------------------------------- ### dargs.check module Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Provides utility functions for checking arguments. ```APIDOC ## Module: dargs.check ### Description This module contains utility functions for validating and checking arguments. ### Functions - `check(argument, value)`: Checks if a given value conforms to the specified argument's rules. ``` -------------------------------- ### set_repeat Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Configures whether the Argument should be treated as repeatable. ```APIDOC ## set_repeat(repeat: bool = True) -> None ### Description Change the repeat attribute of the current Argument. ### Parameters * **repeat** (bool) - Optional - Whether to enable repetition. Defaults to True. ``` -------------------------------- ### dargs.sphinx.DargsObject.option_spec Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Specifies the options for the DargsObject. ```APIDOC ## dargs.sphinx.DargsObject.option_spec ### Description Specifies the options for the DargsObject. ### Method (Not specified, likely an attribute access) ### Endpoint (Not applicable, this is a class attribute) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### Configure JSON Schema in VS Code Source: https://github.com/deepmodeling/dargs/blob/master/docs/json_schema.md This JSON configuration shows how to associate a generated JSON schema file with specific JSON files in Visual Studio Code's project settings. This enables schema validation and autocompletion for those files. ```json { "json.schemas": [ { "fileMatch": [ "/deepmd.json" ], "url": "./deepmd.json" } ] } ``` -------------------------------- ### dargs.sphinx.DargsDomain.resolve_xref() Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Resolves a cross-reference within the DargsDomain. ```APIDOC ## dargs.sphinx.DargsDomain.resolve_xref() ### Description Resolves a cross-reference within the DargsDomain. ### Method (Not specified, likely a method call) ### Endpoint (Not applicable, this is a class method) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### Variant.get_choice Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Determines and returns the specific Argument choice that matches the provided argument dictionary based on the Variant's flag name. ```APIDOC ## get_choice(argdict: dict, path: list[str] | None = None) -> Argument ### Description Get the choice Argument from the argdict based on the flag name. ### Parameters * **argdict** (dict) - The dictionary containing arguments. * **path** (list[str] | None) - Optional - The current path in the structure. ### Returns * **Argument** - The matching choice Argument. ``` -------------------------------- ### check Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Validates if a given dictionary conforms to the expected argument structure, with options for strictness and reference handling. ```APIDOC ## check ### Description Checks whether a given dictionary (`argdict`) meets the structure defined by the current Argument. It recursively validates nested dictionaries based on defined subfields and subvariants. Raises an error if the check fails. ### Method `check(argdict: dict, strict: bool = False, allow_ref: bool = False) -> None` ### Parameters * **argdict** (dict) - The dictionary to be checked against the argument structure. * **strict** (bool, optional) - If true, only keys explicitly defined in the Argument are allowed. Defaults to `False`. * **allow_ref** (bool, optional) - If true, allows loading values from external files using the `$ref` key. A deep copy of `argdict` is made internally to prevent mutation of the caller's data. Defaults to `False`. ``` -------------------------------- ### dargs.dargs.make_ref_pair() Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Creates a reference pair, likely for internal use. ```APIDOC ## dargs.dargs.make_ref_pair() ### Description Creates a reference pair, likely for internal use. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### dargs.json_schema.generate_json_schema() Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Generates a JSON schema from a given input. ```APIDOC ## dargs.json_schema.generate_json_schema() ### Description Generates a JSON schema from a given input. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### traverse Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Traverses through an argument dictionary, applying hooks for keys, values, sub-arguments, and variants. This method is used for deep inspection and modification of argument structures, with options to control reference loading. ```APIDOC ## traverse(argdict: dict, key_hook: Callable[[Argument, dict, List[str]], None] = , value_hook: Callable[[Argument, Any, List[str]], None] = , sub_hook: Callable[[Argument, dict, List[str]], None] = , variant_hook: Callable[[Variant, dict, List[str]], None] = , path: list[str] | None = None, allow_ref: bool = False) -> None ### Description Traverses through the argument dictionary and applies specified hooks. ### Parameters * **argdict** (dict) - The dictionary of arguments to traverse. * **key_hook** (Callable) - Optional - Hook for processing keys. * **value_hook** (Callable) - Optional - Hook for processing values. * **sub_hook** (Callable) - Optional - Hook for processing sub-arguments. * **variant_hook** (Callable) - Optional - Hook for processing variants. * **path** (list[str] | None) - Optional - The current path in the traversal. * **allow_ref** (bool) - Optional - If true, allow loading from external files via the `$ref` key. ``` -------------------------------- ### dargs.dargs module - Variant Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Detailed API for the Variant class within the dargs.dargs submodule. ```APIDOC ## Class: Variant (in dargs.dargs) ### Description This class, located in the `dargs.dargs` submodule, represents a variant with methods for managing choices and documentation. ### Methods - `Variant.add_choice(choice)`: Adds a choice to the variant. - `Variant.dummy_argument()`: Creates a dummy `Argument` object associated with this variant. - `Variant.extend_choices(choices)`: Extends the variant with multiple choices. - `Variant.flatten_sub()`: Flattens the sub-structure of the variant. - `Variant.gen_doc()`: Generates documentation for the variant. - `Variant.gen_doc_flag()`: Generates documentation for the variant's flag. - `Variant.get_choice(name)`: Retrieves a specific choice from the variant by name. - `Variant.set_default(default_choice)`: Sets the default choice for the variant. ``` -------------------------------- ### Variant Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Defines multiple choices for argument sets, controlled by a flag name. Each choice is an Argument, and the Variant class facilitates managing these choices and their selection logic. ```APIDOC ## class dargs.dargs.Variant(flag_name: str, choices: Iterable[[Argument](#dargs.dargs.Argument)] | None = None, optional: bool = False, default_tag: str = '', doc: str = '') Bases: `object` Define multiple choices of possible argument sets. Each Variant contains a flag_name and a list of choices that are represented by Argument`s. The choice is picked if its name matches the value of `flag_name in the actual arguments. The actual arguments should then be a dict containing flag_name and sub fields of the picked choice. ### Parameters flag_name: str : The name of the key to be used as the switching flag. choices: list of Argument : A list of possible choices. Each of them should be an Argument. The name of the Argument serves as the tag in the switching flag. optional: bool, optional : If true, the flag_name can be optional and defaults to defalut_flag. default_tag: str, optional : Needed if optional is true. doc: str, optional : The doc string used in document generation. ### Notes This class should only be used in sub variants of the Argument class. #### add_choice(tag: str | ~dargs.dargs.Argument, _dtype: None | type | ~typing.Iterable[type] = , *args: ~typing.Any, **kwargs: ~typing.Any) -> [Argument](#dargs.dargs.Argument) Add a choice Argument to the current Variant. #### dummy_argument() -> [Argument](#dargs.dargs.Argument) #### extend_choices(choices: Iterable[[Argument](#dargs.dargs.Argument)] | None) -> None Add a list of choice Arguments to the current Variant. #### flatten_sub(argdict: dict, path: list[str] | None = None) -> dict[str, [Argument](#dargs.dargs.Argument)] #### gen_doc(path: list[str] | None = None, showflag: bool = False, **kwargs: Any) -> str #### gen_doc_flag(path: list[str] | None = None, **kwargs: Any) -> str #### get_choice(argdict: dict, path: list[str] | None = None) -> [Argument](#dargs.dargs.Argument) #### set_default(default_tag: bool | str) -> None Change the default tag of the current Variant. ``` -------------------------------- ### dargs.sphinx.DargsDirective.has_content Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Property indicating if the DargsDirective has content. ```APIDOC ## dargs.sphinx.DargsDirective.has_content ### Description Property indicating if the DargsDirective has content. ### Method (Not specified, likely an attribute access) ### Endpoint (Not applicable, this is a class attribute) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### Generate JSON Schema for DeePMD-kit Arguments Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md This snippet demonstrates how to generate a JSON schema from a DeePMD-kit Argument object and save it to a file. It requires importing necessary functions from dargs and deepmd. ```python >>> from dargs.json_schema import generate_json_schema >>> from deepmd.utils.argcheck import gen_args >>> import json >>> from dargs import Argument >>> a = Argument("DeePMD-kit", dtype=dict, sub_fields=gen_args()) >>> schema = generate_json_schema(a) >>> with open("deepmd.json", "w") as f: ... json.dump(schema, f, indent=2) ``` -------------------------------- ### gen_doc_body Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Generates the body part of the documentation string for the current Argument. ```APIDOC ## gen_doc_body ### Description Generates the body section of the documentation string for the current Argument. This typically includes details about its subfields and variants. ### Method `gen_doc_body(path: list[str] | None = None, **kwargs: Any) -> str` ### Parameters * **path** (list[str] | None, optional) - The current path within the nested structure. Defaults to `None`. * **`**kwargs`** (Any) - Additional keyword arguments to influence document generation. ``` -------------------------------- ### dargs.dargs.isinstance_annotation() Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Checks if an object is an instance of a type annotation. ```APIDOC ## dargs.dargs.isinstance_annotation() ### Description Checks if an object is an instance of a type annotation. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### dargs.dargs.Argument Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Defines possible arguments, their types, and properties for data validation and documentation. Supports nested structures, aliases, and custom checks. ```APIDOC ## dargs.dargs.Argument ### Description Define possible arguments and their types and properties. Each Argument instance contains a name and a dtype, that correspond to the key and value type of the actual argument. Additionally, it can include sub_fields and sub_variants to deal with nested dict arguments. ### Parameters * **name** (str) - Required - The name of the current argument, i.e. the key in the arg dict. * **dtype** (None | type | Iterable[type | Any | None]) - Optional - The value type of the current argument, can be a list of possible types. None will be treated as NoneType. * **sub_fields** (Iterable[Argument] | None) - Optional - If given, dtype is assumed to be dict, whose items correspond to the Argument's in the `sub_fields` list. * **sub_variants** (Iterable[Variant] | None) - Optional - If given, dtype is assumed to be dict, and its items are determined by the Variant's in the given list and the value of their flag keys. * **repeat** (bool) - Optional - If true, dtype is assume to be list of dict or dict of dict, and each dict consists of sub fields and sub variants described above. Defaults to false. * **optional** (bool) - Optional - If true, consider the current argument to be optional in checking. Defaults to false. * **default** (Any) - Optional - The default value of the argument, used in normalization. Defaults to _Flags.NONE. * **alias** (Iterable[str] | None) - Optional - Alternative names of the current argument, used in normalization. * **extra_check** (Callable[[Any], bool] | None) - Optional - Additional check to be done on the value of the argument. Should be a function that takes the value and returns whether it passes. * **doc** (str) - Optional - The doc string of the argument, used in doc generation. Defaults to ''. * **fold_subdoc** (bool) - Optional - If true, no doc will be generated for sub args. Defaults to false. * **extra_check_errmsg** (str) - Optional - The error message if extra_check fails. Defaults to ''. ### Properties * **I** (Argument) - Read-only property. ### Examples ```pycon >>> ca = Argument("base", dict, [Argument("sub", int)]) >>> ca.check({"base": {"sub1": 1}}) >>> ca.check_value({"sub1": 1}) ``` For more detailed examples, please check the unit tests. ``` -------------------------------- ### dargs.dargs module - ArgumentEncoder Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md API for the ArgumentEncoder class within the dargs.dargs submodule. ```APIDOC ## Class: ArgumentEncoder (in dargs.dargs) ### Description An encoder class within the `dargs.dargs` submodule for serializing `Argument` objects. ### Methods - `ArgumentEncoder.default(obj)`: Handles the default encoding logic for `Argument` objects. ``` -------------------------------- ### dargs.check.check Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Checks and normalizes input data against provided argument information. It can optionally trim keys and allow references to external files. ```APIDOC ## dargs.check.check ### Description Check and normalize input data. ### Parameters * **arginfo** (Argument | list[Argument] | tuple[Argument, ...]) - Required - Argument object or a list/tuple of Argument objects. * **data** (dict) - Required - The dictionary containing data to check. * **strict** (bool) - Optional - If True, raise an error if a key is not pre-defined. Defaults to True. * **trim_pattern** (str) - Optional - Pattern to trim the key. Defaults to "_\*”. * **allow_ref** (bool) - Optional - If True, allow loading from external files via the `$ref` key. Defaults to False. ### Returns * **dict** - The normalized data. ``` -------------------------------- ### dargs.Argument Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Represents an argument with various methods for manipulation, validation, and documentation generation. ```APIDOC ## Class: Argument ### Description Represents an argument that can be configured with subfields, subvariants, data types, and repetition. It provides methods for validation, normalization, and generating documentation. ### Methods - `Argument.I()`: (Internal use or specific context) - `Argument.add_subfield(name, field)`: Adds a subfield to the argument. - `Argument.add_subvariant(name, variant)`: Adds a subvariant to the argument. - `Argument.check()`: Checks the validity of the argument. - `Argument.check_value(value)`: Checks the validity of a given value for the argument. - `Argument.extend_subfields(subfields)`: Extends the argument with multiple subfields. - `Argument.extend_subvariants(variants)`: Extends the argument with multiple subvariants. - `Argument.flatten_sub()`: Flattens the sub-structure of the argument. - `Argument.gen_doc()`: Generates documentation for the argument. - `Argument.gen_doc_body()`: Generates the body part of the argument's documentation. - `Argument.gen_doc_head()`: Generates the head part of the argument's documentation. - `Argument.gen_doc_path()`: Generates the path part of the argument's documentation. - `Argument.normalize()`: Normalizes the argument. - `Argument.normalize_value(value)`: Normalizes a given value for the argument. - `Argument.set_dtype(dtype)`: Sets the data type for the argument. - `Argument.set_repeat(repeat)`: Sets the repetition behavior for the argument. - `Argument.traverse()`: Traverses the argument structure. - `Argument.traverse_value(value)`: Traverses the value within the argument structure. ``` -------------------------------- ### dargs.dargs module - Exception Classes Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Defines custom exception classes for argument-related errors. ```APIDOC ## Module: dargs.dargs (Exceptions) ### Description This module defines specific exception classes used for handling errors related to argument processing. ### Exception Classes - `ArgumentError`: Base class for all `dargs` argument-related errors. - `ArgumentKeyError`: Raised when an invalid key is used for an argument. - `ArgumentTypeError`: Raised when an argument has an incorrect data type. - `ArgumentValueError`: Raised when an argument has an invalid value. ``` -------------------------------- ### normalize Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Normalizes a dictionary to conform to the Argument structure, optionally modifying it in place and handling defaults, aliases, and references. ```APIDOC ## normalize ### Description Modifies a dictionary (`argdict`) so that it conforms to the Argument structure. Normalization can involve adding default values for optional arguments, substituting aliases with their standard names, and discarding unnecessary arguments based on a provided pattern. It can operate in-place or return a new dictionary. ### Method `normalize(argdict: dict, inplace: bool = False, do_default: bool = True, do_alias: bool = True, trim_pattern: str | None = None, allow_ref: bool = False) -> dict` ### Parameters * **argdict** (dict) - The dictionary to be normalized. * **inplace** (bool, optional) - If true, modifies the given dictionary directly. Otherwise, returns a new dictionary. Defaults to `False`. * **do_default** (bool, optional) - Whether to add default values for arguments. Defaults to `True`. * **do_alias** (bool, optional) - Whether to transform alias names to their standard names. Defaults to `True`. * **trim_pattern** (str | None, optional) - If provided, keys matching this glob pattern will be discarded. Defaults to `None`. * **allow_ref** (bool, optional) - If true, allows loading values from external files using the `$ref` key. Defaults to `False`. ### Returns * **dict**: The normalized argument dictionary. ``` -------------------------------- ### dargs.Argument Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Defines possible arguments and their types and properties. Each Argument instance contains a name and a dtype, corresponding to the key and value type of the actual argument. It can also include sub_fields and sub_variants for nested dict arguments. ```APIDOC ## Class: dargs.Argument ### Description Defines possible arguments and their types and properties. Each Argument instance contains a name and a dtype, corresponding to the key and value type of the actual argument. It can also include sub_fields and sub_variants for nested dict arguments. ### Parameters - **name** (str) - The name of the current argument, i.e., the key in the arg dict. - **dtype** (None | type | Iterable[type | Any | None]) - The value type of the current argument, can be a list of possible types. None will be treated as NoneType. - **sub_fields** (Iterable[Argument] | None) - If given, dtype is assumed to be dict, whose items correspond to the Argument's in the sub_fields list. - **sub_variants** (Iterable[Variant] | None) - If given, dtype is assumed to be dict, and its items are determined by the Variant's in the given list and the value of their flag keys. - **repeat** (bool) - If true, dtype is assumed to be list of dict or dict of dict, and each dict consists of sub fields and sub variants described above. Defaults to false. - **optional** (bool) - If true, consider the current argument to be optional in checking. - **default** (Any) - The default value of the argument, used in normalization. - **alias** (Iterable[str] | None) - Alternative names of the current argument, used in normalization. - **extra_check** (Callable[[Any], bool] | None) - Additional check to be done on the value of the argument. Should be a function that takes the value and returns whether it passes. - **doc** (str) - The doc string of the argument, used in doc generation. - **fold_subdoc** (bool) - If true, no doc will be generated for sub args. - **extra_check_errmsg** (str) - The error message if extra_check fails. ### Methods #### add_subfield(name: str | Argument, *args: Any, **kwargs: Any) -> Argument Add a sub field to the current Argument. #### add_subvariant(flag_name: str | Variant, *args: Any, **kwargs: Any) -> Variant Add a sub variant to the current Argument. #### check(argdict: dict, strict: bool = False, allow_ref: bool = False) -> None Check whether argdict meets the structure defined in self. Will recursively check nested dicts according to sub_fields and sub_variants. Raise an error if the check fails. Parameters: - **argdict** (dict) - The arg dict to be checked. - **strict** (bool) - If true, only keys defined in Argument are allowed. - **allow_ref** (bool) - If true, allow loading from external files via the `$ref` key. A deep copy of `argdict` is made internally so the caller’s data is not mutated. #### check_value(value: Any, strict: bool = False, allow_ref: bool = False) -> None Check the value without the leading key. Same as check({self.name: value}). Raise an error if the check fails. Parameters: - **value** (Any) - The value to be checked. - **strict** (bool) - If true, only keys defined in Argument are allowed. - **allow_ref** (bool) - If true, allow loading from external files via the `$ref` key. A deep copy of `value` is made internally so the caller’s data is not mutated. #### extend_subfields(sub_fields: Iterable[Argument] | None) -> None Add a list of sub fields to the current Argument. #### extend_subvariants(sub_variants: Iterable[Variant] | None) -> None Add a list of sub variants to the current Argument. #### flatten_sub(value: dict, path: list[str] | None = None) -> dict[str, Argument] #### gen_doc(path: list[str] | None = None, **kwargs: Any) -> str Generate doc string for the current Argument. #### gen_doc_body(path: list[str] | None = None, **kwargs: Any) -> str #### gen_doc_head(path: list[str] | None = None, **kwargs: Any) -> str #### gen_doc_path(path: list[str] | None = None, **kwargs: Any) -> str #### normalize(argdict: dict, inplace: bool = False, do_default: bool = True, do_alias: bool = True, trim_pattern: str | None = None, allow_ref: bool = False) -> dict Modify argdict so that it meets the Argument structure. Normalization can add default values to optional args, substitute alias by its standard names, and discard unnecessary args following given pattern. ``` -------------------------------- ### dargs.dargs.update_nodup() Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/api.md Updates a collection without adding duplicate elements. ```APIDOC ## dargs.dargs.update_nodup() ### Description Updates a collection without adding duplicate elements. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Not specified in the source) ### Request Example (Not applicable) ### Response (Not specified in the source) ``` -------------------------------- ### Cross-reference Arguments in reStructuredText Source: https://github.com/deepmodeling/dargs/blob/master/docs/sphinx.md Create cross-references to arguments using the :dargs:argument: role or the standard :ref: role, specifying the argument path. ```rst Both :dargs:argument:`this ` and :ref:`this ` will create a cross-reference to the argument! ``` -------------------------------- ### Generate JSON Schema from Argument Source: https://github.com/deepmodeling/dargs/blob/master/docs/api/dargs.md Generate a JSON schema representation from a dargs.Argument object. This schema can be used for validation or documentation purposes. ```python >>> schema = generate_json_schema(argument) >>> json.dump(schema, open('schema.json', 'w')) ``` -------------------------------- ### dargs check Sub-command Usage Source: https://github.com/deepmodeling/dargs/blob/master/docs/cli.md Details the usage of the 'check' sub-command, which validates JSON data against a specified function's arguments. ```bash dargs check [-h] -f FUNC [--no-strict] [--trim-pattern TRIM_PATTERN] [--allow-ref] [jdata ...] ```