In Sympy be, why does get_field fail for the finite field GF(9) (defined as a finite extension of GF(3))? - field

I'm trying to use the groebner function in Sympy to solve a system of multivariate polynomials in GF(9) = GF(3)[g]/(g**2 + 1). When I do this I get the error
File
"/Applications/Spyder.app/Contents/Resources/lib/python3.9/sympy/polys/groebnertools.py",
line 37, in groebner
orig, ring = ring, ring.clone(domain=domain.get_field())
File
"/Applications/Spyder.app/Contents/Resources/lib/python3.9/sympy/polys/domains/domain.py",
line 846, in get_field
raise DomainError('there is no field associated with %s' % self)
DomainError: there is no field associated with GF(3)[g]/(g**2 + 1)
I reduced the code to the minimum that gives this get_field() failure. I also looked at is_field ... which was True!?
I know that GF and similar mechanisms fail for non-prime finite fields, but I thought that all would be well, if I defined my own GF(9) using a finite extension.
Am I missing something, or does get_field() not realize that gf9 is a field?
My minimal code
from sympy import Symbol, Poly
from sympy.polys.agca.extensions import FiniteExtension
g = Symbol('g')
gf9 = FiniteExtension(Poly(g**2 + 1, g, modulus=3)) # correct GF(9)
print('gf9 = ', gf9, 'type =', type(gf9), 'is_field?', gf9.is_Field)
print()
print('field associated with', gf9, '=', gf9.get_field())
Response
gf9 = GF(3)[g]/(g**2 + 1) is_field? True
Traceback (most recent call last):
File
"/Applications/Spyder.app/Contents/Resources/lib/python3.9/spyder_kernels/py3compat.py",
line 356, in compat_exec
exec(code, globals, locals)
File "/Users/rick/.spyder-py3/temp.py", line 17, in
print('field associated with', gf9, '=', gf9.get_field())
File
"/Applications/Spyder.app/Contents/Resources/lib/python3.9/sympy/polys/domains/domain.py",
line 846, in get_field
raise DomainError('there is no field associated with %s' % self)
DomainError: there is no field associated with GF(3)[g]/(g**2 + 1)
Any help appreciated :)
Addendum: I just noticed that I never asked my real question: How can I use Sympy's groebner function with GF(3)[g]/(g**2 + 1)?

Related

Why does the result of my sage command becomes question mark?

I'm trying to use sagetex package, but then I found this kind of problem when running the code
the result
Here is the code I tried to run:
\documentclass{article}
\usepackage{sagetex}
\usepackage{graphicx}
\usepackage{fancyvrb}
\begin{document}
Using Sage\TeX, one can use Sage to compute things and put them into
your \LaTeX{} document. For example, there are
$\sage{number_of_partitions(1269)}$ integer partitions of $1269$.
You don't need to compute the number yourself, or even cut and paste
it from somewhere.
Here's some Sage code:
\begin{sageblock}
f(x) = exp(x) * sin(2*x)
\end{sageblock}
The second derivative of $f$ is
\[
\frac{\mathrm{d}^{2}}{\mathrm{d}x^{2}} \sage{f(x)} =
\sage{diff(f, x, 2)(x)}.
\]
Here's a plot of $f$ from $-1$ to $1$:
\sageplot{plot(f, -1, 1)}
\sageplot[scale=.5]{plot3d(sin(pi*(x^2+y^2))/2,(x,-1,1),(y,-1,1))}
we know that 2010 factors to $\sage{factor(2010)}$
\begin{sagesilent}
m=identity_matrix(QQ,3)
m[0]=m[0]+m[1]
m[1]=m[1]-m[2]
m[2]=m[2]-2*m[1]
m[1]=m[1]+3*m[0]
m[0]=2*m[0]
\end{sagesilent}
Compute the rref of $\sage{m}$
\begin{sageblock}
g(x)=taylor(tan(x),x,0,10)
\end{sageblock}
$$\tan(x)=\sage{g(x)}$$
\end{document}
When I try to compile this, I get:
**** Error in Sage code on line 23 of file.tex! Traceback follows.
Traceback (most recent call last):
File "file.sagetex.sage.py", line 39, in <module>
_st_.plot(_sage_const_1 , format='notprovided', _p_=plot3d(sin(pi*(x**_sage_const_2 +y**_sage_const_2 ))/_sage_const_2 ,(x,-_sage_const_1 ,_sage_const_1 ),(y,-_sage_const_1 ,_sage_const_1 )))
NameError: name 'y' is not defined
Once a single error occurs, the rest of the Sage output may be lost, leading to all of the question marks. The problem is this line:
\sageplot[scale=.5]{plot3d(sin(pi*(x^2+y^2))/2,(x,-1,1),(y,-1,1))}
and in particular, you have not defined y. (In SageMath, x is automatically defined to be a variable, but not y.) If you add this before the plot, it should work:
\begin{sagesilent}
var('y')
\end{sagesilent}

How to use marginal, probability method in pycrfsuite.Tagger()

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.

Biopython fail to access hetero-residue directly

