Skip to content

Commit fa4c4a2

Browse files
authored
refactor: Reformat to respect ruff rules (#77)
* Reformat to respect ruff rules * ci fix and correction geos-geomechanics package name in ci config * fix test and linting
1 parent dc0a791 commit fa4c4a2

File tree

24 files changed

+296
-234
lines changed

24 files changed

+296
-234
lines changed

.github/workflows/typing-check.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ jobs:
1616
max-parallel: 3
1717
matrix:
1818
# add packages to check typing
19-
package-name: ["hdf5-geomechanics", "geos-posp", "geos-timehistory", "geos-utils", "geos-xml-tools", "hdf5-wrapper"]
19+
package-name: ["geos-geomechanics", "geos-posp", "geos-timehistory", "geos-utils", "geos-xml-tools", "hdf5-wrapper"]
2020

2121
steps:
2222
- uses: actions/checkout@v3
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
from .plot_time_history import getHistorySeries
1+
from .plot_time_history import getHistorySeries #noqa: F401

geos-timehistory/src/geos/timehistory/plot_time_history.py

Lines changed: 40 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,41 @@
1-
import numpy as np
1+
from typing import Any, Optional
22
from geos.hdf5_wrapper import wrapper as h5w
3-
import matplotlib as mpl
43
import matplotlib.pyplot as plt
54
import os
6-
import sys
75
import argparse
86

97
import re
108

119

12-
def isiterable( obj ):
10+
def isiterable( obj: Any ) -> bool:
11+
"""Check if input is iterable."""
1312
try:
14-
it = iter( obj )
13+
it = iter( obj ) # noqa: F841
1514
except TypeError:
1615
return False
1716
return True
1817

1918

20-
def getHistorySeries( database, variable, setname, indices=None, components=None ):
21-
"""
22-
Retrieve a series of time history structures suitable for plotting in addition to the specific set index and component for the time series
19+
def getHistorySeries( database: h5w,
20+
variable: str,
21+
setname: str,
22+
indices: Optional[ int | list[ int ] ] = None,
23+
components: Optional[ int | list[ int ] ] = None ) -> Optional[ list[ tuple[ Any, ...] ] ]:
24+
"""Retrieve a series of time history structures suitable for plotting in addition to the specific set index and component for the time series.
2325
2426
Args:
2527
database (geos.hdf5_wrapper.hdf5_wrapper): database to retrieve time history data from
2628
variable (str): the name of the time history variable for which to retrieve time-series data
2729
setname (str): the name of the index set as specified in the geosx input xml for which to query time-series data
28-
indices (int, list): the indices in the named set to query for, if None, defaults to all
29-
components (int, list): the components in the flattened data types to retrieve, defaults to all
30-
30+
indices (Optional[int | list[ int ]]): the indices in the named set to query for, if None, defaults to all
31+
components (Optional[int | list[ int ]]): the components in the flattened data types to retrieve, defaults to all
32+
3133
Returns:
32-
list: list of (time, data, idx, comp) timeseries tuples for each time history data component
34+
Optional[list[ tuple[ Any, ...] ]]: list of (time, data, idx, comp) timeseries tuples for each time history data component
3335
"""
34-
3536
set_regex = re.compile( variable + '(.*?)', re.IGNORECASE )
3637
if setname is not None:
37-
set_regex = re.compile( variable + '\s*' + str( setname ), re.IGNORECASE )
38+
set_regex = re.compile( variable + r'\s*' + str( setname ), re.IGNORECASE )
3839
time_regex = re.compile( 'Time', re.IGNORECASE ) # need to make this per-set, thought that was in already?
3940

4041
set_match = list( filter( set_regex.match, database.keys() ) )
@@ -62,39 +63,48 @@ def getHistorySeries( database, variable, setname, indices=None, components=None
6263
print(
6364
f"Error: The length of the time-series {time_match} and data-series {set_match} do not match: {time_series.shape} and {data_series.shape} !"
6465
)
65-
66+
indices1: list[ int ] = []
6667
if indices is not None:
6768
if type( indices ) is int:
68-
indices = [ indices ]
69-
if isiterable( indices ):
70-
oob_idxs = list( filter( lambda idx: not 0 <= idx < data_series.shape[ 1 ], indices ) )
69+
indices1 = [ indices ]
70+
elif isiterable( indices ):
71+
oob_idxs: list[ int ] = list(
72+
filter(
73+
lambda idx: not 0 <= idx < data_series.shape[ 1 ], # type: ignore[arg-type]
74+
indices ) ) # type: ignore[arg-type]
7175
if len( oob_idxs ) > 0:
72-
print( f"Error: The specified indices: ({', '.join(oob_idxs)}) " + "\n\t" +
73-
f" are out of the dataset index range: [0,{data_series.shape[1]})" )
74-
indices = list( set( indices ) - set( oob_idxs ) )
76+
print( f"Error: The specified indices: ({', '.join(map(str, oob_idxs))}) " + "\n\t" +
77+
f" are out of the dataset index range: [0,{data_series.shape[1]})" ) # type: ignore[arg-type]
78+
indices1 = list( set( indices ) - set( oob_idxs ) ) # type: ignore[arg-type]
7579
else:
7680
print( f"Error: unsupported indices type: {type(indices)}" )
7781
else:
78-
indices = range( data_series.shape[ 1 ] )
82+
indices1 = list( range( data_series.shape[ 1 ] ) )
7983

84+
components1: list[ int ] = []
8085
if components is not None:
8186
if type( components ) is int:
82-
components = [ components ]
83-
if isiterable( components ):
84-
oob_comps = list( filter( lambda comp: not 0 <= comp < data_series.shape[ 2 ], components ) )
87+
components1 = [ components ]
88+
elif isiterable( components ):
89+
oob_comps: list[ int ] = list(
90+
filter(
91+
lambda comp: not 0 <= comp < data_series.shape[ 2 ], # type: ignore[arg-type]
92+
components ) ) # type: ignore[arg-type]
8593
if len( oob_comps ) > 0:
86-
print( f"Error: The specified components: ({', '.join(oob_comps)}) " + "\n\t" +
94+
print( f"Error: The specified components: ({', '.join(map(str, oob_comps))}) " + "\n\t" +
8795
" is out of the dataset component range: [0,{data_series.shape[1]})" )
88-
components = list( set( components ) - set( oob_comps ) )
96+
components1 = list( set( components ) - set( oob_comps ) ) # type: ignore[arg-type]
8997
else:
9098
print( f"Error: unsupported components type: {type(components)}" )
9199
else:
92-
components = range( data_series.shape[ 2 ] )
100+
components1 = list( range( data_series.shape[ 2 ] ) )
93101

94-
return [ ( time_series[ :, 0 ], data_series[ :, idx, comp ], idx, comp ) for idx in indices for comp in components ]
102+
return [ ( time_series[ :, 0 ], data_series[ :, idx, comp ], idx, comp ) for idx in indices1
103+
for comp in components1 ]
95104

96105

97-
def commandLinePlotGen():
106+
def commandLinePlotGen() -> int:
107+
"""Parse commande line."""
98108
parser = argparse.ArgumentParser(
99109
description="A script that parses geosx HDF5 time-history files and produces time-history plots using matplotlib"
100110
)

geos-trame/pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ dependencies = [
4646
"colorcet==3.1.0",
4747
"funcy==2.0",
4848
"typing_inspect==0.9.0",
49+
"typing_extensions>=4.12",
4950
]
5051

5152
[project.optional-dependencies]

geos-xml-tools/pyproject.toml

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ requires-python = ">=3.8"
1616
dependencies = [
1717
"lxml>=4.5.0",
1818
"parameterized",
19-
"numpy"
19+
"numpy>=1.16.2",
20+
"typing_extensions>=4.12"
2021
]
2122

2223
[project.scripts]
@@ -25,3 +26,14 @@ dependencies = [
2526
test_geosx_xml_tools = "geos.xml_tools.tests.test_manager:main"
2627
check_xml_attribute_coverage = "geos.xml_tools.attribute_coverage:main"
2728
check_xml_redundancy = "geos.xml_tools.xml_redundancy_check:main"
29+
30+
[tool.pytest.ini_options]
31+
addopts = "--import-mode=importlib"
32+
console_output_style = "count"
33+
pythonpath = [".", "src"]
34+
python_classes = "Test"
35+
python_files = "test*.py"
36+
python_functions = "test*"
37+
testpaths = ["tests"]
38+
norecursedirs = "bin"
39+
filterwarnings = []
Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1 @@
1-
"""
2-
A python module that enables advanced xml features for GEOSX.
3-
"""
1+
"""A python module that enables advanced xml features for GEOSX."""

geos-xml-tools/src/geos/xml_tools/attribute_coverage.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def parse_schema_element( root: ElementTree.Element,
1212
xsd: str = '{http://www.w3.org/2001/XMLSchema}',
1313
recursive_types: Iterable[ str ] = [ 'PeriodicEvent', 'SoloEvent', 'HaltEvent' ],
1414
folders: Iterable[ str ] = [ 'src', 'examples' ] ) -> record_type:
15-
"""Parse the xml schema at the current level
15+
"""Parse the xml schema at the current level.
1616
1717
Args:
1818
root (lxml.etree.Element): the root schema node
@@ -24,7 +24,6 @@ def parse_schema_element( root: ElementTree.Element,
2424
Returns:
2525
dict: Dictionary of attributes and children for the current node
2626
"""
27-
2827
element_type = node.get( 'type' )
2928
element_name = node.get( 'name' )
3029
element_def = root.find( "%scomplexType[@name='%s']" % ( xsd, element_type ) )
@@ -49,7 +48,7 @@ def parse_schema_element( root: ElementTree.Element,
4948

5049

5150
def parse_schema( fname: str ) -> record_type:
52-
"""Parse the schema file into the xml attribute usage dict
51+
"""Parse the schema file into the xml attribute usage dict.
5352
5453
Args:
5554
fname (str): schema name
@@ -64,14 +63,14 @@ def parse_schema( fname: str ) -> record_type:
6463

6564

6665
def collect_xml_attributes_level( local_types: record_type, node: ElementTree.Element, folder: str ) -> None:
67-
"""Collect xml attribute usage at the current level
66+
"""Collect xml attribute usage at the current level.
6867
6968
Args:
7069
local_types (dict): dictionary containing attribute usage
7170
node (lxml.etree.Element): current xml node
7271
folder (str): the source folder for the current file
7372
"""
74-
for ka in node.attrib.keys():
73+
for ka in node.attrib:
7574
local_types[ 'attributes' ][ ka ][ folder ].append( node.get( ka ) )
7675

7776
for child in node:
@@ -80,7 +79,7 @@ def collect_xml_attributes_level( local_types: record_type, node: ElementTree.El
8079

8180

8281
def collect_xml_attributes( xml_types: record_type, fname: str, folder: str ) -> None:
83-
"""Collect xml attribute usage in a file
82+
"""Collect xml attribute usage in a file.
8483
8584
Args:
8685
xml_types (dict): dictionary containing attribute usage
@@ -97,15 +96,15 @@ def collect_xml_attributes( xml_types: record_type, fname: str, folder: str ) ->
9796
def write_attribute_usage_xml_level( local_types: record_type,
9897
node: ElementTree.Element,
9998
folders: Iterable[ str ] = [ 'src', 'examples' ] ) -> None:
100-
"""Write xml attribute usage file at a given level
99+
"""Write xml attribute usage file at a given level.
101100
102101
Args:
103102
local_types (dict): dict containing attribute usage at the current level
104103
node (lxml.etree.Element): current xml node
104+
folders (Iterable[ str ]): folders. Defaults to [ 'src', 'examples' ].
105105
"""
106-
107106
# Write attributes
108-
for ka in local_types[ 'attributes' ].keys():
107+
for ka in local_types[ 'attributes' ]:
109108
attribute_node = ElementTree.Element( ka )
110109
node.append( attribute_node )
111110

@@ -129,7 +128,7 @@ def write_attribute_usage_xml_level( local_types: record_type,
129128

130129

131130
def write_attribute_usage_xml( xml_types: record_type, fname: str ) -> None:
132-
"""Write xml attribute usage file
131+
"""Write xml attribute usage file.
133132
134133
Args:
135134
xml_types (dict): dictionary containing attribute usage by xml type
@@ -143,13 +142,12 @@ def write_attribute_usage_xml( xml_types: record_type, fname: str ) -> None:
143142

144143

145144
def process_xml_files( geosx_root: str, output_name: str ) -> None:
146-
"""Test for xml attribute usage
145+
"""Test for xml attribute usage.
147146
148147
Args:
149148
geosx_root (str): GEOSX root directory
150149
output_name (str): output file name
151150
"""
152-
153151
# Parse the schema
154152
geosx_root = os.path.expanduser( geosx_root )
155153
schema = '%ssrc/coreComponents/schema/schema.xsd' % ( geosx_root )
@@ -168,13 +166,12 @@ def process_xml_files( geosx_root: str, output_name: str ) -> None:
168166

169167

170168
def main() -> None:
171-
"""Entry point for the xml attribute usage test script
169+
"""Entry point for the xml attribute usage test script.
172170
173171
Args:
174172
-r/--root (str): GEOSX root directory
175173
-o/--output (str): output file name
176174
"""
177-
178175
# Parse the user arguments
179176
parser = command_line_parsers.build_attribute_coverage_input_parser()
180177
args = parser.parse_args()

geos-xml-tools/src/geos/xml_tools/command_line_parsers.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44

55
def build_preprocessor_input_parser() -> argparse.ArgumentParser:
6-
"""Build the argument parser
6+
"""Build the argument parser.
77
88
Returns:
99
argparse.ArgumentParser: The parser
@@ -29,7 +29,7 @@ def build_preprocessor_input_parser() -> argparse.ArgumentParser:
2929

3030

3131
def parse_xml_preprocessor_arguments() -> Tuple[ argparse.Namespace, Iterable[ str ] ]:
32-
"""Parse user arguments
32+
"""Parse user arguments.
3333
3434
Args:
3535
-i/--input (str): Input file name (multiple allowed)
@@ -46,12 +46,11 @@ def parse_xml_preprocessor_arguments() -> Tuple[ argparse.Namespace, Iterable[ s
4646

4747

4848
def build_xml_formatter_input_parser() -> argparse.ArgumentParser:
49-
"""Build the argument parser
49+
"""Build the argument parser.
5050
5151
Returns:
5252
argparse.ArgumentParser: the parser instance
5353
"""
54-
5554
parser = argparse.ArgumentParser()
5655
parser.add_argument( 'input', type=str, help='Input file name' )
5756
parser.add_argument( '-i', '--indent', type=int, help='Indent size', default=2 )
@@ -64,25 +63,23 @@ def build_xml_formatter_input_parser() -> argparse.ArgumentParser:
6463

6564

6665
def build_attribute_coverage_input_parser() -> argparse.ArgumentParser:
67-
"""Build attribute coverage redundancy input parser
66+
"""Build attribute coverage redundancy input parser.
6867
6968
Returns:
7069
argparse.ArgumentParser: parser instance
7170
"""
72-
7371
parser = argparse.ArgumentParser()
7472
parser.add_argument( '-r', '--root', type=str, help='GEOSX root', default='' )
7573
parser.add_argument( '-o', '--output', type=str, help='Output file name', default='attribute_test.xml' )
7674
return parser
7775

7876

7977
def build_xml_redundancy_input_parser() -> argparse.ArgumentParser:
80-
"""Build xml redundancy input parser
78+
"""Build xml redundancy input parser.
8179
8280
Returns:
8381
argparse.ArgumentParser: parser instance
8482
"""
85-
8683
parser = argparse.ArgumentParser()
8784
parser.add_argument( '-r', '--root', type=str, help='GEOSX root', default='' )
8885
return parser

0 commit comments

Comments
 (0)