Pyomo error: "name 'domain' is not defined" - pyomo

I have a basic electricity system model that I have built in Pyomo and has been working well. I'm now looking to make it a bit more sophisticated, adding in some additional variables, such as start costs for individual generators.
I pasted below some of the code I have added - I can provide more contextual code if required, but it is only these lines that have been added to trigger this error. The error thrown back by Pyomo is shown in quotes in the header to this query. I have deliberately left in some commenting out of lines, where I simplified the code to try to identify where the issue is. To no avail: I still get an error with the commenting out shown below:
model.StartFuelCost = Param(model.GeneratorName, model.Resource, default=0)
model.GeneratorCommitted = Var(model.GeneratorName, model.Hour, domain=Boolean, initialize=0)
model.GeneratorStart = Var(model.GeneratorName, model.Hour, domain=Boolean, initialize=0)
model.StartFuelCostByGenerator = Var(model.GeneratorName, model.Resource, model.Hour, domain=NonNegativeReals, initialize=0.0)
model.StartFuelCostTotal = Var(model.Resource, model. Hour, domain.NonNegativeReals, initialize=0.0)
...
def GeneratorCommitted_rule(model,g,h):
# if model.Generation[g,h] > 0:
return model.GeneratorCommitted[g,h] == 1
# else:
# return model.GeneratorCommitted[g,h] == 0
model.SupplyDemand_Calc2 = Constraint(model.GeneratorName, model.Hour, rule=GeneratorCommitted_rule)
# ISSUE: Either need to remove conditionality or pass info from the last time step
def GeneratorStart_rule(model,g,h):
# if model.Hour > 1:
# return max(0, model.GeneratorCommitted[g,h] - model.GeneratorCommitted[g,h-1]) == model.GeneratorStart[g,h]
# else:
return model.GeneratorCommitted[g,h] == model.GeneratorStart[g,h]
model.SupplyDemand_Calc3 = Constraint(model.GeneratorName, model.Hour, rule=GeneratorStart_rule)
def StartFuelCostByGenerator_rule(model,g,r,h):
return model.StartFuelCost[g,r] * model.ResourcePrice[r] * model.GeneratorStart[g,h] == model.StartFuelCostByGenerator[g,r,h]
model.Costing_Calc5 = Constraint(model.GeneratorName, model.Resource, model.Hour, rule=StartFuelCostByGenerator_rule)
def StartFuelCostTotal_rule(model,r,h):
return sum(model.StartFuelCostByGenerator[g,r,h] for g in model.GeneratorName) == model.StartFuelCostTotal[r,h]
model.Costing_Calc6 = Constraint(model.Resource, model.Hour, rule=StartFuelCostTotal_rule)

This is your problem:
model.StartFuelCostTotal = Var(model.Resource, model. Hour, domain.NonNegativeReals, initialize=0.0)
You have "." (dot) notation there with domain, so it is trying to figure out what this thing is that you call domain... You want to change that to an =.
In the future, it is much easier (and you are more likely) to get help if you post the actual code with the error trace which says which line contains the error.

Related

SQLAlchemy adding/updating in for loop: updating not working

I'm trying to do the following: loop through a series of records, if one already exists, I update it. If it doesn't exist, I add it.
For some reason, the adding is working fine, but the updating is not occurring. here's the code:
for interchange in data:
ltype='asdf'
plink='qwer'
e = Part.query.filter_by(interchange=interchange, light_type=ltype).first()
if e is None:
notpresent = notpresent + 1
p = Part(interchange=interchange,light_type=ltype,partslink=plink,ptype=ptype)
db.session.add(p)
else:
present = present + 1
e.partslink = plink
e.ptype = ptype
db.session.commit()
I print out the present and notpresent variables and both are > 0.
Am I handling the update part incorrectly when the record is found? That portion is not getting saved.
you are missing a line:
# ...
else:
present = present + 1
e.partslink = plink
e.ptype = ptype
db.session.add(e) # here 'add' is adding changes to the session, not a new item.
you cannot commit changes if you do not register them.

Frustrating python syntax error