I am able to access directly a residue from the protein 1n31 by using:
residue = structure[0]['A'][100]
However, when I try to access a hetero-residue, like:
residue = structure[0]['A'][2003]
I get the error message:
File "<stdin>", line 1, in <module>
File "/home/azevedo/.local/lib/python3.5/site-packages/Bio/PDB/Chain.py", line 94, in __getitem__
return Entity.__getitem__(self, id)
File "/home/azevedo/.local/lib/python3.5/site-packages/Bio/PDB/Entity.py", line 41, in __getitem__
return self.child_dict[id]
KeyError: (' ', 2003, ' ')
Why is it happening? How can I directly access a hetero-residue?
Short answer
structure[0]['A'][('H_CYS', 2003, ' ')]
will give you the desired residue
<Residue CYS het=H_CYS resseq=2003 icode= >
BioPython's PDB indexes
BioPython's PDB residue index uses a tuple internally. It consists of hetero flag, sequence identifier and insertion code. For your residue 1000 it would be (' ', 100, ' '), in case of your hetero-residue it would be ('H_CYS', 2003, ' ').
If you provide only an integer as an index it gets translated to (' ', your_int, ' ').
The code can be found in the function _translate_id
General solution
If you don't know the hetero flag in advance, you could use your own function
def get_residue_by_number(residues, number):
for residue in residues:
if residue.id[1] == number:
return residue
get_residue_by_number(structure[0]['A'].get_residues(), 2003)
<Residue CYS het=H_CYS resseq=2003 icode= >
get_residue_by_number(structure[0]['A'].get_residues(), 100)
<Residue ASP het= resseq=100 icode= >

Defining range using regular expressions in Ruby on Rails [duplicate]

This question already has answers here:
Is there a way of changing regular expressions to a range of numbers in Ruby on Rails?
(2 answers)
Closed 8 years ago.
I have this code:
(1..40).map(&:to_s).grep(/[2-3][0-9]/)
So when I type in [2-3][0-9] it will print all the numbers in the range (which is between 20 and 39). How can I do it without defining the range (i.e. in this case it is "1..40") so it works for any regular expression that I type into the brackets?
So similar code to
(1..40).map(&:to_s).grep(/[2-3][0-9]/)
that would work without (1..40).map part.
Ok, this is awful, and you really probably don't actually want to do this, you just think you do. But, FWIW:
def this_is_awful(string)
results = []
string.split("|").each do |section|
#example section is "5[0-3][2-4]"
section_digits = []
section.split(/[\[\]]+/).select{|s| s.size > 0}.each do |range_string|
range_digits = range_string.split("-").select{|s| s.size > 0}
arrays = (range_digits[0]..range_digits[-1]).to_a
section_digits << arrays if arrays.size > 0
end
#now we need every combination of these
section_digits[0].product(*section_digits[1..-1]).each do |combination|
results << combination unless results.include?(combination)
end
end
#at this point, results will be like [[5, 0, 2], [5, 0, 3], [5, 0, 4], etc]. Sort these and convert them to digits via strings
results.sort.collect{|arr| arr.join}
end
eg
irb(main):075:0> this_is_awful("5[2-3]")
=> [52, 53]
irb(main):076:0> this_is_awful("5[2-3][3-9]")
=> [523, 524, 525, 526, 527, 528, 529, 533, 534, 535, 536, 537, 538, 539]
irb(main):077:0> this_is_awful("5[2-3][3-9]|10[1-7][3-8]")
=> [523, 524, 525, 526, 527, 528, 529, 533, 534, 535, 536, 537, 538, 539, 1013, 1014, 1015, 1016, 1017, 1018, 1023, 1024, 1025, 1026, 1027, 1028, 1033, 1034, 1035, 1036, 1037, 1038, 1043, 1044, 1045, 1046, 1047, 1048, 1053, 1054, 1055, 1056, 1057, 1058, 1063, 1064, 1065, 1066, 1067, 1068, 1073, 1074, 1075, 1076, 1077, 1078]
Btw i would say that this question has nothing to do with Ruby on Rails.
EDIT: I just edited this to work more generally, with any enumerable (so it will work with letters too for example). You now get strings back but you can convert them to integers if you want with .collect(&:to_i)
eg
irb(main):122:0> this_is_awful("a[b-e][f-g]")
=> ["abf", "abg", "acf", "acg", "adf", "adg", "aef", "aeg"]
EDIT 2: fixed a bug for when it starts with an array
What you are trying to do is brute forcing. It's inefficient and slow. It's just a wrong approach so forget about RegEx.
You are going to need a real algorithm. So I made one for you...
I'll assume that the your input will only include numbers: 1 and ranges defined like that: [2-6] or any combination of the two, resulting in a string like: 1[2-3][5-7]9.
Imagine this is a vector (array) of possible digits with two types of elements:
range of possible digits.
fixed digit (which is a range of the number to the same number)
Our example for the input 1[2-3][5-7]9 converted should look like:
[ [1,1], [2,3], [5,7], [9,9] ]
The first element in this array ([1,1]) is the range for the first digit, the second ([2,3]) for the second digit, and so on.
It's relatively easy to turn it into something like this. This is an array of arrays with two elements - start and end number of each range.
So what you need to do now is output each possible value. This can be done with a simple recursion for every digit, starting a new branch for every of it's possible values.
Here is an example implementing that recursion:
def recursion(array, number = '')
return if array.empty? # Don't bother if the digits array is empty
# iterate over each possible value of the current pair
(array[0][0]..array[0][1]).each do |i|
if array.length <= 1 # If the digits array is empty (contains only the current range)
# then an entire number would have been generated, so print it
puts number + i.to_s
else
# Start a new branch passing the array (without the current element)
# and the generated number until this moment
recursion(array[1..-1], number + i.to_s)
end
end
end
array = [ [1,1], [2,3], [5,7], [9,9] ]
recursion(array)
Following this approach you can make the function as complicated as you can.
I provided you with the routine on how to compute the numbers themselves, but not on how to create the array which I hope you can handle.
This is harder to implement and certainly doesn't contain all the features of RegEx but is fast and will generate numbers as hell.
P.S. Wow.. This took me an hour to create and debug. Hope it helps.

Unprintable Solver.model()

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.

Resources