Skip to content

Commit

Permalink
810 - Carbon Calculator actions update - Part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
BradHN1 committed Oct 10, 2023
1 parent b294821 commit 077ac1c
Show file tree
Hide file tree
Showing 6 changed files with 1,110 additions and 86 deletions.
59 changes: 29 additions & 30 deletions src/carbon_calculator/CCDefaults.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
from fileinput import filename
from .models import CalcDefault
#from .calcUsers import CalcUserLocality
from datetime import datetime
import time
import timeit
from django.utils import timezone
import csv
from pathlib import Path # python3 only

def getLocality(inputs):
id = inputs.get("user_id","")
Expand All @@ -25,68 +22,63 @@ def getLocality(inputs):
return locality


def getDefault(locality, variable, date=None):
return CCD.getDefault(CCD,locality, variable, date)
def getDefault(locality, variable, date=None, default=None):
return CCD.getDefault(CCD,locality, variable, date, default=default)

def removeDuplicates():
print("Removing duplicate default values, please wait...")
# assuming which duplicate is removed doesn't matter...
for row in CalcDefault.objects.all().reverse():
if CalcDefault.objects.filter(variable=row.variable, locality=row.locality, valid_date=row.valid_date).count() > 1:
print("Purging "+row.variable+" in "+row.locality+" locality, valid from"+str(row.valid_date))
row.delete()
print("Done!")


class CCD():
DefaultsByLocality = {"default":{}} # the class variable

def ready(self):
DefaultsByLocality = {"default":{}} # the class variable
self.DefaultsByLocality = {"default":{}} # the class variable
try:
cq = CalcDefault.objects.all()
for c in cq:
# valid date is 0 if not specified
date = '2000-01-01'
if c.valid_date != None:
date = c.valid_date
if c.locality not in DefaultsByLocality:
DefaultsByLocality[c.locality] = {}
if c.variable not in DefaultsByLocality[c.locality]:
DefaultsByLocality[c.locality][c.variable] = {"valid_dates":[date], "values":[c.value]}

if c.locality not in self.DefaultsByLocality:
self.DefaultsByLocality[c.locality] = {}
if c.variable not in self.DefaultsByLocality[c.locality]:
self.DefaultsByLocality[c.locality][c.variable] = {"valid_dates":[date], "values":[c.value]}
else:
# already one value for this parameter, order by dates
f = False
for i in range(len(DefaultsByLocality[c.locality][c.variable]["values"])):
valid_date = DefaultsByLocality[c.locality][c.variable]["valid_dates"][i]
for i in range(len(self.DefaultsByLocality[c.locality][c.variable]["values"])):
valid_date = self.DefaultsByLocality[c.locality][c.variable]["valid_dates"][i]
if date < valid_date:
# insert value at this point
f = True
DefaultsByLocality[c.locality][c.variable]["valid_dates"].insert(i,date)
DefaultsByLocality[c.locality][c.variable]["values"].insert(i,c.value)
self.DefaultsByLocality[c.locality][c.variable]["valid_dates"].insert(i,date)
self.DefaultsByLocality[c.locality][c.variable]["values"].insert(i,c.value)
break
elif date == valid_date:
# multiple values with one date; clean this from database
removeDuplicates()
print("Duplicate encountered")
f = True
break

# if not inserted into list, append to the end
if not f:
DefaultsByLocality[c.locality][c.variable]["valid_dates"].append(date)
DefaultsByLocality[c.locality][c.variable]["values"].append(c.value)
self.DefaultsByLocality[c.locality][c.variable]["valid_dates"].append(date)
self.DefaultsByLocality[c.locality][c.variable]["values"].append(c.value)


except Exception as e:
print(str(e))
print("CalcDefault initialization skipped")

def __init__(self):
print("CCD __init__ called")


def __init__(self):
print("CCD __init__ called")

def getDefault(self, locality, variable, date):
def getDefault(self, locality, variable, date, default=None):
if locality not in self.DefaultsByLocality:
locality = "default"
if variable in self.DefaultsByLocality[locality]:
Expand All @@ -103,6 +95,8 @@ def getDefault(self, locality, variable, date):
return value

# no defaults found. Signal this as an error.
if default:
return default
raise Exception('Carbon Calculator error: value for "'+variable+'" not found in CalcDefaults')

def exportDefaults(self,fileName):
Expand Down Expand Up @@ -134,6 +128,8 @@ def exportDefaults(self,fileName):