I am writing a script to automate HvZ games at my college and have run into this strange frustrating syntax error:
File "HvZGameMaster.py", line 53
class players(object):
^
SyntaxError: invalid syntax
Here is the offending code
class mailMan(object):
"""mailMan manages player interactions such as tags reported via text messages or emails"""
def __init__(self, playerManager):
super(mailMan, self).__init__()
self.mail = imaplib.IMAP4_SSL('imap.gmail.com')
self.mail.login(args.username,args.password)
self.mail.list()
# Out: list of "folders" aka labels in gmail.
self.mail.select("inbox") #connect to inbox.
def getBody(self, emailMessage):
maintype = emailMessage.get_content_maintype()
if maintype == 'multipart':
for part in emailMessage.get_payload():
if part.get_content_maintype() == 'text':
return part.get_payload()
elif maintype == 'text':
return emailMessage.get_payload()
def getUnread(self):
self.mail.select("inbox") # Select inbox or default namespace
(retcode, messages) = self.mail.search(None, '(UNSEEN)')
if retcode == 'OK':
retlist = []
for num in messages[0].split(' '):
print 'Processing :', messages
typ, data = self.mail.fetch(num,'(RFC822)')
msg = email.message_from_string(data[0][1])
typ, data = self.mail.store(num,'-FLAGS','\\Seen')
if retcode == 'OK':
for item in str(msg).split('\n'):
#finds who sent the message
if re.match("From: *",item):
print (item[6:], self.getBody(msg))
retlist.append((item[6:], self.getBody(msg).rstrip())
#print (item, self.getBody(msg).rstrip())
class players(object): #<-the problem happens here
"""manages the player"""
def __init__(self, pDict):
super(players, self).__init__()
self.pDict = pDict
#makes a partucular player a zombie
def makeZombie(self, pID):
self.pDict[pID].zombie = True
#makes a partucular player a zombie
def makeHuman(self, pID):
self.pDict[pID].zombie = False
As far as I can tell what I have written is correct and I have checked to make sure it is all tabs and not spaces I have made sure i don't have any erroneous \r's or \n's floating around (all \n's are where the should be at the end of the line and I'm not using any \r's)
You can find all my code for this project here if you would like to try running it yourself
There is an unbalanced (missing) parenthesis on the line above the line raising the error:
retlist.append((item[6:], self.getBody(msg).rstrip())
Note that some editors have matching parenthesis highlighting, and key combinations for moving back and forth across matched parentheses. Using an editor with these features can help cut down on these errors.

Word Crawler script not fetching the target words - Python 2.7

I am a newbie to programming. Learning from Udacity. In unit 2, I studied the following code to fetch links from a particular url:
import urllib2
def get_page(url):
return urllib2.urlopen(url).read()
def get_next_target(page):
start_link = page.find('<a href=')
if start_link == -1:
return None, 0
start_quote = page.find('"', start_link)
end_quote = page.find('"', start_quote + 1)
url = page[start_quote + 1:end_quote]
return url, end_quote
def print_all_links(page):
while True:
url, endpos = get_next_target(page)
if url:
print url
page = page[endpos:]
else:
break
print_all_links(get_page('http://en.wikipedia.org'))
It worked perfectly. Today I wanted to modify this code so the script could crawl for a particular word in a webpage rather than URLs. Here is what I came up with:
import urllib2
def get_web(url):
return urllib2.urlopen(url).read()
def get_links_from(page):
start_at = page.find('america')
if start_at == -1:
return None, 0
start_word = page.find('a', start_at)
end_word = page.find('a', start_word + 1)
word = page[start_word + 1:end_word]
return word, end_word
def print_words_from(page):
while True:
word, endlet = get_links_from(page)
if word:
print word
page = page[endlet:]
else:
break
print_words_from(get_web('http://en.wikipedia.org/wiki/America'))
When I run the above, I get no errors, but nothing prints out either. So I added the print keyword -
print print_words_from(get_web('http://en.wikipedia.org/wiki/America'))
When I run, I get None as result. I am unable to understand where am I going wrong. My code probably is messed up, but because there is no error coming up, I am unable to figure out where it is messed up.
Seeking help.
I understand this as you are trying to get it to print the word America for every instance of the word on the Wikipedia page.
You are searching for "america" but the word is written "America". "a" is not equal to "A" which is causing you to find no results.
Also, start_word is searing for 'a', so I adjusted that to search for 'A' instead.
At this point, it was printing 'meric' over and over. I edited your 'word' to begin at 'start_word' rather than 'start_word + 1'. I also adjusted your 'end_word' to be 'end_word+1' so that it prints that last letter.
It is now working on my machine. Let me know if you need any clarification.
def get_web(url):
return urllib2.urlopen(url).read()
def get_links_from(page):
start_at = page.find('America')
if start_at == -1:
return None, 0
start_word = page.find('A', start_at)
end_word = page.find('a', start_word + 1)
word = page[start_word:end_word+1]
return word, end_word
def print_words_from(page):
while True:
word, endlet = get_links_from(page)
if word:
print word
page = page[endlet:]
else:
break
print_words_from(get_web('http://en.wikipedia.org/wiki/America'))

Django No Reverse Match with Arguments

From my template:
July
URL Pattern:
url(r'^ocal/$', views.calendar, name = "othermonth"),
View:
def calendar(request, year, month):
my_year = int(year)
my_month = int(month)
my_calendar_from_month = datetime(my_year, my_month, 1)
my_calendar_to_month = datetime(my_year, my_month, monthrange(my_year, my_month)[1])
my_tickets = Event.objects.filter(on_sale__gte=my_calendar_from_month).filter(on_sale__lte=my_calendar_to_month)
my_previous_year = my_year
my_previous_month = my_month - 1
if my_previous_month == 0:
my_previous_year = my_year - 1
my_previous_month = 12
my_next_year = my_year
my_next_month = my_month + 1
if my_next_month == 13:
my_next_year = my_year + 1
my_next_month = 1
my_year_after_this = my_year + 1
my_year_before_this = my_year - 1
cal = TicketCalendar(my_tickets).formatmonth(year, month)
return render_to_response('calendar.html', {'events_list': my_tickets,
'calendar': mark_safe(cal),
'month': my_month,
'month_name': named_month(my_month),
'year': my_year,
'previous_month': my_previous_month,
'previous_month_name': named_month(my_previous_month),
'previous_year': my_previous_year,
'next_month': my_next_month,
'next_month_name': named_month(my_next_month),
'next_year': my_next_year,
'year_before_this': my_year_before_this,
'year_after_this': my_year_after_this,
}, context_instance=RequestContext(request))
Error:
Reverse for 'othermonth' with arguments '(2013, 7)' and keyword arguments '{}' not found.
I've searched through stackoverflow and the django documentation but I can't seem to figure out why I'm getting this NoReverseMatch error. I'm sure its a very simple oversight on my part because I'm staring at code from a previous project which is almost identical to this and that works fine. Any help would be appreciated, thanks.
UPDATE: I tried removing the parameters that I was trying to send with the URL and that fixed the NoReverseMatch however the view that is called requires those arguments so the link fails.
How do you plan for those arguments to be embedded in your URL? There's nothing capturing them, and no way for the reverse lookup to construct it. You need a URL pattern that accepts these parameters. Something like:
url(r'^ocal/(?P<year>\d{4})/(?P<month>(0|1)?\d)/$', views.calendar, name = "othermonth_bymonth"),
Using keyword rather than positional arguments here is optional, but I think it makes things easier - and allows setting default values that can trigger behavior like showing a calendar for the current day when nothing's specified.
Also, your mytickets queryset can also be constructed thus:
mytickets = Event.objects.filter(on_sale__year=year, onsale__month=month)
Which I think is a little cleaner to read.
Actually, upon a closer look - Django's built in date based views can do a lot of this for you. If you haven't already looked into them, I recommend doing so:
https://docs.djangoproject.com/en/dev/ref/class-based-views/generic-date-based/
For this particular view, all you'd need to do is subclass MonthArchiveView to create your TicketCalendar instance and add it to your context.
Edit: OK, you're still getting problems. This is how I would go about solving this:
views.py
class TicketMonthArchiveView(MonthArchiveView):
allow_empty = True # show months even in which no tickets exist
allow_future = True # show future months
model = Event
def get_context_data(self, **kwargs):
base_context = super(TicketMonthArchiveView, self).get_context_data(**kwargs)
my_tickets = kwargs['object_list']
base_context['calendar'] = mark_safe(TicketCalendar(my_tickets).formatmonth(self.get_year(), self.get_month()))
# the above could be a little off because I don't know exactly how your formatmonth method works
return base_context
urls.py
from somewhere.views import TicketMonthArchiveView
# other patterns, plus:
url(r'^ocal/(?P<year>\d{4})/(?P<month>(0|1)?\d)/$', TicketMonthArchiveView.as_view(), name='calendar_by_month'),
template event_archive_month.html
{{ next_month|date:'%f' }}
Obviously there's a lot more you could do here with the year and day views, but this should demonstrate the general concepts.
Large context volumes caused this behavior for me as well, despite having the correct syntax.
I had this, on Django 1.5:
urls.py
url(r'(?P<CLASSID>[A-Z0-9_]+)/$', 'psclassdefn.views.psclassdefn_detail', name="psclassdefn_detail"),
template.html
{% for inst in li_inst %}
<li><a href={% url 'psclassdefn.views.psclassdefn_detail' CLASSID=inst.CLASSID %}></a></li>
{% endfor %}
I kept on getting NoReverseMatch even though the syntax seemed OK and I could reverse into a no-argument url.
Now, li_inst was a huge list of about 1000 rows fetched from the db and passed to the context variable. Just to test, I trimmed the list by removing all but 10 or so rows. And it worked, without any syntax changes.
Maybe the templating system intentionally throttles the context size? I can filter the list if needed, just didn't expect this error to come from it.

TDD Django tests seem to skip certain parts of the view code

I'm writing some tests for a site using django TDD.
The problem is that when I manually go to the testserver. Fill in the form and submit it then it seems to works fine. But when I run the test using manage.py test wiki it seems to skip parts of the code within the view. The page parts all seem to work fine. But the pagemod-parts within the code and even a write() I created just to see what was going on seems to be ignored.
I have no idea what could be causing this and can't seem to find a solution. Any ideas?
This is the code:
test.py
#imports
class WikiSiteTest(LiveServerTestCase):
....
def test_wiki_links(self):
'''Go to the site, and check a few links'''
#creating a few objects which will be used later
.....
#some code to get to where I want:
.....
#testing the link to see if the tester can add pages
link = self.browser.find_element_by_link_text('Add page (for testing only. delete this later)')
link.click()
#filling in the form
template_field = self.browser.find_element_by_name('template')
template_field.send_keys('homepage')
slug_field = self.browser.find_element_by_name('slug')
slug_field.send_keys('this-is-a-slug')
title_field = self.browser.find_element_by_name('title')
title_field.send_keys('this is a title')
meta_field = self.browser.find_element_by_name('meta_description')
meta_field.send_keys('this is a meta')
content_field = self.browser.find_element_by_name('content')
content_field.send_keys('this is content')
#submitting the filled form so that it can be processed
s_button = self.browser.find_element_by_css_selector("input[value='Submit']")
s_button.click()
# now the view is called
and a view:
views.py
def page_add(request):
'''This function does one of these 3 things:
- Prepares an empty form
- Checks the formdata it got. If its ok then it will save it and create and save
a copy in the form of a Pagemodification.
- Checks the formdata it got. If its not ok then it will redirect the user back'''
.....
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
user = request.user.get_profile()
page = form.save(commit=False)
page.partner = user.partner
page.save() #works
#Gets ignored
pagemod = PageModification()
pagemod.template = page.template
pagemod.parent = page.parent
pagemod.page = Page.objects.get(slug=page.slug)
pagemod.title = page.title
pagemod.meta_description = page.meta_description
pagemod.content = page.content
pagemod.author = request.user.get_profile()
pagemod.save()
f = open("/location/log.txt", "w", True)
f.write('are you reaching this line?')
f.close()
#/gets ignored
#a render to response
Then later I do:
test.py
print '###############Data check##################'
print Page.objects.all()
print PageModification.objects.all()
print '###############End data check##############'
And get:
terminal:
###############Data check##################
[<Page: this is a title 2012-10-01 14:39:21.739966+00:00>]
[]
###############End data check##############
All the imports are fine. Putting the page.save() after the ignored code makes no difference.
This only happens when running it through the TDD test.
Thanks in advance.
How very strange. Could it be that the view is somehow erroring at the Pagemodification stage? Have you got any checks later on in your test that assert that the response from the view is coming through correctly, ie that a 500 error is not being returned instead?
Now this was a long time ago.
It was solved but the solution was a little embarrassing. Basically, it was me being stupid. I can't remember the exact details but I believe a different view was called instead of the one that I showed here. That view had the same code except the "skipped" part.
My apologies to anyone who took their time looking into this.