Pyomo Value Error: No value for uninitialized NumericValue object - pyomo

I am relatively new to Pyomo and I am testing some energy optimization model at the moment. I can define all the objectives and constraints but when trying to solve I get the following error:
'ValueError: No value for uninitialized NumericValue object x[batt]'
Here is relevant parts of my code (things that I don't think are relevant I just filled with ... to save some space):
ders = ["pv", "batt"]
model = ConcreteModel()
model.x = Var(ders, within = NonNegativeReals)
model.p_pv_load = Var(tsIndex, within = NonNegativeReals)
model.p_pv_grid = Var(tsIndex, within = NonNegativeReals)
model.p_pv_batt = Var(tsIndex, within = NonNegativeReals)
model.p_batt_load = Var(tsIndex, within = NonNegativeReals)
model.p_batt_grid = Var(tsIndex, within = NonNegativeReals)
model.soc_batt = Var(tsIndex, within = NonNegativeReals)
model.p_grid_load = Var(tsIndex, within = NonNegativeReals)
model.p_grid_batt = Var(tsIndex, within = NonNegativeReals)
#obj
def obj_rule(model):
return sum(... for ts in tsIndex)
model.obj = Objective(rule = obj_rule, sense = maximize)
#Some potentially relevant Constraints
maxPV = Constraint(expr = model.x["pv"]<=400)
maxBat= Constraint(expr = model.x["batt"]<=400)
socMin = 0.1*model.x["batt"]
socMax = 0.9*model.x["batt"]
socIni = socMin
batt_pMax=model.x["batt"]/3
#Discharge
def battDisc_rule(model, ts):
if ts==0:
return (((model.p_batt_load[ts]+model.p_batt_grid[ts])*(timestep/60))/sqrt(effR_bat) <= model.soc_batt[ts])
else:
return (((model.p_batt_load[ts]+model.p_batt_grid[ts])*(timestep/60))/sqrt(effR_bat) <= model.soc_batt[ts-1])
model.battDisc = Constraint(tsIndex, rule = battDisc_rule)
#Charge
def battCh_rule(model, ts):
if ts==0:
return ((model.p_pv_batt[ts]+model.p_grid_batt[ts])*(timestep/60))*sqrt(effR_bat) <= socMin-model.soc_batt[ts]
else:
return ((model.p_pv_batt[ts]+model.p_grid_batt[ts])*(timestep/60))*sqrt(effR_bat) <= socMin-model.soc_batt[ts-1]
model.battCh = Constraint(tsIndex, rule = battCh_rule)
#Soc
def socBounds_rule(model, ts):
return inequality(socMin, model.soc_batt[ts], socMax)
model.socBounds = Constraint(tsIndex, rule = socBounds_rule)
def update_SOC(model, ts):
if ts==0:
return model.soc_batt[ts]==socIni
else:
return model.soc_batt[ts] == model.soc_batt[ts-1]+(((model.p_pv_batt[ts]+model.p_grid_batt[ts]*sqrt(effR_bat))-((model.p_batt_load[ts]+model.p_batt_grid[ts])/sqrt(effR_bat)))*(timestep/60))
model.updateSOC = Constraint(tsIndex, rule=update_SOC)
def chPower_rule(model, ts):
return model.p_pv_batt[ts]+model.p_grid_batt[ts]*sqrt(effR_bat) <= batt_pMax
model.chPower = Constraint(tsIndex, rule=chPower_rule)
def dchPower_rule(model, ts):
return model.p_batt_load[ts]+model.p_batt_grid[ts]/sqrt(effR_bat) <= batt_pMax
model.dchPower = Constraint(tsIndex, rule=dchPower_rule)
I do not understand the error message since of course x[batt] is uninitialized as it is one of the decision variables.
Weirdly, in Julia's JuMP i can make it run using exactly the same GLPK solver and model description.
Thanks a lot for your help in advance.

The problem was the inequality() constraint function in combination with that I forgot to add "model" to the constraint declaration twice.

Related

list indices must be integers or slices, not dict in django

I just want to iterate through the list of JSON data which I get in the payload but getting an error as list indices must be integers or slices, not dict
payload:
[{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":150,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"},{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":151,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"}]
views.py:
#api_view(['POST'])
def SaveUserResponse(request):
for ran in request.data:
auditorid = request.data[ran].get('AuditorId')
ticketid = request.data[ran].get('TicketId')
qid = request.data[ran].get('QId')
answer = request.data[ran].get('Answer')
sid = '0'
TicketType = request.data[ran].get('TicketType')
TypeSelected = request.data[ran].get('TypeSelected')
agents = request.data[ran].get('Agents')
supervisor = request.data[ran].get('Supervisor')
Comments = request.data[ran].get('Comments')
action = request.data[ran].get('Action')
subfunction = request.data[ran].get('AuditSubFunction')
region = request.data[ran].get('AuditRegion')
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] #auditorid=%s,#ticketid=%s,#qid=%s,#answer=%s,#sid=%s,#TicketType=%s,#TypeSelected=%s,#agents=%s, #supervisor =%s, #Comments=%s, #action=%s, #subfunction=%s, #region=%s',
(auditorid,ticketid,qid,answer, sid,TicketType, TypeSelected, agents, supervisor, Comments, action, subfunction,region))
return Response(True)
I ran this code on my machine and it works for the payload you provided.
#api_view(['POST'])
def SaveUserResponse(request):
for ran in request.data:
auditorid = ran.get('AuditorId')
ticketid = ran.get('TicketId')
qid = ran.get('QId')
answer = ran.get('Answer')
sid = '0'
TicketType = ran.get('TicketType')
TypeSelected = ran.get('TypeSelected')
agents = ran.get('Agents')
supervisor = ran.get('Supervisor')
Comments = ran.get('Comments')
action = ran.get('Action')
subfunction = ran.get('AuditSubFunction')
region = ran.get('AuditRegion')
If it doesn't then content of request.data must be different then payload you shared in original post

