Restructure code

This commit is contained in:
Daniel Rojas 2020-10-24 14:32:14 +02:00
parent 9d0582e10c
commit caaaa38feb

View File

@ -6,7 +6,6 @@ import os
from pathlib import Path from pathlib import Path
import sys import sys
from typing import Any, Tuple from typing import Any, Tuple
import re
import yaml import yaml
@ -33,20 +32,20 @@ def parse(yaml_input: str, file_out: (str, Path) = None, return_types: (None, st
- "harness" - will return the `Harness` instance - "harness" - will return the `Harness` instance
""" """
yaml_data = yaml.safe_load(yaml_input) # define variables =========================================================
# containers for parsed component data and connection sets
template_connectors = {} template_connectors = {}
template_connector_names = []
template_cables = {} template_cables = {}
template_cable_names = [] connection_sets = []
# actual harness
designators_and_templates = {}
autogenerated_designators = {}
alternating_sections = ['connectors','cables']
harness = Harness() harness = Harness()
# others
designators_and_templates = {} # store mapping of components to their respective template
autogenerated_designators = {} # keep track of auto-generated designators to avoid duplicates
# add items # parse YAML input file ====================================================
yaml_data = yaml.safe_load(yaml_input)
sections = ['connectors', 'cables', 'connections'] sections = ['connectors', 'cables', 'connections']
types = [dict, dict, list] types = [dict, dict, list]
for sec, ty in zip(sections, types): for sec, ty in zip(sections, types):
@ -60,12 +59,11 @@ def parse(yaml_input: str, file_out: (str, Path) = None, return_types: (None, st
# if isinstance(image, dict): # if isinstance(image, dict):
# image['gv_dir'] = Path(file_out if file_out else '').parent # Inject context # image['gv_dir'] = Path(file_out if file_out else '').parent # Inject context
# store component templates only; do not generate instances yet
if sec == 'connectors': if sec == 'connectors':
template_connectors[key] = attribs template_connectors[key] = attribs
template_connector_names.append(key)
elif sec == 'cables': elif sec == 'cables':
template_cables[key] = attribs template_cables[key] = attribs
template_cable_names.append(key)
else: else:
pass # section exists but is empty pass # section exists but is empty
else: # section does not exist, create empty section else: # section does not exist, create empty section
@ -74,8 +72,12 @@ def parse(yaml_input: str, file_out: (str, Path) = None, return_types: (None, st
elif ty == list: elif ty == list:
yaml_data[sec] = [] yaml_data[sec] = []
print('Conector templates:', template_connector_names) connection_sets = yaml_data['connections']
print('Cable templates: ', template_cable_names)
print('Conector templates:', list(template_connectors.keys()))
print('Cable templates: ', list(template_cables.keys()))
# go through connection sets, generate and connect components ==============
def resolve_designator(inp): def resolve_designator(inp):
if '.' in inp: # generate a new instance of an item if '.' in inp: # generate a new instance of an item
@ -83,7 +85,7 @@ def parse(yaml_input: str, file_out: (str, Path) = None, return_types: (None, st
if designator == '': if designator == '':
autogenerated_designators[template] = autogenerated_designators.get(template, 0) + 1 autogenerated_designators[template] = autogenerated_designators.get(template, 0) + 1
designator = f'_{template}_{autogenerated_designators[template]}' designator = f'_{template}_{autogenerated_designators[template]}'
# check if contradiction # check if redefining existing component to different template
if designator in designators_and_templates: if designator in designators_and_templates:
if designators_and_templates[designator] != template: if designators_and_templates[designator] != template:
raise Exception(f'Trying to redefine {designator} from {designators_and_templates[designator]} to {template}') raise Exception(f'Trying to redefine {designator} from {designators_and_templates[designator]} to {template}')
@ -98,10 +100,8 @@ def parse(yaml_input: str, file_out: (str, Path) = None, return_types: (None, st
designators_and_templates[designator] = template designators_and_templates[designator] = template
return (template, designator) return (template, designator)
connection_sets = yaml_data['connections']
for connection_set in connection_sets: for connection_set in connection_sets:
print('') print('')
print('connection set @0:', connection_set) print('connection set @0:', connection_set)
# figure out number of parallel connections within this set # figure out number of parallel connections within this set
@ -113,7 +113,6 @@ def parse(yaml_input: str, file_out: (str, Path) = None, return_types: (None, st
connectioncount.append(len(expand(list(entry.values())[0]))) # - X1: [1-4,6] yields 5 connectioncount.append(len(expand(list(entry.values())[0]))) # - X1: [1-4,6] yields 5
else: else:
connectioncount.append(None) # strings do not reveal connectioncount connectioncount.append(None) # strings do not reveal connectioncount
if not any(connectioncount): if not any(connectioncount):
raise Exception('No item in connection set revealed number of connections') raise Exception('No item in connection set revealed number of connections')
print(f'Connection count: {connectioncount}') print(f'Connection count: {connectioncount}')
@ -121,7 +120,7 @@ def parse(yaml_input: str, file_out: (str, Path) = None, return_types: (None, st
# check that all entries are the same length # check that all entries are the same length
if len(set(filter(None, connectioncount))) > 1: if len(set(filter(None, connectioncount))) > 1:
raise Exception('All items in connection set must reference the same number of connections') raise Exception('All items in connection set must reference the same number of connections')
# all entries are the same length, connection count is set
connectioncount = list(filter(None, connectioncount))[0] connectioncount = list(filter(None, connectioncount))[0]
# expand string entries to list entries of correct length # expand string entries to list entries of correct length
@ -167,21 +166,24 @@ def parse(yaml_input: str, file_out: (str, Path) = None, return_types: (None, st
print('connection set @3:', connection_set) print('connection set @3:', connection_set)
# TODO: check alternating cable/connector # TODO: check alternating cable/connector
alternating_sections = ['connectors','cables']
# generate items # Populate wiring harness ==============================================
# generate components
for entry in connection_set: for entry in connection_set:
for item in entry: for item in entry:
designator = list(item.keys())[0] designator = list(item.keys())[0]
template = designators_and_templates[designator] template = designators_and_templates[designator]
if designator in harness.connectors: if designator in harness.connectors:
print(' ', designator, 'is an existing connector instance') print(' ', designator, 'is an existing connector instance')
elif template in template_connector_names: elif template in template_connectors.keys():
print(' ', designator, 'is a new connector instance of type', template) print(' ', designator, 'is a new connector instance of type', template)
harness.add_connector(name = designator, **template_connectors[template]) harness.add_connector(name = designator, **template_connectors[template])
elif designator in harness.cables: elif designator in harness.cables:
print(' ', designator, 'is an existing cable instance') print(' ', designator, 'is an existing cable instance')
elif template in template_cable_names: elif template in template_cables.keys():
print(' ', designator, 'is a new cable instance of type', template) print(' ', designator, 'is a new cable instance of type', template)
harness.add_cable(name = designator, **template_cables[template]) harness.add_cable(name = designator, **template_cables[template])
@ -191,12 +193,14 @@ def parse(yaml_input: str, file_out: (str, Path) = None, return_types: (None, st
else: else:
print(f' Template {template} not found, neither in connectors nor in cables') print(f' Template {template} not found, neither in connectors nor in cables')
# transpose connection set list
# before: one row per component, one column per connection in set
# after: one row per connection in set, one column per component
print('TRANSPOSE!!') print('TRANSPOSE!!')
connection_set = list(map(list, zip(*connection_set))) # transpose list connection_set = list(map(list, zip(*connection_set))) # transpose list
print(connection_set) print(connection_set)
# actually connect components using connection list # connect components
for index_entry, entry in enumerate(connection_set): for index_entry, entry in enumerate(connection_set):
print(f' entry ie {index_entry}', entry) print(f' entry ie {index_entry}', entry)
for index_item, item in enumerate(entry): for index_item, item in enumerate(entry):
@ -240,6 +244,7 @@ def parse(yaml_input: str, file_out: (str, Path) = None, return_types: (None, st
print(f' Mate {from_name} {designator} {to_name} ({index_entry})') print(f' Mate {from_name} {designator} {to_name} ({index_entry})')
harness.add_mate_component(from_name, to_name, designator) harness.add_mate_component(from_name, to_name, designator)
# harness population comleted ==============================================
if "additional_bom_items" in yaml_data: if "additional_bom_items" in yaml_data:
for line in yaml_data["additional_bom_items"]: for line in yaml_data["additional_bom_items"]: