-
-
Notifications
You must be signed in to change notification settings - Fork 12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add py2bexp CLI tool to convert qlassf functions to boolean expressions #56
Merged
Merged
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c084f81
Add py2bexp CLI tool to convert qlassf functions to boolean expressions
tomv42 ac43b51
Fix unit tests
tomv42 6c9c7f9
Add assertions in unit tests
tomv42 922c06d
Comment unused import
tomv42 7544f82
Correct dimacs unit test
tomv42 6805980
Clean test_tools.py
tomv42 40ab93c
Moved `find_last_qlassf` function to `tools.py`
tomv42 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,145 @@ | ||
#!/usr/bin/env python3 | ||
|
||
# Copyright 2023-2024 Davide Gessa | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import argparse | ||
import sys | ||
|
||
import sympy | ||
from sympy.logic.boolalg import to_anf, to_cnf, to_dnf, to_nnf | ||
|
||
import qlasskit | ||
from qlasskit.qlassfun import QlassF | ||
from qlasskit.tools.utils import parse_str | ||
|
||
|
||
def read_input(input_file): | ||
if input_file == "-": | ||
return sys.stdin.read() | ||
with open(input_file, "r") as file: | ||
return file.read() | ||
|
||
|
||
def find_last_qlassf(qlassf_list): | ||
return qlassf_list[-1][1] if qlassf_list else None | ||
|
||
|
||
def convert_to_bool_expression(qlassf: QlassF, form: str): | ||
combined_expr = sympy.And(*[expr[1] for expr in qlassf.expressions]) | ||
|
||
if form == "anf": | ||
return to_anf(combined_expr) | ||
elif form == "cnf": | ||
return to_cnf(combined_expr, simplify=True) | ||
elif form == "dnf": | ||
return to_dnf(combined_expr, simplify=True) | ||
elif form == "nnf": | ||
return to_nnf(combined_expr, simplify=True) | ||
return combined_expr # Default case if no specific form is requested | ||
|
||
|
||
def convert_to_dimacs(expr): | ||
clauses = to_cnf(expr, simplify=True).args | ||
if len(clauses) == 1 and isinstance(clauses[0], sympy.Symbol): | ||
clauses = [clauses] | ||
|
||
var_dict = {symbol: i + 1 for i, symbol in enumerate(expr.free_symbols)} | ||
dimacs_clauses = [] | ||
|
||
for clause in clauses: | ||
if isinstance(clause, sympy.Or): | ||
clause_literals = clause.args | ||
else: | ||
clause_literals = [clause] | ||
|
||
dimacs_clause = [] | ||
for lit in clause_literals: | ||
if isinstance(lit, sympy.Not): | ||
dimacs_clause.append(-var_dict[lit.args[0]]) | ||
else: | ||
dimacs_clause.append(var_dict[lit]) | ||
dimacs_clauses.append(dimacs_clause) | ||
|
||
num_vars = len(var_dict) | ||
num_clauses = len(dimacs_clauses) | ||
dimacs_str = f"p cnf {num_vars} {num_clauses}\n" | ||
for clause in dimacs_clauses: | ||
dimacs_str += " ".join(map(str, clause)) + " 0\n" | ||
return dimacs_str | ||
|
||
|
||
def output_result(result, output_file, output_format, form): | ||
if output_format == "dimacs": | ||
if form != "cnf": | ||
print( | ||
"Warning: DIMACS format is only supported for CNF form. Converting to CNF." | ||
) | ||
result = to_cnf(result, simplify=True) | ||
result = convert_to_dimacs(result) | ||
if output_file == "-": | ||
print(result) | ||
else: | ||
with open(output_file, "w") as file: | ||
file.write(str(result)) | ||
|
||
|
||
def main(): | ||
parser = argparse.ArgumentParser( | ||
description="Convert qlassf functions in a Python script to boolean expressions." | ||
) | ||
parser.add_argument( | ||
"-i", "--input-file", default="-", help="Input file (default: stdin)" | ||
) | ||
parser.add_argument("-e", "--entrypoint", help="Entrypoint function name") | ||
parser.add_argument( | ||
"-o", "--output", default="-", help="Output file (default: stdout)" | ||
) | ||
parser.add_argument( | ||
"-f", | ||
"--form", | ||
choices=["anf", "cnf", "dnf", "nnf"], | ||
default="sympy", | ||
help="Expression form (default: sympy)", | ||
) | ||
parser.add_argument( | ||
"-t", | ||
"--format", | ||
choices=["sympy", "dimacs"], | ||
default="sympy", | ||
help="Output format (default: sympy)", | ||
) | ||
parser.add_argument( | ||
"-v", "--version", action="version", version=f"qlasskit {qlasskit.__version__}" | ||
) | ||
|
||
args = parser.parse_args() | ||
|
||
script = read_input(args.input_file) | ||
qlassf_list = parse_str(script) | ||
|
||
if args.entrypoint: | ||
qlassf = next((f[1] for f in qlassf_list if f[0] == args.entrypoint), None) | ||
else: | ||
qlassf = find_last_qlassf(qlassf_list) | ||
|
||
if qlassf: | ||
bool_expr = convert_to_bool_expression(qlassf, args.form) | ||
output_result(bool_expr, args.output, args.format, args.form) | ||
else: | ||
print("No qlassf function found", file=sys.stderr) | ||
|
||
|
||
if __name__ == "__main__": | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
move this function to tools.py