inserting a data in a formset passed by a form

hi I have this error in inserting a data in a formset passed by a form this is the error that appears in my browser:
NOT NULL constraint failed: devtest_datigruppi.gruppi_scheda_id
it practically fails to see this change: groups.gruppi_scheda = Schede.objects.get (tab_name = tabName) but via print the right thing appears to me
schedaName = schede_form.cleaned_data['nome_scheda']
scheda = schede_form.save(commit = False)
scheda.utente = request.user
scheda.save()
#gruppi
if gruppi_formset.is_valid():
for gruppi in gruppi_formset:
gruppi.save(commit = False)
gruppi.gruppi_scheda = Schede.objects.get(nome_scheda = schedaName)
//print(gruppi.gruppi_scheda)
gruppi.save()
You have to assign the return value of gruppi.save(commit=False) into a variable and update the gruppi_scheda property there:
gruppi_instance = gruppi.save(commit=False)
gruppi_instance.gruppi_scheda = Schede.objects.get(nome_scheda = schedaName)
gruppi_instance.save()

django filter data and make union of all data points to assignt to a new data

My model is as follows
class Drawing(models.Model):
drawingJSONText = models.TextField(null=True)
project = models.CharField(max_length=250)
Sample data saved in drawingJSONText field is as below
{"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]}
I am trying to write a view file where the data is filtered based on project field and all the resulting queryset of drawingJSONText field are made into one data
def load(request):
""" Function to load the drawing with drawingID if it exists."""
try:
filterdata = Drawing.objects.filter(project=1)
ids = filterdata.values_list('pk', flat=True)
length = len(ids)
print(list[ids])
print(len(list(ids)))
drawingJSONData = dict()
drawingJSONData = {'points': [], 'lines': []}
for val in ids:
if length >= 0:
continue
drawingJSONData1 = json.loads(Drawing.objects.get(id=ids[val]).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]
length -= 1
#print(drawingJSONData)
drawingJSONData = json.dumps(drawingJSONData)
context = {
"loadIntoJavascript": True,
"JSONData": drawingJSONData
}
# Editing response headers and returning the same
response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context))
return response
I runs without error but it shows a blank screen
i dont think the for function is working
any suggestions on how to rectify
I think you may want
for id_val in ids:
drawingJSONData1 = json.loads(Drawing.objects.get(id=id_val).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]

How to raise multiple ValidationError on Django Rest API?

