Commit 876726d0 authored by Greenwood, Scott's avatar Greenwood, Scott
Browse files

add documentation and some minor restructure

parent 83ce80d8
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
@@ -49,7 +49,7 @@ class JuliaMethods(LanguageMethod):
            RuntimeError: If the architecture creation fails.
        """
        # Call the parent logic
        super().create_architecture(template_folder)
        template_folder = super().create_architecture(template_folder)
        
        try:
            # TODO: Insert supported methods here, for example:
+52 −23
Original line number Diff line number Diff line
@@ -18,7 +18,6 @@ import re
import pathlib

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))
import helper_functions

@@ -146,6 +145,30 @@ def replace_string_between_identifiers(input_string, replacement_text, left_iden
    output = re.sub(pattern_string, left_identifier + replacement_text + right_identifier, input_string)
    return output

def handle_package_mo(folder):
    """
    Ensures the package.mo file exists in the folder.
    
    Parameters:
    folder (pathlib.Path): The folder where package.mo should be created.
    """
    if len([f for f in folder.glob('package.mo')]) == 0:
        with open(os.path.join(folder, 'package.mo'), 'w') as pkgfile:
            pkgfile.write('within TO_BE_REPLACED;\n')
            pkgfile.write(f'package {folder.stem}\n')
            pkgfile.write(f'end {folder.stem};\n')
        
def handle_package_order(folder):
    """
    Ensures the package.order file exists and is up-to-date.
    
    Parameters:
    folder (pathlib.Path): The folder where package.order should be created.
    """
    if len([f for f in folder.glob('package.order')]) == 0:
        with open(os.path.join(folder, 'package.order'), 'w') as pkgfile:
            pkgfile.write('')
            
def correct_package_files(project_path, template_folder):
    """
    Corrects and ensures the existence of package.mo, *.mo "within ...;", and package.order files within the project directory.
@@ -164,18 +187,8 @@ def correct_package_files(project_path, template_folder):
    folders = [f for f in path.glob("**/*") if not f.is_file()]
    folders.append(path)
    for folder in folders:
        # Create default package.mo file if it does not exist
        # temp_package_mo = folder.glob('package.mo')
        if len([f for f in folder.glob('package.mo')]) == 0:
               with open(os.path.join(folder, 'package.mo'), 'w') as pkgfile:
                   pkgfile.write('within TO_BE_REPLACED;\n')
                   pkgfile.write(f'package {folder.stem}\n')
                   pkgfile.write(f'end {folder.stem};\n')
                   
        # Create default package.order file if it does not exist
        if len([f for f in folder.glob('package.order')]) == 0:
               with open(os.path.join(folder, 'package.order'), 'w') as pkgfile:
                   pkgfile.write('')
        handle_package_mo(folder)  # Create default package.mo file if it does not exist                  
        handle_package_order(folder) # Create default package.order file if it does not exist
        
    # package.mo and *.mo "within ...;" specific corrections
    files = [f for f in path.glob("**/*.mo") if f.is_file()]
@@ -264,6 +277,30 @@ def sort_folder_content(folder_content, method='default'):
        
    return order_names
  
def get_unique_systems(systems_list):
    """
    Returns a list of unique systems from the provided systems list.
    
    Parameters:
    systems_list (list): List of systems to filter for uniqueness.
    
    Returns:
    tuple: A tuple of the unique systems list and a list of duplicate reports.
    """
    seen_names = set()
    unique_systems = []
    report = []
    
    for system in systems_list:
        if system:
            if system['Name'] in seen_names:
                report.append(f"Removed duplicate system with name: {system['Name']}")
            else:
                seen_names.add(system['Name'])
                unique_systems.append(system)
    
    return unique_systems, report

def remove_duplicate_systems(input_dict, current_level=0):
    """
    Checks at every level in the nested dictionary if the 'systems' field's values contain 
@@ -285,16 +322,9 @@ def remove_duplicate_systems(input_dict, current_level=0):

    # Check for duplicates in the systems field at the current level
    if 'Systems' in cleaned_dict:
        seen_names = set()
        unique_systems = []
        for system in cleaned_dict['Systems']:
            if system:
                if system['Name'] in seen_names:
                    report.append(f"Removed duplicate system with name: {system['Name']} at level {current_level}")
                else:
                    seen_names.add(system['Name'])
                    unique_systems.append(system)
        unique_systems, system_report = get_unique_systems(cleaned_dict['Systems'])
        cleaned_dict['Systems'] = unique_systems
        report.extend(system_report)

        # Recursively check the nested dictionaries
        for idx, system in enumerate(cleaned_dict['Systems']):
@@ -323,7 +353,6 @@ def main(json_file_path, output_path, template_folder, architecture='nested'):
    data, report = remove_duplicate_systems(data)

    # Output the updated dictionary and the report
    
    if report:
        print('Duplicate systems removed for architecture creation:')
        print("Report:\n", report)
+0 −1
Original line number Diff line number Diff line
@@ -8,7 +8,6 @@ Users may choose either license, at their discretion.
"""

