Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Engage97 yearparamas #210

Open
wants to merge 6 commits into
base: calliope-c7
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 55 additions & 64 deletions calliope_app/api/models/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -833,7 +833,7 @@ def update(self, form_data):
METHODS = ['essentials', 'add', 'edit', 'delete']
for method in METHODS:
if method in form_data.keys():
data = form_data[method]
data = form_data[method]
getattr(Tech_Param, '_' + method)(self, data)


Expand Down Expand Up @@ -937,6 +937,7 @@ def _add(cls, technology, data):
if (('year' in value_dict) & ('value' in value_dict)):
years = value_dict['year']
values = value_dict['value']
build_year_offsets = value_dict['build_year_offset']
num_records = np.min([len(years), len(values)])
new_objects = []
for i in range(num_records):
Expand All @@ -945,6 +946,7 @@ def _add(cls, technology, data):
model_id=technology.model_id,
technology_id=technology.id,
year=years[i],
build_year_offset=build_year_offsets[i],
parameter_id=key,
value=ParamsManager.clean_str_val(vals[0]),
raw_value=vals[1] if len(vals) > 1 else vals[0]))
Expand Down Expand Up @@ -992,6 +994,8 @@ def _edit(cls, technology, data):
raw_value=vals[1] if len(vals) > 1 else vals[0])
if 'year' in value_dict:
parameter_instance.update(year=value_dict['year'])
if 'build_year_offset' in value_dict:
parameter_instance.update(build_year_offset=value_dict['build_year_offset'])

@classmethod
def _delete(cls, technology, data):
Expand All @@ -1009,7 +1013,6 @@ def _delete(cls, technology, data):
model_id=technology.model_id,
id=key).hard_delete()


class Location(models.Model):
class Meta:
db_table = "location"
Expand Down Expand Up @@ -1068,7 +1071,6 @@ def __str__(self):
else:
return '%s | %s [%s]' % (self.location_1, self.technology,
self.technology.pretty_tag)

def update(self, form_data):
""" Update the Location Technology parameters
stored in Loc_Tech_Param """
Expand Down Expand Up @@ -1109,80 +1111,68 @@ class Meta:
def _add(cls, loc_tech, data):
""" Add a new parameter to a location technology """
for key, value_dict in data.items():
if (('year' in value_dict) & ('value' in value_dict)):
if all(field in value_dict for field in ['year', 'value', 'build_year_offset']):
years = value_dict['year']
values = value_dict['value']
num_records = np.min([len(years), len(values)])
build_year_offsets = value_dict['build_year_offset']
num_records = min(len(years), len(values), len(build_year_offsets))
new_objects = []
for i in range(num_records):
vals = str(values[i]).split('||')
value = str(values[i])
if '||' in value:
clean_value, raw_value = value.split('||')
else:
clean_value = raw_value = value
new_objects.append(cls(
model_id=loc_tech.model_id,
loc_tech_id=loc_tech.id,
model_id=loc_tech.model.id,
loc_tech=loc_tech,
year=years[i],
build_year_offset=build_year_offsets[i],
parameter_id=key,
value=ParamsManager.clean_str_val(vals[0]),
raw_value=vals[1] if len(vals) > 1 else vals[0]))
value=ParamsManager.clean_str_val(clean_value.strip()),
raw_value=raw_value.strip()
))
cls.objects.bulk_create(new_objects)

@classmethod
def _edit(cls, loc_tech, data):
""" Edit a location technology parameter """
if 'parameter' in data:
if 'parameter_instance' in data:
for param_id, param_data in data['parameter_instance'].items():
loc_tech_param = cls.objects.filter(id=param_id, loc_tech=loc_tech).first()
if loc_tech_param:
if 'build_year_offset' in param_data:
loc_tech_param.build_year_offset = param_data['build_year_offset']
if 'year' in param_data:
loc_tech_param.year = param_data['year']
if 'value' in param_data:
value = param_data['value']
if '||' in value:
clean_value, raw_value = value.split('||')
else:
clean_value = raw_value = value
loc_tech_param.value = ParamsManager.clean_str_val(clean_value.strip())
loc_tech_param.raw_value = raw_value.strip()
loc_tech_param.save()
elif 'parameter' in data:
for key, value in data['parameter'].items():
vals = str(value).split('||')
cls.objects.filter(
model_id=loc_tech.model_id,
loc_tech_id=loc_tech.id,
parameter_id=key).hard_delete()
cls.objects.create(
model_id=loc_tech.model_id,
loc_tech_id=loc_tech.id,
parameter_id=key,
value=ParamsManager.clean_str_val(vals[0]),
raw_value=vals[1] if len(vals) > 1 else vals[0])
if 'timeseries' in data:
for key, value in data['timeseries'].items():
cls.objects.filter(
model_id=loc_tech.model_id,
loc_tech_id=loc_tech.id,
parameter_id=key).hard_delete()
cls.objects.create(
model_id=loc_tech.model_id,
loc_tech_id=loc_tech.id,
if '||' in value:
clean_value, raw_value = value.split('||')
else:
clean_value = raw_value = value
cls.objects.update_or_create(
loc_tech=loc_tech,
parameter_id=key,
value=ParamsManager.clean_str_val(value),
timeseries_meta_id=value,
timeseries=True)
if 'parameter_instance' in data:
instance_items = data['parameter_instance'].items()
for key, value_dict in instance_items:
parameter_instance = cls.objects.filter(
model_id=loc_tech.model_id,
id=key)
if 'value' in value_dict:
vals = str(value_dict['value']).split('||')
parameter_instance.update(
value=ParamsManager.clean_str_val(vals[0]),
raw_value=vals[1] if len(vals) > 1 else vals[0])
if 'year' in value_dict:
parameter_instance.update(year=value_dict['year'])

defaults={
'value': ParamsManager.clean_str_val(clean_value.strip()),
'raw_value': raw_value.strip(),
'model': loc_tech.model
}
)
@classmethod
def _delete(cls, loc_tech, data):
""" Delete a location technology parameter """
if 'parameter' in data:
for key, value in data['parameter'].items():
cls.objects.filter(
model_id=loc_tech.model_id,
loc_tech_id=loc_tech.id,
parameter_id=key).hard_delete()
elif 'parameter_instance' in data:
instance_items = data['parameter_instance'].items()
for key, value in instance_items:
cls.objects.filter(
model_id=loc_tech.model_id,
id=key).hard_delete()
param_ids = data.get('parameter_instance', [])
for param_id in param_ids:
cls.objects.filter(id=param_id, loc_tech=loc_tech).delete()