Suppose I have three serializers in function and I want to check the validation. If any errors occur in the condition it Response error message at a time
My function:
def employ_create(request):
if request.method == 'POST':
employ_basic_info = data['basic_info']
employ_academic_info = data['academic_info']
employ_address = data['address']
employ_basic_info_serializer = EmployBasicInfoSerializers(data=employ_basic_info)
employ_academic_info_serializer = EmployAcademicInfoSerializers(data=employ_academic_info)
employ_address_serializer = EmployAddressInfoSerializers(data=employ_address)
if employ_basic_info_serializer.is_valid() and employ_academic_info_serializer.is_valid() and employ_address_serializer.is_valid():
employ_basic_info_serializer.save(employ_id=user_obj)
employ_academic_info_serializer.save(employ_id=user_obj)
employ_address_serializer.save(employ_id=user_obj)
return Response(status=rest_framework.status.HTTP_200_OK)
status_errors = {
'employ_basic_info_error':employ_basic_info_serializer.errors,
'employ_academic_info_error':employ_academic_info_serializer.errors,
'employ_address_error':employ_address_serializer.errors,
}
return Response({'stutase':status_errors}, status=rest_framework.status.HTTP_400_BAD_REQUEST)
I want to return employ_basic_info_serializer, employ_academic_info_serializer, employ_address_serializer errors if any errors occur. How can I do it? pls, help me...
Make sure to call the is_valid() method of each serializer object as,
def employ_create(request):
if request.method == 'POST':
employ_basic_info = data['basic_info']
employ_academic_info = data['academic_info']
employ_address = data['address']
employ_basic_info_serializer = EmployBasicInfoSerializers(
data=employ_basic_info)
employ_academic_info_serializer = EmployAcademicInfoSerializers(
data=employ_academic_info)
employ_address_serializer = EmployAddressInfoSerializers(data=employ_address)
is_valid_employ_basic_info_serializer = employ_basic_info_serializer.is_valid()
is_valid_employ_academic_info_serializer = employ_academic_info_serializer.is_valid()
is_valid_employ_address_serializer = employ_address_serializer.is_valid()
if (
is_valid_employ_academic_info_serializer and
is_valid_employ_basic_info_serializer and
is_valid_employ_address_serializer
):
employ_basic_info_serializer.save(employ_id=user_obj)
employ_academic_info_serializer.save(employ_id=user_obj)
employ_address_serializer.save(employ_id=user_obj)
return Response(status=rest_framework.status.HTTP_200_OK)
status_errors = {
'employ_basic_info_error': employ_basic_info_serializer.errors,
'employ_academic_info_error': employ_academic_info_serializer.errors,
'employ_address_error': employ_address_serializer.errors,
}
return Response(
{'stutase': status_errors},
status=rest_framework.status.HTTP_400_BAD_REQUEST
)

How exactly is tensorflow.control_dependecy applied?

self.solver = 'adam'
if self.solver == 'adam':
optimizer = tf.train.AdamOptimizer(self.learning_rate_init)
if self.solver == 'sgd_nestrov':
optimizer = tf.train.MomentumOptimizer(learning_rate = self.learning_rate_init, momentum = self.momentum, \
use_nesterov = True)
gradients, variables = zip(*optimizer.compute_gradients(self.loss))
clipped_gradients, self.global_norm = tf.clip_by_global_norm(gradients, self.max_grad_norm)
update_ops_ = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
optimizer_op = optimizer.apply_gradients(zip(clipped_gradients, variables))
control_ops = tf.group([self.ema_op] + update_ops_)
with tf.control_dependencies([optimizer_op]):
self.optimizer = control_ops
i call self.optimizer with the session
The code above is not updating the gradients. However if i change the control dependencies part of the code to the one below it works perfectly fine except that it misses out on a final exponential moving average (self.ema_op) update, which is not desirable to me:
self.solver = 'adam'
if self.solver == 'adam':
optimizer = tf.train.AdamOptimizer(self.learning_rate_init)
if self.solver == 'sgd_nestrov':
optimizer = tf.train.MomentumOptimizer(learning_rate = self.learning_rate_init, momentum = self.momentum, \
use_nesterov = True)
gradients, variables = zip(*optimizer.compute_gradients(self.loss))
clipped_gradients, self.global_norm = tf.clip_by_global_norm(gradients, self.max_grad_norm)
update_ops_ = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
optimizer_op = optimizer.apply_gradients(zip(clipped_gradients, variables))
control_ops = tf.group([self.ema_op] + update_ops_)
# with tf.control_dependencies(optimizer_op):
# self.optimizer = control_ops
with tf.control_dependencies([self.ema_op] + update_ops_):
self.optimizer = optimizer.apply_gradients(zip(clipped_gradients, variables))
Please tell me what am i missing?
You need to define the tensorflow operations under the with statement, not just set the variable. Doing self.optimizer = control_ops has no effect because you did not create any tensorflow operations.
Without fully understanding your problem I think you want something like this:
with tf.control_dependencies(optimizer_op):
control_ops = tf.group([self.ema_op] + update_ops_)
self.optimizer = control_ops
The with statement enters a block, under which any new ops you create in tensorflow will be dependent upon optimizer_op in this case.