Skip to content

Commit

Permalink
Merge pull request #28 from conjure-cp/print-info
Browse files Browse the repository at this point in the history
Option to print info
  • Loading branch information
ozgurakgun authored Apr 11, 2023
2 parents b640703 + 98c2317 commit 4f2cb92
Show file tree
Hide file tree
Showing 9 changed files with 84 additions and 55 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,4 @@ This section is mainly for the benefit of the project maintainers.
- git tag -a v3.1.4 -m "release v3.1.4"
- git push origin main --tags
- (Optionally) edit the version in scripts/install-colab.sh to "main" so it tracks the latest commit, and push.
- git commit scripts/install-colab.sh -m "install latest version on main when called from the main branch"
2 changes: 1 addition & 1 deletion conjure/conjure.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def solve(self, args: str, code: str, shell_params: dict) -> dict:
_, error = shell_output.communicate()
if error:
raise Exception(error.decode('utf-8'))
return conjurehelper.read_solution_json_file()
return conjurehelper.read_solution_json_file(), conjurehelper.read_info_json_file()

def get_representations(self, code: str):
conjurehelper = ConjureHelper()
Expand Down
19 changes: 16 additions & 3 deletions conjure/conjurehelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,30 @@ def read_solution_json_file(self) -> dict:
try:
for p in os.listdir('conjure-output'):
if p.endswith('solutions.json'):
with open("conjure-output/" + p) as f:
with open("conjure-output/" + p, "r") as f:
filecontent = f.read()
# there is a bug in Conjure's latest release...
if filecontent.strip() == "]":
return {"conjure_solutions": []}
else:
with open("conjure-output/" + p) as f:
with open("conjure-output/" + p, "r") as f:
return {'conjure_solutions': json.load(f)}
except Exception as e:
raise Exception('Error while reading json solution file.')
raise Exception('Error while reading the solution file.')

def read_info_json_file(self) -> dict:
try:
for p in os.listdir('conjure-output'):
if p.endswith('.eprime-info'):
with open("conjure-output/" + p, "r") as f:
obj = {}
for line in f:
[k,v] = line.split(':')
obj[k] = v
return obj
except Exception as e:
raise Exception('Error while reading the info file. ' + str(e))

def clean_tmp_files(self) -> None:
# remove conjure-output-folder
if os.path.isdir('./conjure-output'):
Expand Down
55 changes: 41 additions & 14 deletions conjure/conjuremagics.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
import asyncio
from IPython.core.magic import (
Magics, magics_class, cell_magic, line_magic)
from IPython.display import display
from IPython.display import display, Markdown, JSON
import ipywidgets as widgets
from .conjure import Conjure

import json

@magics_class
class ConjureMagics(Magics):
Expand All @@ -17,6 +17,7 @@ class ConjureMagics(Magics):
conjure_representations = {}
# print output of conjure execution
print_output = 'Yes'
print_info = 'No'
# supported solvers
conjure_solvers = ['minion', 'gecode', 'chuffed', 'glucose', 'glucose-syrup',
'lingeling', 'cadical', 'kissat', 'minisat', 'bc_minisat_all', 'nbc_minisat_all',
Expand Down Expand Up @@ -55,7 +56,7 @@ def conjure(self, args, code):
try:
if code not in self.conjure_models: # we won't add code to models if the code is already there
self.conjure_models.append(code)
resultdict = conjure.solve(args, '\n'.join(self.conjure_models), dict(self.shell.user_ns))
resultdict, infodict = conjure.solve(args, '\n'.join(self.conjure_models), dict(self.shell.user_ns))

except Exception as err:
self.conjure_models.pop()
Expand All @@ -70,20 +71,32 @@ def conjure(self, args, code):

if self.print_output == 'Yes':
if len(resultdict['conjure_solutions']) == 0:
return "No solution"
display(Markdown("No solution"))
if len(resultdict['conjure_solutions']) == 1:
return resultdict['conjure_solutions'][0]
output_md = "```json\n"
output_md += json.dumps(resultdict['conjure_solutions'][0])
output_md += "\n```"
display(Markdown(output_md))
else:
return resultdict
output_md = "```json\n"
output_md += json.dumps(resultdict)
output_md += "\n```"
display(Markdown(output_md))
else:
print("Done. Found %d solution(s)." %
len(resultdict["conjure_solutions"]))
if len(resultdict['conjure_solutions']) == 1:
print("Variables have been assigned their value in the solution")
print(
"The solution is also stored in Python variable: conjure_solutions")
elif len(resultdict['conjure_solutions'] > 1):
print("Solutions are stored in Python variable: conjure_solutions")
display(Markdown("Done. Found 1 solution."))
display(Markdown("Variables have been assigned their value in the solution"))
display(Markdown("The solution is also stored in Python variable: `conjure_solutions`"))
else:
display(Markdown("Done. Found %d solutions.\n" % len(resultdict["conjure_solutions"])))
display(Markdown("Solutions are stored in Python variable: `conjure_solutions`"))

if self.print_info == 'Yes':
output_md = "| Statistic | Value |\n"
output_md += "|:-|-:|\n"
for k,v in infodict.items():
output_md += "| %s | %s |\n" % (k.strip(), v.strip())
display(Markdown(output_md))

@line_magic
def conjure_settings(self, line):
Expand All @@ -96,6 +109,14 @@ def conjure_settings(self, line):
layout=widgets.Layout(width='80%')
)

