Cosine scoring in whoosh, python - python

I've implemented some python code to run search on whoosh using BM25 and all went out ok, but now that I'm trying to change scoring mechanism to Cosine, I'm getting this error:
File "TFIDF.py", line 18, in tfidf
with ix.searcher(weighting=whoosh.scoring.Cosine()) as searcher: AttributeError: 'module' object has no attribute 'Cosine'
If I import Cosine
from whoosh.scoring import Cosine
I get this:
File "TFIDF.py", line 4, in <module>
from whoosh.scoring import Cosine
ImportError: cannot import name Cosine
My code is below:
import whoosh
from whoosh.scoring import Cosine
from whoosh.fields import *
from whoosh.scoring import *
from whoosh.qparser import *
from whoosh.query import *
from whoosh.index import open_dir
#Index path
lab3dir= "../lab3/Aula3_1/"
ix = open_dir(lab3dir + "indexdir") #Index generated in previous lab
def cosine(queryTerms):
list=[]
dict={} # dict com ID do doc e Similiaridade
with ix.searcher(weighting=whoosh.scoring.Cosine()) as searcher:
query = QueryParser("content", ix.schema, group=OrGroup).parse(u(queryTerms))
results = searcher.search(query, limit=100)
for i,r in enumerate(results):
list.append(r["id"])
print r, results.score(i)
dict[r["id"]]= results.score(i)
return dict
Any ideias???
Thank you!

The documentation on http://pythonhosted.org/Whoosh/searching.html#the-searcher-object, which I assume is what you're looking at is incorrect as you have found. Look at the documentation (http://pythonhosted.org/Whoosh/api/scoring.html#module-whoosh.scoring) or the source code (https://bitbucket.org/mchaput/whoosh/src/362fc2999c8cabc51370f433de7402fafd536ec6/src/whoosh/scoring.py?at=default) for the options actually available.

Related

ABAQUS script for a custom field output

I am new to ABAQUS scripting and I am trying to calculate micromotion using COPEN, CSLIP1 and CSLIP2. I came up with the code below:
from abaqusConstants import *
from odbAccess import *
from odbMaterial import *
from odbSection import *
from math import *
from copy import deepcopy
from caeModules import *
from driverUtils import executeOnCaeStartup
from numpy import fabs as fabs
import numpy as np
from types import IntType
odb = session.openOdb(name='E:\PDP02.odb', readOnly=FALSE)
odb = session.odbs['E:\PDP02.odb']
print odb.rootAssembly.instances.keys()
grout_instance = odb.rootAssembly.instances['PROX-1#PROXIMAL-1']
keys = odb.steps.keys()
for key in keys:
step = odb.steps[key]
for frame in step.frames:
print frame.description
Copen = frame.fieldOutputs['COPEN']
Cslip1 = frame.fieldOutputs['CSLIP1']
Cslip2 = frame.fieldOutputs['CSLIP2']
Micromotion = sqrt(power(Copen,2)+power(Cslip1,2)+power(Cslip2,2))
#Micromotion =sqrt(power(Cslip2,2))
#float(Micromotion)
frame.FieldOutput(name='Micromotion', description='Average Micromotion', field=Micromotion)
odb.update()
odb.save()
After executing the code, i get the following error message: "OdiError: Expression evaluates to an overflow or underflow". Please help me understand this error message and how to rectify it. I am happy to provide the .inp and .odb files for reference and verification.
Simply put, overflow and underflow happen when we assign a value that is out of range of the declared data type of the variable. If the (absolute) value is too big, we call it overflow, if the value is too small, we call it underflow.

How to save pyprover object with pickle

I want to save logical expressions of pyprover with pickle.
The following is the code I wrote in google corabolatory.
!pip install pyprover
import pickle
from pyprover import *
logic = ~A & B
print(1,logic)
print(2,type(logic))
print(3,type(A))
with open("test.pickle","wb") as f:
pickle.dump(logic,f)
with open("test.pickle","rb") as f:
logic2 = pickle.load(f) # error
print(logic2)
The output is below
1 ~A & B
2 <class 'pyprover.logic.And'>
3 <class 'pyprover.logic.Prop'>
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-27-4cd4fe38fcb4> in <module>
12
13 with open("test.pickle","rb") as f:
---> 14 logic2 = pickle.load(f) # error
15
16 print(logic2)
AttributeError: 'Top' object has no attribute 'elems'
How can I save the logical expression with pickle?
pyprover github
If you know how to save the object, I do not care about whether or not it uses pickle. I tried dill,only to get the same result as pickle.
I wrote an dill issue here
I tried to import modules like this but it didn't solve the problem.
import dill
import pyprover
from pyprover import *
from pyprover.logic import *
from pyprover.parser import *
from pyprover.constants import *
from pyprover.atoms import *
from pyprover.util import *
from pyprover.tools import *
from pyprover.__coconut__ import *
from pyprover.__init__ import *

When using RDKIT, object is not iterable error appears

