Skip to content

Commit ed81b85

Browse files
committed
Apply linter suggestions
1 parent 5e9064f commit ed81b85

30 files changed

+252
-189
lines changed

cfpq_algo/all_pairs/all_pairs_cfl_reachability_algo.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,3 @@ def _create_instance(
4040
4141
Algo instance encapsulates intermediate solving state between algorithm steps.
4242
"""
43-
pass

cfpq_algo/all_pairs/matrix/abstract_all_pairs_cfl_reachability.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
from abc import ABC, abstractmethod
22
from typing import List
33

4+
import graphblas
45
from graphblas.core.matrix import Matrix
56
from graphblas.core.operator import Semiring, Monoid
6-
from graphblas.semiring import any_pair
77

8+
from cfpq_algo.all_pairs.all_pairs_cfl_reachability_algo import AllPairsCflReachabilityAlgoInstance
89
from cfpq_algo.setting.algo_setting import AlgoSetting
10+
from cfpq_algo.setting.matrix_optimizer_setting import create_matrix_optimizer
11+
from cfpq_matrix.matrix_utils import complimentary_mask, identity_matrix
912
from cfpq_model.cnf_grammar_template import CnfGrammarTemplate
1013
from cfpq_model.label_decomposed_graph import OptimizedLabelDecomposedGraph, LabelDecomposedGraph
11-
from cfpq_algo.setting.matrix_optimizer_setting import get_matrix_optimizer_settings, create_matrix_optimizer
12-
from cfpq_matrix.utils import complimentary_mask, identity_matrix
13-
from cfpq_algo.all_pairs.all_pairs_cfl_reachability_algo import AllPairsCflReachabilityAlgoInstance
14-
from cfpq_model.subtractable_semiring import SubtractableSemiring
14+
from cfpq_matrix.subtractable_semiring import SubtractableSemiring
1515

1616

1717
class AbstractAllPairsCflReachabilityMatrixAlgoInstance(AllPairsCflReachabilityAlgoInstance, ABC):
@@ -22,13 +22,13 @@ def __init__(
2222
settings: List[AlgoSetting],
2323
algebraic_structure: SubtractableSemiring = SubtractableSemiring(
2424
one=True,
25-
semiring=any_pair,
26-
sub_op=lambda minuend, subtrahend: complimentary_mask(minuend, subtrahend)
25+
semiring=graphblas.semiring.any_pair,
26+
sub_op=complimentary_mask
2727
)
2828
):
2929
self.graph = OptimizedLabelDecomposedGraph.from_unoptimized(
3030
graph,
31-
matrix_optimizer = create_matrix_optimizer(settings)
31+
matrix_optimizer=create_matrix_optimizer(settings)
3232
)
3333
self.grammar = grammar
3434
self.settings = settings

cfpq_algo/all_pairs/matrix/incremental_all_pairs_cfl_reachability_algo.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
from typing import List
22

3+
from cfpq_algo.all_pairs.all_pairs_cfl_reachability_algo import (
4+
AllPairsCflReachabilityAlgoInstance,
5+
AllPairsCflReachabilityAlgo
6+
)
7+
from cfpq_algo.all_pairs.matrix.abstract_all_pairs_cfl_reachability import \
8+
AbstractAllPairsCflReachabilityMatrixAlgoInstance
39
from cfpq_algo.setting.algo_setting import AlgoSetting
410
from cfpq_model.cnf_grammar_template import CnfGrammarTemplate
511
from cfpq_model.label_decomposed_graph import LabelDecomposedGraph
6-
from cfpq_algo.all_pairs.matrix.abstract_all_pairs_cfl_reachability import \
7-
AbstractAllPairsCflReachabilityMatrixAlgoInstance
8-
from cfpq_algo.all_pairs.all_pairs_cfl_reachability_algo import AllPairsCflReachabilityAlgoInstance, \
9-
AllPairsCflReachabilityAlgo
1012

1113

12-
class IncrementalAllPairsCFLReachabilityMatrixAlgoInstance(AbstractAllPairsCflReachabilityMatrixAlgoInstance):
13-
def __init__(self, *args, **kwargs):
14-
super().__init__(*args, **kwargs)
15-
14+
class IncrementalAllPairsCFLReachabilityMatrixAlgoInstance(
15+
AbstractAllPairsCflReachabilityMatrixAlgoInstance
16+
):
1617
def compute_transitive_closure(self):
1718
front = self.graph.to_unoptimized()
1819
self.graph = self.graph.empty_copy()

cfpq_algo/all_pairs/matrix/non_incremental_all_pairs_cfl_reachability_algo.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
from typing import List
22

3+
from cfpq_algo.all_pairs.all_pairs_cfl_reachability_algo import (
4+
AllPairsCflReachabilityAlgoInstance,
5+
AllPairsCflReachabilityAlgo
6+
)
7+
from cfpq_algo.all_pairs.matrix.abstract_all_pairs_cfl_reachability import \
8+
AbstractAllPairsCflReachabilityMatrixAlgoInstance
39
from cfpq_algo.setting.algo_setting import AlgoSetting
410
from cfpq_model.cnf_grammar_template import CnfGrammarTemplate
511
from cfpq_model.label_decomposed_graph import OptimizedLabelDecomposedGraph, LabelDecomposedGraph
6-
from cfpq_algo.all_pairs.matrix.abstract_all_pairs_cfl_reachability import \
7-
AbstractAllPairsCflReachabilityMatrixAlgoInstance
8-
from cfpq_algo.all_pairs.all_pairs_cfl_reachability_algo import AllPairsCflReachabilityAlgoInstance, \
9-
AllPairsCflReachabilityAlgo
1012

1113

12-
class NonIncrementalAllPairsCFLReachabilityMatrixAlgoInstance(AbstractAllPairsCflReachabilityMatrixAlgoInstance):
13-
def __init__(self, *args, **kwargs):
14-
super().__init__(*args, **kwargs)
15-
14+
class NonIncrementalAllPairsCFLReachabilityMatrixAlgoInstance(
15+
AbstractAllPairsCflReachabilityMatrixAlgoInstance
16+
):
1617
def compute_transitive_closure(self) -> OptimizedLabelDecomposedGraph:
1718
old_nvals = self.graph.nvals
1819
while True:

cfpq_algo/setting/algo_settings_manager.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@
44

55
from cfpq_algo.setting.algo_setting import AlgoSetting
66
from cfpq_algo.setting.preprocessor_setting import IndexExplodingPreProcessorSetting
7-
from cfpq_algo.setting.matrix_optimizer_setting import OptimizeEmptyMatrixSetting, LazyAddMatrixSetting, \
7+
from cfpq_algo.setting.matrix_optimizer_setting import (
8+
OptimizeEmptyMatrixSetting,
9+
LazyAddMatrixSetting,
810
OptimizeFormatMatrixSetting
11+
)
912

1013

1114
class AlgoSettingsManager:
@@ -34,4 +37,5 @@ def read_args(self, args: Namespace) -> List[AlgoSetting]:
3437
def report_unused(self):
3538
for setting in self._settings:
3639
if setting.was_specified_by_user and not setting.was_used_by_algo:
37-
warnings.warn(f"Algo setting '{setting.flag_name}' was specified, but was not used by the algorithm.")
40+
warnings.warn(f"Algo setting '{setting.flag_name}' was specified, "
41+
"but was not used by the algorithm.")

cfpq_algo/setting/matrix_optimizer_setting.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@
1212
from cfpq_matrix.empty_optimized_matrix import EmptyOptimizedMatrix
1313

1414

15-
def create_matrix_optimizer(algo_settings: List[AlgoSetting]) -> Callable[[Matrix], OptimizedMatrix]:
15+
def create_matrix_optimizer(
16+
algo_settings: List[AlgoSetting]
17+
) -> Callable[[Matrix], OptimizedMatrix]:
1618
optimizer_settings = get_matrix_optimizer_settings(algo_settings)
1719
return lambda matrix: optimize_matrix(matrix, optimizer_settings)
1820

@@ -44,7 +46,7 @@ def add_arg(self, parser: ArgumentParser):
4446
)
4547

4648
def read_arg(self, args: Namespace):
47-
if args.__getattribute__(self.var_name) is True:
49+
if getattr(args, self.var_name) is True:
4850
self.was_specified_by_user = True
4951
self.is_enabled = False
5052

cfpq_algo/setting/preprocessor_setting.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from cfpq_algo.setting.algo_setting import AlgoSetting
66
from cfpq_model.cnf_grammar_template import CnfGrammarTemplate
77
from cfpq_model.label_decomposed_graph import LabelDecomposedGraph
8-
from cfpq_model.utils import explode_indices
8+
from cfpq_model.model_utils import explode_indices
99

1010

1111
class PreProcessorSetting(AlgoSetting, ABC):

cfpq_cli/run_all_pairs_cflr.py

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,51 +4,52 @@
44
from time import time
55
from typing import Optional, List
66

7+
from cfpq_algo.all_pairs.all_cfl_pairs_reachability_impls import \
8+
ALL_PAIRS_CFL_REACHABILITY_ALGO_NAMES, \
9+
get_all_pairs_cfl_reachability_algo
710
from cfpq_algo.setting.algo_setting import AlgoSetting
811
from cfpq_algo.setting.algo_settings_manager import AlgoSettingsManager
912
from cfpq_algo.setting.preprocessor_setting import preprocess_graph_and_grammar
13+
from cfpq_cli.time_limit import time_limit, TimeoutException
1014
from cfpq_model.cnf_grammar_template import CnfGrammarTemplate
1115
from cfpq_model.label_decomposed_graph import LabelDecomposedGraph
12-
from cfpq_algo.all_pairs.all_cfl_pairs_reachability_impls import \
13-
ALL_PAIRS_CFL_REACHABILITY_ALGO_NAMES, \
14-
get_all_pairs_cfl_reachability_algo
15-
from cfpq_cli.time_limit import time_limit, TimeoutException
1616

1717

1818
def run_all_pairs_cflr(
1919
algo_name: str,
2020
graph_path: str,
2121
grammar_path: str,
2222
time_limit_sec: Optional[int],
23-
out_file: Optional[str],
23+
out_path: Optional[str],
2424
settings: List[AlgoSetting]
2525
):
2626
algo = get_all_pairs_cfl_reachability_algo(algo_name)
2727
graph = LabelDecomposedGraph.read_from_pocr_graph_file(graph_path)
2828
grammar = CnfGrammarTemplate.read_from_pocr_cnf_file(grammar_path)
2929
graph, grammar = preprocess_graph_and_grammar(graph, grammar, settings)
3030
try:
31-
with (time_limit(time_limit_sec)):
31+
with time_limit(time_limit_sec):
3232
start = time()
3333
res = algo.solve(graph=graph, grammar=grammar, settings=settings)
3434
finish = time()
3535
print(f"AnalysisTime\t{finish - start}")
3636
print(f"#SEdges\t{res.nvals}")
37-
if out_file is not None:
38-
out_dir = os.path.dirname(out_file)
37+
if out_path is not None:
38+
out_dir = os.path.dirname(out_path)
3939
if out_dir != "" and not os.path.exists(out_dir):
4040
os.makedirs(out_dir)
41-
with open(out_file, 'w') as out_file:
41+
with open(out_path, 'w', encoding="utf-8") as out_file:
4242
for (source, target) in res:
4343
out_file.write(f"{source}\t{target}\n")
4444
except TimeoutException:
45-
print(f"AnalysisTime\tNaN")
46-
print(f"#SEdges\tNaN")
45+
print("AnalysisTime\tNaN")
46+
print("#SEdges\tNaN")
4747

4848

4949
def main(raw_args: List[str]):
5050
parser = argparse.ArgumentParser(
51-
description="Solves the Context-Free Language Reachability (CFL-R) problem for all vertex pairs.",
51+
description="Solves the Context-Free Language Reachability (CFL-R) problem "
52+
"for all vertex pairs.",
5253
)
5354
parser.add_argument(dest='algo', choices=ALL_PAIRS_CFL_REACHABILITY_ALGO_NAMES,
5455
help='Specifies the algorithm to use.')
@@ -62,7 +63,8 @@ def main(raw_args: List[str]):
6263
help='Specifies the grammar file in POCR format. '
6364
'Non-empty lines (except the last two) denote grammar rules: '
6465
'complex rules (`<NON_TERMINAL> <SYMBOL_1> <SYMBOL_2>`), '
65-
'simple rules (`<NON_TERMINAL> <TERMINAL>`), and epsilon rules (`<NON_TERMINAL>`), '
66+
'simple rules (`<NON_TERMINAL> <TERMINAL>`), '
67+
'and epsilon rules (`<NON_TERMINAL>`), '
6668
'with values separated by whitespace characters. '
6769
'Indexed symbol names should end with `_i`. '
6870
'The final two lines define the starting non-terminal as: '
@@ -72,8 +74,9 @@ def main(raw_args: List[str]):
7274
parser.add_argument('--out', dest='out', default=None,
7375
help='Specifies the output file for saving vertex pairs. '
7476
'The line format is: `[START_VERTEX]\t[END_VERTEX]`. '
75-
'Each line indicates a path exists from [START_VERTEX] to [END_VERTEX], '
76-
'labels along which spell a word from the specified Context-Free Language (CFL).'
77+
'Each line indicates a path exists from [START_VERTEX] '
78+
'to [END_VERTEX], labels along which spell a word from '
79+
'the specified Context-Free Language (CFL).'
7780
)
7881
settings_manager = AlgoSettingsManager()
7982
settings_manager.add_args(parser)
@@ -83,7 +86,7 @@ def main(raw_args: List[str]):
8386
graph_path=args.graph,
8487
grammar_path=args.grammar,
8588
time_limit_sec=args.time_limit,
86-
out_file=args.out,
89+
out_path=args.out,
8790
settings=settings_manager.read_args(args)
8891
)
8992
settings_manager.report_unused()

cfpq_eval/eval_all_pairs_cflr.py

Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
def is_enough_data_collected(result_file_path: Path, rounds: int):
2323
try:
24-
with open(result_file_path, 'r') as file:
24+
with open(result_file_path, 'r', encoding="utf-8") as file:
2525
reader = list(csv.reader(file))
2626
if len(reader) - 1 >= rounds or any("OOT" in row or "OOM" in row for row in reader):
2727
return True
@@ -31,19 +31,19 @@ def is_enough_data_collected(result_file_path: Path, rounds: int):
3131

3232

3333
def run_experiment(
34-
algo_settings: str,
35-
algo_name: str,
36-
graph_path: Path,
37-
grammar_path: Path,
38-
rounds: int,
39-
timeout_sec: Optional[int],
40-
result_file_path: Path
34+
algo_settings: str,
35+
algo_name: str,
36+
graph_path: Path,
37+
grammar_path: Path,
38+
rounds: int,
39+
timeout_sec: Optional[int],
40+
result_file_path: Path
4141
):
4242
graph_base_name = graph_path.stem
4343
grammar_base_name = grammar_path.stem
4444

4545
if not os.path.exists(result_file_path):
46-
with open(result_file_path, 'w', newline='') as csvfile:
46+
with open(result_file_path, 'w', newline='', encoding="utf-8") as csvfile:
4747
writer = csv.writer(csvfile)
4848
writer.writerow(["algo", "graph", "grammar", "s_edges", "ram_kb", "time_sec"])
4949

@@ -80,7 +80,7 @@ def run_experiment(
8080
)
8181
s_edges, ram_kb, time_sec = "OOM", "OOM", "OOM"
8282

83-
with open(result_file_path, 'a', newline='') as csvfile:
83+
with open(result_file_path, 'a', newline='', encoding="utf-8") as csvfile:
8484
print(f" {s_edges} {ram_kb} {time_sec}")
8585
writer = csv.writer(csvfile)
8686
writer.writerow([
@@ -106,7 +106,7 @@ def reduce_result_file_to_one_row(result_file_path: Path) -> pd.DataFrame:
106106
return df
107107

108108
df['ram_gb'] = df['ram_kb'].apply(
109-
lambda x: x / 10**6 if isinstance(x, int) or isinstance(x, float) else x
109+
lambda x: x / 10 ** 6 if isinstance(x, (int, float)) else x
110110
)
111111
assert df['algo'].nunique() <= 1
112112
assert df['graph'].nunique() <= 1
@@ -117,8 +117,8 @@ def reduce_result_file_to_one_row(result_file_path: Path) -> pd.DataFrame:
117117
else:
118118
unique_s_edges = df['s_edges'].unique()
119119
if len(unique_s_edges) > 1:
120-
warnings.warn(f"Inconsistent 's_edges' values {unique_s_edges} found in {result_file_path}. "
121-
f"Using first 's_edges' value.")
120+
warnings.warn(f"Inconsistent 's_edges' values {unique_s_edges} "
121+
f"found in {result_file_path}. Using first 's_edges' value.")
122122

123123
ram_gb_mean = df['ram_gb'].mean()
124124
time_sec_mean = df['time_sec'].mean()
@@ -135,13 +135,15 @@ def reduce_result_file_to_one_row(result_file_path: Path) -> pd.DataFrame:
135135
'ram_gb': [
136136
round_to_significant_digits(ram_gb_mean)
137137
if ram_gb_std < DISPLAY_STD_THRESHOLD * ram_gb_mean
138-
else f"{round_to_significant_digits(ram_gb_mean)} ± {round_to_significant_digits(ram_gb_std)}"
138+
else f"{round_to_significant_digits(ram_gb_mean)}"
139+
f" ± {round_to_significant_digits(ram_gb_std)}"
139140
],
140141
'time_sec': [
141142
# Graspan reports analysis time in whole seconds, so it may report 0
142143
(round_to_significant_digits(time_sec_mean) if time_sec_mean != 0 else "< 1")
143144
if time_sec_std < DISPLAY_STD_THRESHOLD * time_sec_mean
144-
else f"{round_to_significant_digits(time_sec_mean)} ± {round_to_significant_digits(time_sec_std)}"
145+
else f"{round_to_significant_digits(time_sec_mean)}"
146+
f" ± {round_to_significant_digits(time_sec_std)}"
145147
]
146148
})
147149
return df
@@ -205,7 +207,10 @@ def display_results(result_files_paths: List[Path]) -> None:
205207
print()
206208

207209
df = pd.concat(
208-
[reduce_result_file_to_one_row(result_file_path) for result_file_path in result_files_paths],
210+
[
211+
reduce_result_file_to_one_row(result_file_path)
212+
for result_file_path in result_files_paths
213+
],
209214
ignore_index=True
210215
)
211216
df['algo'] = pd.Categorical(df['algo'], categories=df['algo'].unique())
@@ -219,14 +224,14 @@ def display_results(result_files_paths: List[Path]) -> None:
219224

220225

221226
def eval_all_pairs_cflr(
222-
algo_config: Path,
223-
data_config: Path,
224-
result_path: Path,
225-
rounds: Optional[int],
226-
timeout_sec: Optional[int],
227+
algo_config: Path,
228+
data_config: Path,
229+
result_path: Path,
230+
rounds: Optional[int],
231+
timeout_sec: Optional[int],
227232
):
228233
result_files_paths = []
229-
with open(algo_config, mode='r') as algo_file:
234+
with open(algo_config, mode='r', encoding="utf-8") as algo_file:
230235
algo_reader = csv.DictReader(algo_file)
231236
for algo_row in algo_reader:
232237
algo_name = algo_row['algo_name']
@@ -236,7 +241,7 @@ def eval_all_pairs_cflr(
236241
if not os.path.exists(algo_result_path):
237242
os.makedirs(algo_result_path)
238243

239-
with open(data_config, mode='r') as data_file:
244+
with open(data_config, mode='r', encoding="utf-8") as data_file:
240245
data_reader = csv.DictReader(data_file)
241246
for data_row in data_reader:
242247
graph_path = Path(data_row['graph_path']).absolute()
@@ -260,7 +265,8 @@ def eval_all_pairs_cflr(
260265

261266
def main(raw_args: List[str]):
262267
parser = argparse.ArgumentParser(
263-
description='Evaluates all vertex pairs Context-Free Language Reachability (CFL-R) algorithms.'
268+
description='Evaluates all vertex pairs '
269+
'Context-Free Language Reachability (CFL-R) algorithms.'
264270
)
265271

266272
parser.add_argument('algo_config', type=str,
@@ -284,5 +290,5 @@ def main(raw_args: List[str]):
284290
)
285291

286292

287-
if __name__ == "__main__": # pragma: no cover
293+
if __name__ == "__main__": # pragma: no cover
288294
main(raw_args=sys.argv[1:]) # pragma: no cover

0 commit comments

Comments
 (0)