conjure_info_rbtns = widgets.RadioButtons(
options=['Yes', 'No'],
value=self.print_info,
description='Print info',
style={'description_width': 'initial'},
layout=widgets.Layout(width='80%')
)

conjure_choose_reps_rbtns = widgets.RadioButtons(
options=self.choose_representations_options,
value=self.choose_representations_value,
Expand Down Expand Up @@ -152,6 +173,12 @@ async def f():
self.print_output = x
asyncio.ensure_future(f())

async def f0():
while True:
x = await wait_for_change(conjure_info_rbtns, 'value')
self.print_info = x
asyncio.ensure_future(f0())

async def f1():
while True:
x = await wait_for_change(conjure_solvers_rbtns, 'value')
Expand Down Expand Up @@ -182,7 +209,7 @@ async def f4():
settings_tab = widgets.Tab()
settings_tab.children = [
widgets.VBox(
[conjure_output_rbtns, conjure_choose_reps_rbtns, conjure_number_of_sols_inp]),
[conjure_output_rbtns, conjure_info_rbtns, conjure_choose_reps_rbtns, conjure_number_of_sols_inp]),
conjure_solvers_rbtns,
widgets.VBox(list(map(lambda x: x["btn"], radionbuttonobjs)))
]
Expand Down
7 changes: 3 additions & 4 deletions test/basic.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ such that
```




{'x': 4, 'xyz': 483, 'y': 8, 'z': 3}

```json
{"x": 4, "xyz": 483, "y": 8, "z": 3}
```

7 changes: 3 additions & 4 deletions test/clear.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,9 @@ such that
```




{'x': 4, 'xyz': 483, 'y': 8, 'z': 3}

```json
{"x": 4, "xyz": 483, "y": 8, "z": 3}
```



Expand Down
14 changes: 6 additions & 8 deletions test/help.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,9 @@ such that
```




{'x': 4, 'xyz': 483, 'y': 8, 'z': 3}

```json
{"x": 4, "xyz": 483, "y": 8, "z": 3}
```



Expand All @@ -70,8 +69,7 @@ x = w
```




{'x': 6}

```json
{"x": 6}
```

7 changes: 3 additions & 4 deletions test/inarg.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ such that
```




{'x': 7}

```json
{"x": 7}
```

27 changes: 10 additions & 17 deletions test/numsols.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,13 @@ such that
```


No solution


'No solution'

```json
{"conjure_solutions": []}
```



Expand Down Expand Up @@ -65,18 +68,9 @@ such that
```




{'conjure_solutions': [{'x': 0},
{'x': 1},
{'x': 2},
{'x': 3},
{'x': 4},
{'x': 5},
{'x': 6},
{'x': 8},
{'x': 9}]}

```json
{"conjure_solutions": [{"x": 0}, {"x": 1}, {"x": 2}, {"x": 3}, {"x": 4}, {"x": 5}, {"x": 6}, {"x": 8}, {"x": 9}]}
```



Expand Down Expand Up @@ -110,10 +104,9 @@ such that
```




{'x': 1, 'y': 7}

```json
{"x": 1, "y": 7}
```



Expand Down

0 comments on commit 4f2cb92

Please sign in to comment.