class Scenario(models.Model):
Expand Down Expand Up @@ -1451,7 +1441,7 @@ def get_tech_params_dict(level, id, excl_ids=None, systemwide=True):

if level in ['1_tech', '2_loc_tech']:
values += ["year", "timeseries", "timeseries_meta_id",
"raw_value", "value"]
"raw_value", "value", "build_year_offset"]

# System-Wide Handling
if systemwide is False:
Expand All @@ -1467,6 +1457,7 @@ def get_tech_params_dict(level, id, excl_ids=None, systemwide=True):
'id': param["id"] if 'id' in param.keys() else 0,
'level': level,
'year': param["year"] if 'year' in param.keys() else 0,
'build_year_offset': param["build_year_offset"] if "build_year_offset" in param.keys() else 0,
'technology_id': technology.id,
'parameter_root': param["parameter__root"],
'parameter_category': param[parameter__category],
Expand Down
39 changes: 32 additions & 7 deletions calliope_app/api/views/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,35 @@ def delete_technology(request):
return HttpResponse(json.dumps(payload), content_type="application/json")


def format_comment(full_name, data):
actions = []

# Process 'add' actions
if 'add' in data:
for key, value in data['add'].items():
years = value['year']
build_year_offsets = value['build_year_offset']
values = value['value']
for year, offset, val in zip(years, build_year_offsets, values):
formatted_val = val.replace("||", " or ")
actions.append(f"Added technology with build_year_offset {offset}, value {formatted_val}, year {year}")
if 'edit' in data:
if 'parameter_instance' in data['edit']:
edit_count = len(data['edit']['parameter_instance'])
if edit_count > 0:
actions.append(f"Edited {edit_count} parameter instance{'s' if edit_count > 1 else ''}")
if 'delete' in data:
if 'parameter_instance' in data['delete']:
delete_count = len(data['delete']['parameter_instance'])
if delete_count > 0:
actions.append(f"Deleted {delete_count} parameter instance{'s' if delete_count > 1 else ''}")
result = f"{full_name} performed the following actions:\n"
for action in actions:
result += f"* {action}\n"

return result.strip()


@csrf_protect
def update_tech_params(request):
"""
Expand All @@ -607,19 +636,14 @@ def update_tech_params(request):
technology_id = escape(request.POST["technology_id"])
form_data = json.loads(request.POST["form_data"])
escaped_form_data = recursive_escape(form_data)

model = Model.by_uuid(model_uuid)
model.handle_edit_access(request.user)

technology = model.technologies.filter(id=technology_id)

if len(technology) > 0:
technology.first().update(escaped_form_data)
# Log Activity
comment = "{} updated the technology: {}.".format(
request.user.get_full_name(),
technology.first().pretty_name,
)
comment = format_comment(request.user.get_full_name(), escaped_form_data)
# Change this: from what params to this... Move to _add request.user
Model_Comment.objects.create(model=model, comment=comment, type="edit")
model.notify_collaborators(request.user)
model.deprecate_runs(technology_id=technology_id)
Expand Down Expand Up @@ -862,6 +886,7 @@ def update_loc_tech_params(request):
if len(loc_tech) > 0:
loc_tech.first().update(form_data)
# Log Activity
comment = format_comment(request.user.get_full_name(), form_data)
comment = "{} updated the node: {} ({}) @ {}.".format(
request.user.get_full_name(),
loc_tech.first().technology.pretty_name,
Expand Down
3 changes: 1 addition & 2 deletions calliope_app/client/component_views/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from django.utils.timezone import make_aware

from api.models.configuration import Scenario_Param, Scenario, Scenario_Loc_Tech, \
Timeseries_Meta, ParamsManager, Model, User_File, Carrier, Tech_Param
Timeseries_Meta, ParamsManager, Model, User_File, Carrier, Tech_Param, Loc_Tech_Param
from api.utils import get_cols_from_csv


Expand Down Expand Up @@ -158,7 +158,6 @@ def all_tech_params(request):

for param in parameters:
param['raw_units'] = param['units']

timeseries = Timeseries_Meta.objects.filter(model=model, failure=False,
is_uploading=False)

Expand Down
Loading