import pathlib
# import re

import sys
import os
+1 −1
Original line number Diff line number Diff line
@@ -48,7 +48,7 @@ class ModelicaMethods(LanguageMethod):
            RuntimeError: If the architecture creation fails.
        """
        # Call the parent logic
        super().create_architecture(template_folder)
        template_folder = super().create_architecture(template_folder)
        
        try:
            create_architecture.main(self.parent.input_specification,
+71 −0
Original line number Diff line number Diff line
@@ -11,16 +11,45 @@ import re
import os

def get_file_lines(file_path):
    """
    Reads all lines from a file and returns them as a list.

    Parameters:
    file_path (str): Path to the file to read.

    Returns:
    list: List of lines from the file.
    """
    with open(file_path, 'r') as struct:
        lines = struct.readlines()  
    return lines

def convert_lines_to_string(lines):
    """
    Converts a list of lines into a single string, joining them with spaces.

    Parameters:
    lines (list): List of lines (strings).

    Returns:
    str: A single string with all lines joined by spaces.
    """
    output = ' '.join(lines)
    # output = output.replace('\n',' ')
    return output

def extract_variable(input_string, dtype=None):
    """
    Extracts variable definitions from a given input string based on modelica type.

    Parameters:
    input_string (str): The input string to search for variables.
    dtype (str or list): Type of variable to extract (e.g., 'parameter', 'input'). 
                         If None, defaults to 'parameter|input|output'.

    Returns:
    list: A list of tuples containing variable details (dtype, variable name, etc.).
    """
    if dtype is None:
        dtype = 'parameter|input|output'
    elif type(dtype) == list:
@@ -31,12 +60,33 @@ def extract_variable(input_string, dtype=None):
    return variables

def get_variable_by_type(file_path, dtype='parameter'):
    """
    Retrieves variables from a file based on a specified modelica type (e.g., parameter, input, output).

    Parameters:
    file_path (str): Path to the file.
    dtype (str): Type of variable to extract ('parameter' by default).

    Returns:
    list: A list of tuples representing the variables found.
    """
    lines = get_file_lines(file_path)
    input_string = convert_lines_to_string(lines)
    parameters = extract_variable(input_string, dtype)
    return parameters

def extract_default_class_from_model(file_path, folder='Sources', instance='sources'):
    """
    Extracts the default class redeclaration for a given model file.

    Parameters:
    file_path (str): Path to the file to read.
    folder (str): Name of the folder (e.g., 'Sources', 'Models',...).
    instance (str): Name of the instance (e.g., 'sources').

    Returns:
    list: A list of matches found for redeclared replaceable classes.
    """
    # Define the regex pattern
    pattern = r'redeclare\s+replaceable\s+{}.(\w+)\s+{}'.format(folder, instance)

@@ -47,6 +97,15 @@ def extract_default_class_from_model(file_path, folder='Sources', instance='sour
    return matches

def apply_instance_naming_conventions(name):
    """
    Applies naming conventions for instance names.

    Parameters:
    name (str): The original name.

    Returns:
    str: The name converted to follow conventions (lowercase abbreviation or lowercased first letter).
    """
    if name.isupper():
        # Abbreviations are all lowercase for the the instance (e.g., CDU -> cdu)
        name = name.lower()
@@ -56,6 +115,18 @@ def apply_instance_naming_conventions(name):
    return name

def search_log_file_reverse(file_path, search_text):
    """
    Searches a log file for a specific text in reverse (from the end of the file).
    It reads the file in chunks and processes the lines backward.
    
    Parameters:
    file_path (str): Path to the log file to search.
    search_text (str): The text to search for in the log file.
    
    Returns:
    None: Prints the line number where the text is found.
"""

    # Open the file in binary mode
    with open(file_path, 'rb') as file:
        # Set file pointer to the end of the file
Loading