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

Compute can load #13

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
182 changes: 173 additions & 9 deletions can.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/bin/python

from operator import mod
from unicodedata import normalize
import json
import re
Expand Down Expand Up @@ -40,7 +41,7 @@ def validate_bit(bit: int) -> bool:
return True

class topic:
def __init__(self, msg: str, id: int, description: str):
def __init__(self, msg: str, id: int,frequency: int, description: str):
self.name = Can.convert_string(msg)

if not isinstance(id, int):
Expand All @@ -53,6 +54,10 @@ def __init__(self, msg: str, id: int, description: str):

self.bytes = [None] * 8

self.frequency = frequency

self.frame_length = 47
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why 47? Can you add a comment pointing to a source or explaining it.


self.describe_byte(
"signature", 0, "Senders signature", "uint8_t", "")

Expand All @@ -61,7 +66,9 @@ def get(self) -> dict:
"name": str(self.name),
"description": self.description,
"id": self.id,
"bytes": self.bytes
"bytes": self.bytes,
"frequency": self.frequency,
"frame_length": self.frame_length
}

def __str__(self) -> str:
Expand Down Expand Up @@ -99,6 +106,12 @@ def validate_bit_name(self, byte: int, name: str):
for bit in filter(None, self.bytes[byte].get('bits')):
if bit == Can.convert_string(name):
raise ValueError("bit field `name` must be unique!")

def get_length(self):
return len(list(filter(lambda x: x is not None, self.bytes)))

def get_frame_length(self):
return 44 + 8 * self.get_length()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why 44 and 8? Can you add a comment pointing to a source or explaining it.


