I have problems setting a timeout for my solver:
s = Solver()
encoding = parse_smt2_file("ex.smt2")
s.add(encoding)
s.set("timeout", 600)
solution = s.check()
but I get the following error
Traceback (most recent call last):
File "/Users/X/Documents/encode.py", line 145, in parse_polyedra("file")
File "/Users/X/Documents/encode.py", line 108, in parse_polyedra s.set("timeout",1) File "/Users/X/z3/build/z3.py", line 5765, in set Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
File "/Users/X/z3/build/z3core.py", line 3969, in Z3_solver_set_params raise Z3Exception(lib().Z3_get_error_msg_ex(a0, err))
Z3Exception: unknown parameter 'timeout'
A list of legal parameters appears, but timeout is not part of it. I took a look to this post, but the problem is not the same. As far as I understand, the parameter should be accepted, it is just that in the stable version the timeout may never happens, but there should not be problems to compile.
Anyway I installed the unstable branch and the problem persist.
I was able to use the timeout option (and it actually timeouts, and returns the best known solution in the case of optimization) with the following versions:
Python 2.7.9 (default, Mar 1 2015, 12:57:24)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import z3
>>> s = z3.Solver()
>>> s.set("timeout", 600)
>>> z3.get_version_string()
'4.4.2'
Related
In my code I get
Traceback (most recent call last):
File "Midi Projects/symbolToChord_v1.py", line 160, in <module>
mo.save("songWithChords.mid")
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mido/midifiles/midifiles.py", line 432, in save
self._save(file)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mido/midifiles/midifiles.py", line 445, in _save
write_track(outfile, track)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mido/midifiles/midifiles.py", line 251, in write_track
data.extend(encode_variable_int(msg.time))
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mido/midifiles/meta.py", line 112, in encode_variable_int
raise ValueError('variable int must be a positive integer')
ValueError: variable int must be a positive intege
I suppose I am running the latest version on MIDO.
pip freeze | grep mido
mido==1.2.9
what am doing wrong?
Any help would be greatly appreciated.
I am no expert, but I had a similar problem.
The time attribute in mido is a bit confusing as it can either represents ticks or time deltas. From the documentation (https://mido.readthedocs.io/en/latest/midi_files.html#about-the-time-attribute
):
The time attribute is used in several different ways:
inside a track, it is delta time in ticks. This must be an integer.
in messages yielded from play(), it is delta time in seconds (time elapsed since the last yielded message)
(only important to implementers) inside certain methods it is used for absolute time in ticks or seconds
You can also see this github issue for reference https://github.com/mido/mido/issues/189
Can I save the constraints I created for a z3 solver and later reload them to continue looking for more solutions?
I have learned there is the SMT-LIB2 format for such things and that z3 and z3py have an API for saving and loading in that format. Unfortunately I cannot make it work.
Here's my example program which pointlessly saves and reloads:
import z3
filename = 'z3test.smt'
# Make a solver with some arbitrary useless constraint
solver = z3.Solver()
solver.add(True)
# Save to file
smt2 = solver.sexpr()
with open(filename, mode='w', encoding='ascii') as f: # overwrite
f.write(smt2)
f.close()
# Load from file
solver.reset()
solver.from_file(filename)
It fails with:
Exception has occurred: ctypes.ArgumentError
argument 3: <class 'TypeError'>: wrong type
File "C:\Users\Marian Aldenhövel\Desktop\FridgeIQ\z3\z3-4.8.4.d6df51951f4c-x64-win\bin\python\z3\z3core.py", line 3449, in Z3_solver_from_file
_elems.f(a0, a1, _to_ascii(a2))
File "C:\Users\Marian Aldenhövel\Desktop\FridgeIQ\z3\z3-4.8.4.d6df51951f4c-x64-win\bin\python\z3\z3.py", line 6670, in from_file
_handle_parse_error(e, self.ctx)
File "C:\Users\Marian Aldenhövel\Desktop\FridgeIQ\src\z3test.py", line 17, in <module>
solver.from_file(filename)
Is this a problem with my understanding or my code? Can it be done like this? Are sexpr() and from_file() the right pair of API calls?
I am using z3 and z3py 4.8.4 from https://github.com/z3prover/z3/releases on Windows 10 64bit.
More detail if required:
I am playing with z3 in Python to find solutions for a large disection-puzzle.
To find all solutions I am calling solver.check(). When it returns a sat verdict I interpret the model as image of my puzzle solution. I then add a blocking clause ruling out that specific solution and call solver.check() again.
This works fine and I am delighted.
The runtime to find all solutions will be on the order of many days or until I get bored. I am concerned that my machine will not be running continuously for that long. It may crash, run out of power, or be rebooted for other reasons.
I can easily recreate the initial constraints which is the whole point of the program. But the blocking clauses are a runtime product and a function of how far we have gotten.
I thought I could save the state of the solver and if at runtime I find such a file restart by loading that with the blocking clauses intact and go on finding more solutions instead of having to start over.
Thank you for taking your time reading and thinking.
Marian
With z3 4.4.1 and z3 4.8.5, I would dump (and reload) the constraints in smt2 format as follows:
import z3
filename = "z3test.smt2"
x1 = z3.Real("x1")
x2 = z3.Real("x2")
solver = z3.Solver()
solver.add(x1 != x2)
#
# STORE
#
with open(filename, mode='w') as f:
f.write(solver.to_smt2())
#
# RELOAD
#
solver.reset()
constraints = z3.parse_smt2_file(filename, sorts={}, decls={})
solver.add(constraints)
print(solver)
output:
~$ python t.py
[And(x1 != x2, True)]
file z3test.smt2:
(set-info :status unknown)
(declare-fun x2 () Real)
(declare-fun x1 () Real)
(assert
(and (distinct x1 x2) true))
(check-sat)
I have no idea whether the API changed in the version you are using. Feedback is welcome.
Documentation is not helpful to me at all.
First, I tried using set() ,but I don't understand what it means by
set an instance for future calls
I could successfully feed my data using my dataset's structure described below.
So, I am not sure why I need to use set for that as it mentioned.
Here is my feature sequence of type scipy.sparse after I called nonzero() method.
[['66=1', '240=1', '286=1', '347=10', '348=1'],...]
where ... imply, same structure as previous elements
Second problem I encountered is Tagger.probability() and Tagger.marginal().
For Tagger.probability, I used the same input as Tagget.tag(), and I get this follwoing error.
and if my input is just a list instead of list of list. I get the following error.
Traceback (most recent call last):
File "cliner", line 60, in <module>
main()
File "cliner", line 49, in main
train.main()
File "C:\Users\Anak\PycharmProjects\CliNER\code\train.py", line 157, in main
train(training_list, args.model, args.format, args.use_lstm, logfile=args.log, val=val_list, test=test_list)
File "C:\Users\Anak\PycharmProjects\CliNER\code\train.py", line 189, in train
model.train(train_docs, val=val_docs, test=test_docs)
File "C:\Users\Anak\PycharmProjects\CliNER\code\model.py", line 200, in train
test_sents=test_sents, test_labels=test_labels)
File "C:\Users\Anak\PycharmProjects\CliNER\code\model.py", line 231, in train_fit
dev_split=dev_split )
File "C:\Users\Anak\PycharmProjects\CliNER\code\model.py", line 653, in generic_train
test_X=test_X, test_Y=test_Y)
File "C:\Users\Anak\PycharmProjects\CliNER\code\machine_learning\crf.py", line 220, in train
train_pred = predict(model, X) # ANAK
File "C:\Users\Anak\PycharmProjects\CliNER\code\machine_learning\crf.py", line 291, in predict
print(tagger.probability(xseq[0]))
File "pycrfsuite/_pycrfsuite.pyx", line 650, in pycrfsuite._pycrfsuite.Tagger.probability
ValueError: The numbers of items and labels differ: |x| = 12, |y| = 73
For Tagger.marginal(), I can only produce error similar to first error shown of Tagger.probabilit().
Any clue on how to use these 3 methods?? Please give me shorts example of use cases of these 3 methods.
I feel like there must be some example of these 3 methods, but I couldn't find one. Am I looking at the right place. This is the website I am reading documentation from
Additional info: I am using CliNER. in case any of you are familiar with it.
https://python-crfsuite.readthedocs.io/en/latest/pycrfsuite.html
I know this questions is over a year old, but I just had to figure out the same thing as well -- I am also leveraging some of the CliNER framework. For the CliNER specific solution, I forked the repo and rewrote the predict method in the ./code/machine_learning/crf.py file
To obtain the marginal probability, you need to add the following line to the for loop that iterates over the pycrf_instances after yseq is created (see line 196 here)
y_probs = [tagger.marginal(y, ii) for ii, y in enumerate(yseq)]
And then you can return that list of marginal probabilities from the predict method -- you will in turn be required to rewrite additional functions in the to accommodate this change.
The documentation says that the RTC clock can be initialized with the RTC.init call.
https://docs.micropython.org/en/latest/esp8266/library/machine.RTC.html
But it does not work that way:
>>>import machine
>>>rtc = machine.RTC()
>>>rtc.init((2018,4,10,17,30))
Traceback (most recent call last):
File "<stdin>", line 1 in <module>:
AttributeError: 'RTC' object has no attribute 'init'
So the documentation contradicts reality. The firmware version is v1.9.3 - downloaded the latest just a few days ago.
Most interestingly, dir(rtc) gives ['datetime','memory','alarm','alarm_left','irq','ALARM0']. It is missing several other methods: now, deinit, cancel
So where is the RTC init method, and how could it disappear?
UPDATE: I have figured out that the documentation is wrong, I need to use RTC.datetime instead of RTC.init. But it is still wrong:
>>>from machine import RTC
>>>rtc=RTC()
>>>rtc.datetime((2000,1,1,23,59,59,0,0))
>>>rtc.datetime()
(2000, 1, 3, 0, 11, 59, 3, 705)
In other words: 2000-01-01T23:59:59 suddenly became 2000-01-03T00:11:59. How?
I also could not find anything useful on the tzinfo parameter of the RTC.datetime method. It should be a number, that is clear. But what does it mean?
I have also tried midnight:
>>>rtc.datetime((2000,1,1,0,0,0,0,0))
>>>rtc.datetime()
(2000,1,1,5,0,0,1,155)
So at tzinfo=0, midnight becomes 05:00:00. I first thought that it means UTC+5 but it does not:
>>>rtc.datetime((2000,1,1,10,0,0,0,0))
>>>rtc.datetime()
(2000,1,1,5,0,0,1,155)
And finally:
>>>rtc.datetime((2000,1,1,5,0,0,0,0))
>>>rtc.datetime()
(2000,1,1,5,0,0,1,545)
This is insane! It looks like the hour part is totally ignored.
Wow this is unbelievable! After looking in the source code, it turns out that the fourth parameter is "day of the week", beginning with Monday. So the documentation is totally messed up!
tzinfo parameter does not exist.
The actual parameters in the tuple are:
(year,month,day,day of the week(0-6;Mon-Sun),hour(24 hour format),minute,second,microsecond)
It also seems that when you set the date and time, you can always set day of the week to zero, it will be automatically corrected from the year+month+day.
So for April 10th,2018 at 6:31 P.M. with 15 seconds and 0 microseconds:
>>>rtc.datetime((2018,4,10,0,18,31,15,0))
>>>rtc.datetime()
(2018, 4, 10, 1, 18, 31, 16, 808)
Where the fourth number=1 means it is the SECOND day of the week, Tuesday.
The following program generates a Z3 model that cannot be printed (that is, print solver.model() throws an exception), using the latest version of Z3 from the master git branch (commit 89c1785b):
x = Int('x')
a = Array('a', IntSort(), BoolSort())
b = Array('b', IntSort(), BoolSort())
c = Array('c', BoolSort(), BoolSort())
e = ForAll(x, Or(Not(a[x]), c[b[x]]))
print e
solver = Solver()
solver.add(e)
c = solver.check()
print c
if c == sat:
print solver.model()
produces:
ForAll(x, Or(Not(a[x]), c[b[x]]))
sat
Traceback (most recent call last):
File "z3bug.py", line 16, in <module>
print solver.model()
File "src/api/python/z3.py", line 5177, in __repr__
File "src/api/python/z3printer.py", line 939, in obj_to_string
File "src/api/python/z3printer.py", line 841, in __call__
File "src/api/python/z3printer.py", line 831, in main
File "src/api/python/z3printer.py", line 760, in pp_model
File "src/api/python/z3printer.py", line 794, in pp_func_interp
File "src/api/python/z3.py", line 5088, in else_value
File "src/api/python/z3.py", line 818, in _to_expr_ref
File "src/api/python/z3core.py", line 2307, in Z3_get_ast_kind
z3types.Z3Exception: 'invalid argument'
I can also reproduce the same behavior in the online z3py interface, at http://rise4fun.com/Z3Py/lfQG. Slightly more debugging suggests that the model's assignment for c is a z3.FuncInterp that throws an 'invalid argument' exception when you call else_value() on it.
Is this a bug in Z3, or are my expectations not quite right? My expectation was that it should always be possible to get the else_value() of a FuncInterp, since otherwise it's not a complete function, but perhaps this is not always correct?
This is a bug in the Z3 Python printer. I fixed the bug, and the fix is already available at codeplex.
http://z3.codeplex.com/SourceControl/changeset/f8014f54c18a
To get the fix (now), we have to retrieve the "work-in-progress" (unstable) branch. The fix will be available in the master branch in the next official release. To retrieve the unstable branch, we should use:
git clone https://git01.codeplex.com/z3 -b unstable
Another option is to use print solver.model().sexpr(). It will use Z3 internal printer instead of the Python based one.
Regarding else_value(), its value may not be specified by Z3. The meaning it: it is a "don't care". That is, any interpretation can be used to satisfy the formula.
I also fixed the Z3 Python API to return None when the else_value is not specified.