def importDefaults(self,fileName):
csvfile = None
print("Updating Carbon Calculator constant values.")
removeDuplicates()
try:
status = True
with open(fileName, newline='') as csvfile:
Expand All @@ -158,6 +154,9 @@ def importDefaults(self,fileName):
value = eval(item[t["Value"]])
reference = item[t["Reference"]]
updated = item[t["Updated"]]
updated = datetime.strptime(updated, '%Y-%m-%d %H:%M')
current_tz = timezone.get_current_timezone()
updated = current_tz.localize(updated)

if not valid_date or valid_date=="":
valid_date = '2000-01-01'
Expand Down
39 changes: 23 additions & 16 deletions src/carbon_calculator/carbonCalculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@
from .foodWaste import EvalLowCarbonDiet, EvalReduceWaste, EvalCompost
from .landscaping import EvalReduceLawnSize, EvalReduceLawnCare, EvalRakeOrElecBlower, EvalElectricMower
#from .calcUsers import ExportCalcUsers, CalcUserUpdate
# uncomment to measure elapsed time
#import time

CALCULATOR_VERSION = "4.0.1"
CALCULATOR_VERSION = "4.0.2"
QUESTIONS_DATA = BASE_DIR + "/carbon_calculator/content/Questions.csv"
ACTIONS_DATA = BASE_DIR + "/carbon_calculator/content/Actions.csv"
DEFAULTS_DATA = BASE_DIR + "/carbon_calculator/content/defaults.csv"
#QUESTIONS_DATA = "/carbon_calculator/content/Questions.csv"
#ACTIONS_DATA = "/carbon_calculator/content/Actions.csv"
#DEFAULTS_DATA = "/carbon_calculator/content/Defaults.csv"
TOKEN_POINTS = 15

def fileDateTime(path):
# file modification
Expand Down Expand Up @@ -119,12 +119,13 @@ def SavePic2Media(picURL):

def AverageImpact(action, date=None, locality="default"):
averageName = action.name + '_average_points'
impact = getDefault(locality, averageName, date)
impact = getDefault(locality, averageName, date, default=TOKEN_POINTS)
return impact

class CarbonCalculator:
def __init__(self, reset=False) :
#fails on initial migration during test
# uncomment to measure elapsed time
#start = time.time()
try:
print("Initializing Carbon Calculator, version "+CALCULATOR_VERSION)

Expand Down Expand Up @@ -191,6 +192,10 @@ def __init__(self, reset=False) :
theInstance = theClass(name)
self.allActions[name] = theInstance

# uncomment to measure elapsed time
#end = time.time()
#print(end - start)

except Exception as e:
print(str(e))
print("Calculator initialization skipped")
Expand Down Expand Up @@ -385,23 +390,26 @@ def ImportActions(self, actionsFile):
if first:
t = {}
for i in range(len(item)):
if i==0:
item[i] = 'Name'
t[item[i]] = i
first = False
else:
name = item[0]
if name == '':
continue

# update the unique Action with this name
qs, created = Action.objects.update_or_create(
name=name,
defaults={
avg_points = item[t["Avg points"]]
defaults = {
'description':item[t["Description"]],
'helptext':item[t["Helptext"]],
'category':item[t["Category"]],
'average_points':int(eval(item[t["Avg points"]])),
'average_points': int(eval(avg_points)) if avg_points else TOKEN_POINTS,
'questions':item[t["Questions"]].split(",")
}
# update the unique Action with this name
qs, created = Action.objects.update_or_create(
name=name,
defaults=defaults
)

if created:
Expand Down Expand Up @@ -458,9 +466,10 @@ def __init__(self,name):
self.savings = 0
self.text = "" # "Explanation for the calculated results."
self.picture = ""
#

def Query(self):
status, actionInfo = QuerySingleAction(self.name)
if status == VALID_QUERY:
if not self.id and status == VALID_QUERY:
self.id = actionInfo["id"]
self.title = actionInfo["title"]
self.description = actionInfo["description"]
Expand All @@ -470,8 +479,6 @@ def __init__(self,name):
self.picture = actionInfo["picture"]
self.initialized = True

def Query(self):
status, actionInfo = QuerySingleAction(self.name)
return {"status":status, "action":actionInfo}

def Eval(self, inputs):
Expand Down
Loading

0 comments on commit 077ac1c

Please sign in to comment.