Setting number of lags - python

I am teaching myself the use of time series in Python.
I was following
https://arch.readthedocs.io/en/latest/unitroot/unitroot_examples.html
I performed
adf = ADF(default)
print(adf.summary().as_text())
It worked perfectly.
However, when I wanted to change lags like
adf.lags = 5
print(adf.summary().as_text())
or change the type of trend as in the snip below
it gives me the following error (same for the trend):
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [11], in <module>
----> 1 adf.lags = 5
2 print(adf.summary().as_text())
AttributeError: can't set attribute
Even when I follow all instructions on the exercise page and recreate it with the data used there I cannot get the lags to change. What am I doing wrong?

Although documentation (r.t.docs) confirms as you suggested, after a quick look at ADF class inside ARCH/ unitroot/unitroot.py, I believe it takes parameter lags upon creation of the class. I tried and it works.
Instead of adf.lags = 5 you may use version below.
adf = ADF(default, lags = 5 )
class ADF:
def __init__(
self,
y: ArrayLike,
lags: Optional[int] = None,
trend: UnitRootTrend = "c",
max_lags: Optional[int] = None,
method: Literal["aic", "bic", "t-stat"] = "aic",
low_memory: Optional[bool] = None,
) -> None:

Related

Constraint 'feasibility_cut[1]' does not have a proper value. Found 'True'

I'm new to python and pyomo, so I would kindly appreciate your help,
I'm currently having trouble trying to add a constraint to my mathematical model in Pyomo, the problem is while I try to add the "feasibility_cut", it says "Constraint 'feasibility_cut[1]' does not have a proper value. Found 'True' ", what I understand from this is that, pyomo sees this constraint as a logical comparative constraint, which is I don't know why!
Here is a part of the code that I think is necessary to see:
RMP = ConcreteModel()
RMP.ymp = Var(SND.E, within=Integers)
RMP.z = Var(within = Reals)
S1 = (len(SND.A), len(SND.K))
S2 = (len(SND.A), len(SND.A))
uBar= np.zeros(S1)
vBar=np.zeros(S2)
RMP.optimality_cut = ConstraintList()
RMP.feasibility_cut = ConstraintList()
expr2 = (sum(SND.Fixed_Cost[i,j]*RMP.ymp[i,j] for i,j in SND.E) + RMP.z)
RMP.Obj_RMP = pe.Objective(expr = expr2, sense = minimize)
iteration=0
epsilon = 0.01
while (UB-LB)>epsilon :
iteration = iteration +1
DSPsolution = Solver.solve(DSP)
for i in SND.A:
for k in SND.K:
uBar[i-1,k-1] = value(DSP.u[i,k])
for i,j in SND.E:
vBar[i-1,j-1] = value(DSP.v[i,j])
if value(DSP.Obj_DSP) == DSPinf:
RMP.feasCut.add()
else:
RMP.optimCut.add()
RMPsolution = solver.solve(RMP)
UB=min(UB,)
LB=max(LB,value(RMP.Obj_RMP))
if value(DSP.Obj_DSP) == DSPinf:
RMP.feasibility_cut.add( 0>= sum(-SND.Capacity[i,j]*vBar[i-1,j-1]*RMP.ymp[i,j] for i,j in
SND.E) + sum(uBar[i-1,k-1]*SND.New_Demand[k,i] for i in SND.A for k in SND.K if (k,i) in
SND.New_Demand) )
else:
RMP.optimality_cut.add( RMP.z >= sum(SND.Fixed_Cost[i,j]*RMP.ymp[i,j] for i,j in SND.E) +
sum(uBar[i-1,k-1]*SND.New_Demand[k,i] for i in SND.A for k in SND.K) -
sum(SND.Capacity[i,j]*vBar[i-1,j-1]*RMP.ymp[i,j] for i,j in SND.E) )
Welcome to the site.
A couple preliminaries... When you post code that generates an error, it is customary (and easier for those to help) if you post the entire code necessary to reproduce the error and the stack trace, or at least identify what line is causing the error.
So when you use a constraint list in pyomo, everything you add to it must be a legal expression in terms of the model variables, parameters, and other constants etc. You are likely getting the error because you are adding an expression that evaluates to True. So it is likely that an expression you are adding does not depend on a model variable. See the example below.
Also, you need to be careful mingling numpy and pyomo models, numpy arrays etc. can cause some confusion and odd errors. I'd recommend putting all data into the model or using pure python data types (lists, sets, dictionaries).
Here are 2 errors. You have an empty add() in your code too, which will throw an error.
In [1]: from pyomo.environ import *
In [2]: m = ConcreteModel()
In [3]: m.my_constraints = ConstraintList()
In [4]: m.X = Var()
In [5]: m.my_constraints.add(m.X >= 5) # good!
Out[5]: <pyomo.core.base.constraint._GeneralConstraintData at 0x7f8778cfa880>
In [6]: m.my_constraints.add() # error!
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-cf466911f3a1> in <module>
----> 1 m.my_constraints.add()
TypeError: add() missing 1 required positional argument: 'expr'
In [7]: m.my_constraints.add(3 <= 4) # error: trivial evaluation!
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-a0bec84404b0> in <module>
----> 1 m.my_constraints.add(3 <= 4)
...
ValueError: Invalid constraint expression. The constraint expression resolved to a trivial Boolean (True) instead of a Pyomo object. Please modify your rule to return Constraint.Feasible instead of True.
Error thrown for Constraint 'my_constraints[2]'
In [8]:

Getting ValueError after last iteration when using .apply() method

I wrote a function to query emotion analysis from senpy by passing reviews. I printed every line with index to see if it just worked fine. The dataset has 5684 rows. However, when reaching the last row I get a ValueError. I also tried to add this last review to my function and I received the corresponding values successfully.
This is the function I wrote.
def query_emotion(review):
params = {'input': review}
res = requests.get('http://senpy.gsi.upm.es/api/emotion-depechemood',
params=params)
if res.status_code != 200:
raise Exception(res)
data = json.loads(res.text)
negative_fear = data['entries'][0]['onyx:hasEmotionSet'][0]['onyx:hasEmotion'][0]['onyx:hasEmotionIntensity']
amusement = data['entries'][0]['onyx:hasEmotionSet'][0]['onyx:hasEmotion'][1]['onyx:hasEmotionIntensity']
anger = data['entries'][0]['onyx:hasEmotionSet'][0]['onyx:hasEmotion'][2]['onyx:hasEmotionIntensity']
annoyance = data['entries'][0]['onyx:hasEmotionSet'][0]['onyx:hasEmotion'][3]['onyx:hasEmotionIntensity']
indifference = data['entries'][0]['onyx:hasEmotionSet'][0]['onyx:hasEmotion'][4]['onyx:hasEmotionIntensity']
joy = data['entries'][0]['onyx:hasEmotionSet'][0]['onyx:hasEmotion'][5]['onyx:hasEmotionIntensity']
awe = data['entries'][0]['onyx:hasEmotionSet'][0]['onyx:hasEmotion'][6]['onyx:hasEmotionIntensity']
sadness = data['entries'][0]['onyx:hasEmotionSet'][0]['onyx:hasEmotion'][7]['onyx:hasEmotionIntensity']
print(X[X.Text == review].index, ": ", [negative_fear, amusement, anger, annoyance, indifference, joy, awe, sadness])
return negative_fear, amusement, anger, annoyance, indifference, joy, awe, sadness
I called the function using the .apply() method:
X['Text_negative_fear'], X['Text_amusement'], X['Text_anger'], X['Text_annoyance'], X['Text_indifference'], X['Text_joy'], X['Text_awe'], X['Text_sadness'] = X.Text.apply(query_emotion)
And these are the last lines from the output after calling the function:
Int64Index([5681], dtype='int64') : [0.0792444511959933, 0.1580643288473154, 0.11423923859401869, 0.1399028217635615, 0.13737889283844476, 0.10330318175060896, 0.1746433112249919, 0.09322377378506547]
Int64Index([5682], dtype='int64') : [0.08308025773764179, 0.1820866455048511, 0.09436993092693748, 0.12984061502089508, 0.1281518690206751, 0.10726563771574184, 0.19287900349802356, 0.08232604057523404]
Int64Index([5683], dtype='int64') : [0.09470651839679665, 0.19571514056396988, 0.10608728359324908, 0.12185687329212973, 0.12744650875201016, 0.10307696316708366, 0.150327288948556, 0.10078342328620486]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-12-6f8cc4431e17> in <module>()
----> 1 X['Text_negative_fear'], X['Text_amusement'], X['Text_anger'], X['Text_annoyance'], X['Text_indifference'], X['Text_joy'], X['Text_awe'], X['Text_sadness'] = X.Text.apply(query_emotion)
ValueError: too many values to unpack (expected 8)
Thank you for any advice that might fix this issue!

How to get a list of all tokens from Lucene 8.6.1 index using PyLucene?