def describe_byte(self,
name: str,
Expand All @@ -120,6 +133,8 @@ def describe_byte(self,

name = Can.convert_string(name)

self.frame_length += 8

self.bytes[byte] = {
"name": name,
"description": description,
Expand Down Expand Up @@ -172,6 +187,12 @@ def get(self) -> dict:
"topics": self.topics
}

def get_total_load(self, bitrate):
load = 0
for topic in self.topics:
load += topic.get_load(bitrate)
return load

def __str__(self) -> str:
return json.dumps(self.get(), indent=4)

Expand All @@ -182,14 +203,16 @@ def add_topic(self, topic):

self.topics.append(topic.get())

def __init__(self, version: str):
def __init__(self, version: str, bitrate: int):
self.version = version
self.modules = []
self.bitrate = bitrate

def get(self) -> dict:
return {
"version": self.version,
"modules": self.modules,
"bitrate": self.bitrate,
}

def __str__(self) -> str:
Expand Down Expand Up @@ -228,26 +251,167 @@ def export_c_library(self, filename: str = "can_ids.h"):
self.export_h("can_ids.h")
self.export_h("can_parser_types.h")

def export_csv(self, filename: str):
import pandas as pd

modules = []
signature = []
ids = []
names = []
frequency = []
load = []
frame_length = []
description = []

for module in self.modules:
for topic in module["topics"]:
modules.append(module["name"])
signature.append(module["signature"])
ids.append(topic["id"])
names.append(topic["name"])
frequency.append(round(topic["frequency"],3))
load.append(round(self.get_topic_load(topic),3))
frame_length.append(topic["frame_length"])
description.append(topic["description"])

df = pd.DataFrame({
"modules":modules,
"signature": signature,
"name": names,
"ids": ids,
"frequency": frequency,
"load": load,
"frame_length": frame_length,
"description": description,
})
Comment on lines +257 to +286
Copy link
Member

@joaoantoniocardoso joaoantoniocardoso Oct 29, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this data is small it is okay doing it this way, but note that for bigger data, possibly it would be better convert it to a DataFrame first, then group / add / remove columns as you need.


df.to_csv(filename)


def get_can_load_by_topic(self):
load = {}
for module in self.modules:
for topic in module["topics"]:
if not topic["id"] in load.keys():
load[topic["id"]] = []
load[topic["id"]].append(self.get_topic_load(topic))
return load


def get_can_load(self):
load = 0
for module in self.modules:
for topic in module["topics"]:
load += self.get_topic_load(topic)
return load

def get_topic_load(self, topic: dict):
frame_length = topic["frame_length"]
frame_period = (1/self.bitrate) * frame_length
return frame_period * topic["frequency"] * 100
# load = period for 1 msg * frequency * 100%
# Reference:
# https://support.vector.com/kb?id=kb_article_view&sysparm_article=KB0012332&sys_kb_id=99354e281b2614148e9a535c2e4bcb6d&spa=1
Comment on lines +312 to +314
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Always great to have references, move it on the beginning of the function


def plot_load(self):
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(nrows= 2, ncols=2,figsize=(9, 6))
plt.figtext(.5, .9, "Can Load ", fontsize=15, ha='center')

### Ids x Load
ids = {}
for module in self.modules:
for topic in module["topics"]:
if not topic["id"] in ids.keys():
ids[topic["id"]] = 0
ids[topic["id"]] += self.get_topic_load(topic)

id = list(ids.keys())
id.sort()

load = []
for i in id:
load.append(ids[i])

axes[0][0].bar(range(0, len(id)), load, align='center', color='royalblue')
axes[0][0].set_xticks(range(0, len(id)))
axes[0][0].set_xticklabels(list(id), fontsize = 9, rotation = 90)
axes[0][0].set_title("Load x Id")
axes[0][0].set_ylabel("Load [%]")
axes[0][0].set_xlabel("Ids")
axes[0][0].invert_xaxis()
axes[0][0].grid()

id.append("free")
load.append(100 - sum(load))
cmap = plt.cm.prism
colors = cmap(np.linspace(0.2, 0.8, len(id)))
axes[0][1].set_title("Load x Id")
axes[0][1].pie(load, labels=id,
textprops={'size': 'smaller'}, radius=1.5,colors=colors, labeldistance=1.1, startangle=-45)

#### Modules X Load
load = []
modules = {}
for module in self.modules:
for topic in module["topics"]:
if not module["name"] in modules.keys():
modules[module["name"]] = 0
modules[module["name"]] += self.get_topic_load(topic)
load = list(modules.values())
modules = list(modules.keys())
axes[1][0].set_title("Load x Module")
axes[1][0].bar(range(0, len(modules)), load)
axes[1][0].set_xticks(range(0,len(modules)))
axes[1][0].set_xticklabels(modules, fontsize = 9, rotation=90)
axes[1][0].set_ylabel("Load [%]")

modules.append("free")
load.append(100.0 - sum(load))
axes[1][1].set_title("Load x Module")
axes[1][1].pie(load, labels=modules,
textprops={'size': 'smaller'}, radius=1.5, labeldistance=1.1,startangle=-45)



plt.show()




if __name__ == '__main__':
t1 = Can.topic("motor", 9, "Motor controller parameters")
t1 = Can.topic("motor", 9, 100, "Motor controller parameters")
t1.describe_byte("motor", 1, "Switches and states", "bitfield", "")
t1.describe_bit("motor on", 1, 0)
t1.describe_byte("D raw", 2, "Motor Duty Cycle", "uint8_t", "%")
t1.describe_byte("I raw", 3, "Motor Soft Start", "uint8_t", "%")
t2 = Can.topic("motor2", 19, 10, "Motor controller parameters")
t2.describe_byte("motor", 1, "Switches and states", "bitfield", "")
t2.describe_bit("motor on", 1, 0)
t2.describe_byte("D raw", 2, "Motor Duty Cycle", "uint8_t", "%")
t2.describe_byte("I raw", 3, "Motor Soft Start", "uint8_t", "%")
# print(t1)

m1 = Can.module("mic17", 10, "Modulo de Interface de Controle")
m1.add_topic(t1)
m1.add_topic(t2)
m2 = Can.module("mam21", 10, "Mamm")

# print(m1)

c1 = Can()
c1 = Can("0.0.0", 500e3)
c1.add_module(m1)
# print(c1)
c1.export_json("sample.json")
print(c1.get_can_load())
print(c1.get_topic_load(t1.get()))
c1.plot_load()
c1.export_csv("a")
# c2 = Can()
# c2.import_json("sample.json")
# print(c2)

c2 = Can()
c2.import_json("sample.json")
print(c2)
# c2.export_ids_h("sample.h")

c2.export_ids_h("sample.h")

Loading