Skip to content

Commit

Permalink
Merge pull request #39 from alchem0x2A/master
Browse files Browse the repository at this point in the history
Docstring enhancing and sparc version detection
  • Loading branch information
alchem0x2A authored Jan 17, 2024
2 parents a18575f + af288aa commit 3a7c15c
Show file tree
Hide file tree
Showing 15 changed files with 632 additions and 242 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/installation_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ jobs:
# python -m pytest -svv tests/ --cov=sparc --cov-report=json --cov-report=html
export SPARC_TESTS_DIR="./SPARC-master/tests"
export ASE_SPARC_COMMAND="mpirun -n 1 sparc"
export SPARC_DOC_PATH="./SPARC-master/doc"
export SPARC_DOC_PATH="./SPARC-master/doc/.LaTeX"
coverage run -a -m pytest -svv tests/
coverage json --omit="tests/*.py"
coverage html --omit="tests/*.py"
Expand Down
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -773,3 +773,10 @@ al-eos-sparc.traj
examples/ex1-ase/
/SPARC-master/
/master.zip
/*.ion
/*.static
/*.out*
/*.static*
/*.inpt*
/*.log
/*.psp8
17 changes: 14 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,21 @@ schema used by the API at sparc.sparc_json_api.default_json_api
```

The schema file is generated from SPARC's LaTeX documentation. In
upcoming releases of `SPARC-X-API`, we're aiming to provide users
the flexibility to use their own custom schema files. This would be
upcoming releases of `SPARC-X-API`, we're aiming to provide users the
flexibility to use their own custom schema files. This would be
particularly useful for those who might be testing a development
branch of SPARC.
branch of SPARC. By default, the JSON schema is packaged under
`sparc/sparc_json_api` directory. If you have another version of SPARC
source code, you can set the environment variable `$SPARC_DOC_PATH` to
the directory containing the LaTeX codes for the documentation, such
as `<SPARC-source-code-root>/doc/.LaTeX`. If you obtain `sparc-x` from
the conda method as mentioned above, By default, the JSON schema is
packaged under `sparc/sparc_json_api` directory. If you have another
version of SPARC source code, you can set the environment variable
`$SPARC_DOC_PATH` is automatically set to
`<conda-env-root>/share/doc/sparc/.LaTeX`. Setting up the environment
variable `$SPARC_DOC_PATH` helps loading the correct JSON schame that
is compatible with your SPARC binary code.

### C) SPARC Command Configuration

Expand Down
104 changes: 88 additions & 16 deletions sparc/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,33 @@
import numpy as np

curdir = Path(__file__).parent
# TODO: must clean the api directory
default_api_dir = curdir / "sparc_json_api"
default_json_api = default_api_dir / "parameters.json"


class SparcAPI:
"""
An interface to the parameter settings in SPARC-X calculator. User can use the
SparcAPI instance to validate and translate parameters that matches a certain
version of the SPARC-X code.
Attributes:
sparc_version (str): Version of SPARC.
categories (dict): Categories of parameters.
parameters (dict): Detailed parameters information.
other_parameters (dict): Additional parameters.
data_types (dict): Supported data types.
Methods:
get_parameter_dict(parameter): Retrieves dictionary for a specific parameter.
help_info(parameter): Provides detailed information about a parameter.
validate_input(parameter, input): Validates user input against the expected parameter type.
convert_string_to_value(parameter, string): Converts string input to the appropriate data type.
convert_value_to_string(parameter, value): Converts a value to a string representation.
"""

def __init__(self, json_api=None):
"""Initialize the API from a json file"""
# TODO: like ase io, adapt to both file and fio
""" """
if json_api is None:
json_api = Path(default_json_api)
else:
Expand All @@ -26,9 +44,20 @@ def __init__(self, json_api=None):
self.parameters = json_data["parameters"]
self.other_parameters = json_data["other_parameters"]
self.data_types = json_data["data_types"]
# TODO: Make a parameters by categories

def get_parameter_dict(self, parameter):
"""
Retrieves the dictionary for a specified parameter.
Args:
parameter (str): The name of the parameter.
Returns:
dict: Dictionary containing details of the parameter.
Raises:
KeyError: If the parameter is not known to the SPARC version.
"""
parameter = parameter.upper()
if parameter not in self.parameters.keys():
raise KeyError(
Expand All @@ -37,6 +66,14 @@ def get_parameter_dict(self, parameter):
return self.parameters[parameter]

def help_info(self, parameter):
"""Provides a detailed information string for a given parameter.
Args:
parameter (str): The name of the parameter to get information for.
Returns:
str: A formatted string with detailed information about the parameter.
"""
pdict = self.get_parameter_dict(parameter)
message = "\n".join(
[
Expand All @@ -57,13 +94,18 @@ def help_info(self, parameter):
return message

def validate_input(self, parameter, input):
"""Give a string for a parameter,
determine if the input follows the type
"""
Validates if the given input is appropriate for the specified parameter's type.
Args:
parameter (str): The name of the parameter.
input: The input to validate, can be of various types (string, int, float, numpy types).
input can be either a string or a 'direct' data type,
like python float or numpy float
Returns:
bool: True if input is valid, False otherwise.
TODO: there are many exceptions in array types, should enumerate
Raises:
ValueError: If the data type of the parameter is not supported.
"""
is_input_string = isinstance(input, str)
pdict = self.get_parameter_dict(parameter)
Expand Down Expand Up @@ -97,7 +139,6 @@ def validate_input(self, parameter, input):
except Exception:
return False
elif "array" in dtype:
# import pdb; pdb.set_trace()
if is_input_string:
if ("." in input) and ("integer" in dtype):
warn(
Expand All @@ -109,7 +150,6 @@ def validate_input(self, parameter, input):
)
)
try:
# import pdb; pdb.set_trace()
arr = np.genfromtxt(input.splitlines(), dtype=float, ndmin=1)
# In valid input with nan
if np.isnan(arr).any():
Expand All @@ -131,14 +171,24 @@ def validate_input(self, parameter, input):
except Exception:
arr = np.array(0.0)
return len(arr.shape) > 0
# elif dtype == "other":
# # Any "other"-type inputs should be provided only using string
# return is_input_string
else:
raise ValueError(f"Data type {dtype} is not supported!")

def convert_string_to_value(self, parameter, string):
"""Convert a string input into valie parameter type"""
"""
Converts a string input to the appropriate value type of the parameter.
Args:
parameter (str): The name of the parameter.
string (str): The string input to convert.
Returns:
The converted value, type depends on parameter's expected type.
Raises:
TypeError: If the input is not a string.
ValueError: If the string is not a valid input for the parameter.
"""

# Special case, the string may be a multiline string-array!
if isinstance(string, list):
Expand Down Expand Up @@ -189,7 +239,19 @@ def convert_string_to_value(self, parameter, string):
return value

def convert_value_to_string(self, parameter, value):
"""Convert a valid value for the paramter to string for writing"""
"""
Converts a value to its string representation based on the parameter type.
Args:
parameter (str): The name of the parameter.
value: The value to convert.
Returns:
str: The string representation of the value.
Raises:
ValueError: If the value is not valid for the parameter.
"""

is_input_string = isinstance(value, str)
if not self.validate_input(parameter, value):
Expand Down Expand Up @@ -224,6 +286,16 @@ def convert_value_to_string(self, parameter, value):


def _array_to_string(arr, format):
"""
Converts an array to a string representation based on the specified format.
Args:
arr (array): The array to convert.
format (str): The format type ('integer array', 'double array', etc.).
Returns:
str: String representation of the array.
"""
arr = np.array(arr)
if arr.ndim == 1:
arr = arr.reshape(1, -1)
Expand Down
Loading

0 comments on commit 3a7c15c

Please sign in to comment.