I am trying to use tanimoto similarity to compare molecular fingerprints using rdkit. I am trying to compare the two items in list 1 with the one item in list 2. However, I get getting an error. I do not understand it because I have anything named "Mol" in my code. Does anyone have any advice? Thank you
from rdkit import Chem
from rdkit.Chem import rdFingerprintGenerator
from rdkit.Chem import DataStructs
mol1 = ('CCO', 'CCOO')
mol2 = ('CC')
fii = Chem.MolFromSmiles(mol2)
fpgen1 = rdFingerprintGenerator.GetMorganGenerator(radius=2)
fps1 = [fpgen1.GetFingerprint(m) for m in fii]
for m in mol1:
fi = Chem.MolFromSmiles(m)
fpgen2 = rdFingerprintGenerator.GetMorganGenerator(radius=2)
fps2 = [fpgen2.GetFingerprint(m) for m in fi]
for x in fsp2:
t = DataStructs.TanimotoSimilarity(fps1, fps2(x))
print(t)
ERROR:
fps1 = [fpgen1.GetFingerprint(m) for m in fii]
TypeError: 'Mol' object is not iterable
The Mol object is the name of the rdkit class that is returned when you call Chem.MolFromSmiles, not one of your variable names.
The error says that the Mol object is not iterable (it is a single molecule)
from rdkit import Chem
from rdkit.Chem import rdFingerprintGenerator
from rdkit.Chem import DataStructs
smiles1 = ('CCO', 'CCOO')
smiles2 = ('CC',)
mols1 = [Chem.MolFromSmiles(smi) for smi in smiles1]
mols2 = [Chem.MolFromSmiles(smi) for smi in smiles2]
# you only need to instantiate the generator once, you can use it for both lists
fpgen = rdFingerprintGenerator.GetMorganGenerator(radius=2)
fps1 = [fpgen.GetFingerprint(m) for m in mols1]
fps2 = [fpgen.GetFingerprint(m) for m in mols2]
# if you only care about the single entry in fps2 you can just index it
for n, fp in enumerate(fps1):
t = DataStructs.TanimotoSimilarity(fp, fps2[0])
print(n, t)

Error in Selecting Random Nodes(Python)

Here is My Python Code is given below:-
import networkx as nx
import matplotlib.pyplot as plt
from random import choice
g=nx.Graph()
city_set=['Delhi','Lucknow','Indore','Kolkata','Hyderabad','Chennai',
'Tivandrum','Banglore','Pune','Mumbai','Surat','Ahmedabad','Jaipur']
for each in city_set:
g.add_node(each)
costs=[]
value =100
while(value<=2000):
costs.append(value)
value=value+70
while(g.number_of_edges()<24):
c1=choice(g.nodes())
c2=choice(g.nodes())
if c1!=c2 and g.has_edge(c1,c2)==0:
w=choice(costs)
g.add_edge(c1,c2,weight=w)
nx.draw(g,with_labels=1)
plt.show(g)
and while compiling the code I got the error stated below:-
$ python cities.py
Traceback (most recent call last):
File "cities.py", line 22, in <module>
c1=choice(g.nodes())
File "/usr/lib/python2.7/random.py", line 277, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq
is empty
File "/usr/local/lib/python2.7/dist-
packages/networkx/classes/reportviews.py", line 178, in __getitem__
return self._nodes[n]
KeyError: 7
I also created vitual enviourment of Pyhton but again it shows the smae error.
Also, I tried finding some stuff on Google and check for the solution but no one has similar problem like this.
Change
c1=choice(g.nodes())
c2=choice(g.nodes())
into
c1=choice(list(g))
c2=choice(list(g))
should work.
g.nodes() returns a NodeView and not a list of nodes.
import random
import networkx as nx
costs = []
value=100
while(value<=2000):
costs.append(value)
value+=100
print (costs)
while(G.number_of_edges()<16):
c1 = random.choice(list(G.nodes()))
c2 = random.choice(list(G.nodes()))
if c1!=c2 and G.has_edge(c1,c2)==0:
w= random.choice(costs)
G.add_edge(c1,c2,weight = w)
Try this code as there is some error in the syntax of the random shown in the video. I have pasted my code, test it.
G.nodes() needs to return a list but here is returning a NodeView. Hence change G.nodes() to list(G.nodes())

my module won't load

i am sorry,i am just a beginner in python language,i am quite stuck in this problem quite long.actually,i want to make a descending and ascending of list that the user input by creating a module of the descending and the ascending.but i couldn't get it work.
the main python file is pythonaslab.py and the module for the ascending and the descending is selectionmodule.py..the code:
this is the selectionmodule:
import pythonaslab
def ascendingselection():
for q in range(len(b)):
w=q+1
for w in range(len(b)):
if b[q]>b[w]:
f=b[q]
b[q]=b[w]
b[w]=f
print b
def descendingselection():
for q in range(len(b)):
w=q+1
for w in range(len(b)):
if b[q]<b[w]:
f=b[q]
b[q]=b[w]
b[w]=f
print b
And this is the main file,the pythonaslab:
import selectionmodule
a = int(input())
b = [int(input()) for _ in range(a)]
print b
print "1.ascending 2.descending"
c=input()
if c==1:
selectionmodule.ascendingselection()
if c==2:
selectionmodule.descendingselection()
can you point me where's the cause of all this error i got?
Traceback (most recent call last):
File "E:\Coding\pythonaslab.py", line 1, in <module>
import selectionmodule
File "E:\Coding\selectionmodule.py", line 1, in <module>
import pythonaslab
File "E:\Coding\pythonaslab.py", line 16, in <module>
selectionmodule.descendingselection()
AttributeError: 'module' object has no attribute 'descendingselection'
You created a circular import; your pythonaslab module imports selectionmodule which imports the pythonaslab module. You end up with incomplete modules that way, don't do that.
Remove the import pythonaslab line from selectionmodule; you are not using pythonaslab in that module.
Also, another module cannot read your globals; you need to pass those in as arguments:
# this function takes one argument, and locally it is known as b
def ascendingselection(b):
# rest of function ..
then call that with:
selectionmodule.ascendingselection(b)
Note that you are not limited to one-letter variable names. Using longer, descriptive names makes your code more readable.
if you don't want to use module name such as:
selectionmodule.ascendingselection(b)
you should import :
from selectionmodule import *
then you can call:
ascendingselection(b) # without module name
Or you can import your module and assigne a alias name:
import selectionmodule as o
o.ascendingselection(b) # with alias name
for more information read: import confusaion

Categories