I have got some direction from this question. I first make the index like below.
import lucene
from org.apache.lucene.analysis.standard import StandardAnalyzer
from org.apache.lucene.index import IndexWriterConfig, IndexWriter, DirectoryReader
from org.apache.lucene.store import SimpleFSDirectory
from java.nio.file import Paths
from org.apache.lucene.document import Document, Field, TextField
from org.apache.lucene.util import BytesRefIterator
index_path = "./index"
lucene.initVM()
analyzer = StandardAnalyzer()
config = IndexWriterConfig(analyzer)
if len(os.listdir(index_path))>0:
config.setOpenMode(IndexWriterConfig.OpenMode.APPEND)
store = SimpleFSDirectory(Paths.get(index_path))
writer = IndexWriter(store, config)
doc = Document()
doc.add(Field("docid", "1", TextField.TYPE_STORED))
doc.add(Field("title", "qwe rty", TextField.TYPE_STORED))
doc.add(Field("description", "uio pas", TextField.TYPE_STORED))
writer.addDocument(doc)
writer.close()
store.close()
I then try to get all the terms in the index for one field like below.
store = SimpleFSDirectory(Paths.get(index_path))
reader = DirectoryReader.open(store)
Attempt 1: trying to use the next() as used in this question which seems to be a method of BytesRefIterator implemented by TermsEnum.
for lrc in reader.leaves():
terms = lrc.reader().terms('title')
terms_enum = terms.iterator()
while terms_enum.next():
term = terms_enum.term()
print(term.utf8ToString())
However, I can't seem to be able to access that next() method.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-47-6515079843a0> in <module>
2 terms = lrc.reader().terms('title')
3 terms_enum = terms.iterator()
----> 4 while terms_enum.next():
5 term = terms_enum.term()
6 print(term.utf8ToString())
AttributeError: 'TermsEnum' object has no attribute 'next'
Attempt 2: trying to change the while loop as suggested in the comments of this question.
while next(terms_enum):
term = terms_enum.term()
print(term.utf8ToString())
However, it seems TermsEnum is not understood to be an iterator by Python.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-48-d490ad78fb1c> in <module>
2 terms = lrc.reader().terms('title')
3 terms_enum = terms.iterator()
----> 4 while next(terms_enum):
5 term = terms_enum.term()
6 print(term.utf8ToString())
TypeError: 'TermsEnum' object is not an iterator
I am aware that my question can be answered as suggested in this question. Then I guess my question really is, how do I get all the terms in TermsEnum?
I found that the below works from here and from test_FieldEnumeration() in the test_Pylucene.py file which is in pylucene-8.6.1/test3/.
for term in BytesRefIterator.cast_(terms_enum):
print(term.utf8ToString())
Happy to accept an answer that has more explanation than this.

fminbound for a simple equation

def profits(q):
range_price = range_p(q)
range_profits = [(x-c(q))*demand(q,x) for x in range_price]
price = range_price[argmax(range_profits)] # recall from above that argmax(V) gives
# the position of the greatest element in a vector V
# further V[i] the element in position i of vector V
return (price-c(q))*demand(q,price)
print profits(0.6)
print profits(0.8)
print profits(1)
0.18
0.2
0.208333333333
With q (being quality) in [0,1], we know that the maximizing quality is 1. Now the question is, how can I solve such an equation? I keep getting the error that either q is not defined yet (which is only natural as we are looking for it) or I get the error that some of the arguments are wrong.
q_firm = optimize.fminbound(-profits(q),0,1)
This is what I've tried, but I get this error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-99-b0a80dc20a3d> in <module>()
----> 1 q_firm = optimize.fminbound(-profits(q),0,1)
NameError: name 'q' is not defined
Can someone help me out? If I need to supply you guys with more information to the question let me know, it's my first time using this platform. Thanks in advance!
fminbound needs a callable, while profits(q) tries to calculate a single value. Use
fminbound(lambda q: -profits(q), 0, 1)
Note that the lambda above is only needed to generate a function for negative profits. Better define a function for -profits and feed it to fminbound.
Better still, use minimize_scalar instead of fminbound.

Why can't I call a Kivy.core.image function?

I did a program using python and pyGTK. Now, I'm translating it to Kivy, for use it with a tablet (Android). One archive.py is a custom widget with graphic information about a person (an image of her/his, a frame with color if him/his is selected, a little candle if is your birthday,..)
The question is, to make the custom widget I need to know the image size, but when I write:
wi = self._imagen.width()
I have this error:
TypeError: 'int' object is not callable
Before, in code, I check self._imagen is an kivy.core.image.Image object, that has a width function:
if self._imagen != None:
print self._imagen #terminal print <kivy.core.image.Image object at 0xb2f2db9c>
wi = self._imagen.width() #ERROR
hi = self._imagen.height()
I search for any instruction in my code like: self._imagen = 1 (or other int number) (there is not).
I don't know why. Thanks and sorry for my english
Use wi = self._imagen.width using wi = self._imagen.width() is trying to call the int object as a method, that is why you are getting the error.
In [1]: width = 3
In [2]: print width
3
In [3]: print width()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-33019bd92b32> in <module>()
----> 1 print width()
TypeError: 'int' object is not callable

Categories