Commit 2053ecb6 authored by Greenwood, Scott's avatar Greenwood, Scott
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading

.gitignore

0 → 100644
+5 −0
Original line number Diff line number Diff line
*.bak-mo
**/dsfinal.txt
temp/
*.zip
*.pyc

AutoCSM/__init__.py

0 → 100644
+0 −0

Empty file added.

AutoCSM/auto_csm.py

0 → 100644
+104 −0
Original line number Diff line number Diff line
# -*- coding: utf-8 -*-
"""
Created on Wed Jun  5 13:10:34 2024

@author: fig
"""

from languages.modelica.modelica_methods import ModelicaMethods
from languages.julia.julia_methods import JuliaMethods

import helper_functions
import pathlib

class AutoCSM:
    def __init__(self, language='modelica', architecture='nested', terminal_animation=True):
        self.language = language
        self.architecture = architecture
        self.language_methods = {
            'modelica': ModelicaMethods(self),
            'julia': JuliaMethods(self)
        }
        self.terminal_animation = terminal_animation

    def set_language(self, language):
        if language in self.language_methods:
            self.language = language
        else:
            raise ValueError(f"Unsupported language: {language}")

    def set_architecture(self, architecture):
        self.architecture = architecture

    def set_input_specification(self, input_specification):
        self.input_specification = input_specification
   
    def set_output_path(self, output_path):
        self.output_path = output_path
    
    def set_model_path(self, model_path):
        self.model_path = model_path
 
    def set_project_path(self, project_path):
        # Remove package.mo if contained in project_path (i.e., a common issue)
        temp = pathlib.Path(project_path)
        if temp.name == "package.mo":
            temp = temp.parent
        self.project_path = str(temp)
        
    ## Sub-class methods
    def create_architecture(self, *args, **kwargs):
        if self.terminal_animation:
            with helper_functions.Loader("Creating the architecture..."):
                return self.language_methods[self.language].create_architecture(*args, **kwargs)
        else:
            print("Creating the architecture...")
            return self.language_methods[self.language].create_architecture(*args, **kwargs)
        
    def create_model(self, *args, **kwargs):
        if self.terminal_animation:
            with helper_functions.Loader("Creating the model..."):
                return self.language_methods[self.language].create_model(*args, **kwargs)
        else:
            print("Creating the model...")
            return self.language_methods[self.language].create_model(*args, **kwargs)

    def create_fmu(self, *args, **kwargs):
        if self.terminal_animation:
            with helper_functions.Loader("Creating the FMU..."):
                return self.language_methods[self.language].create_fmu(*args, **kwargs)
        else:
            print("Creating the FMU...")
            return self.language_methods[self.language].create_fmu(*args, **kwargs)
    
if __name__ == "__main__":
    
    # JSON file path
    # json_file_path = '../data/input_specification_v2.json'
    json_file_path = '../data/input_specification_frontier_test.json'
    
    # Output Modelica file
    output_path = '../temp'

    # Path to ExaDigiT based project
    project_path = '../method/Modelica/ORNLSupercomputing'
    
    # Model dependecies
    dependencies = [r'C:/Users/fig/OneDrive - Oak Ridge National Laboratory/proposals/2024_02_FrontierSystemModelAutomation/Publications/2024_AmericaModelicaConference/FrontierTH/package.mo',
          		    r'../../modelica-buildings/Buildings/package.mo',
          		    r'../../TRANSFORM-Library/TRANSFORM/package.mo']
    
    # Example usage
    csm = AutoCSM(language='modelica', architecture='nested')
    csm.set_input_specification(json_file_path)
    csm.set_output_path(output_path)
    csm.create_architecture()
    
    csm.set_project_path(project_path)
    csm.create_model(uniform=[False,False])
    csm.create_fmu(dependencies)
    
    # auto_csm.set_language('julia')
    # auto_csm.read_input('input_file.txt', 'additional_arg1', param='value')
    # auto_csm.create_model('model_file.txt', option=True)
    # auto_csm.create_fmu('fmu_file.txt', debug=True)
+174 −0
Original line number Diff line number Diff line
# -*- coding: utf-8 -*-
"""
Created on Thu May 30 17:26:47 2024

@author: fig
"""
import json

def read_json(file_path):
    """
    Reads a JSON file from the specified file path and returns its contents as a dictionary.

    Parameters:
    file_path (str): The path to the JSON file.

    Returns:
    dict: The contents of the JSON file.
    """
    try:
        with open(file_path, 'r') as file:
            data = json.load(file)
        return data
    except FileNotFoundError:
        print(f"Error: The file {file_path} was not found.")
    except json.JSONDecodeError:
        print(f"Error: The file {file_path} is not a valid JSON file.")
    except Exception as e:
        print(f"An error occurred: {e}")


#%%
from itertools import cycle
from shutil import get_terminal_size
from threading import Thread
from time import sleep
class Loader:
    def __init__(self, desc="Loading...", end="Done!", timeout=0.1, steps='cycle'):
        """
        Source: https://stackoverflow.com/questions/22029562/python-how-to-make-simple-animated-loading-while-process-is-running
        A loader-like context manager

        Args:
            desc (str, optional): The loader's description. Defaults to "Loading...".
            end (str, optional): Final print. Defaults to "Done!".
            timeout (float, optional): Sleep time between prints. Defaults to 0.1.
        
        Example usage:
        with Loader("Loading with context manager..."):
            for i in range(10):
                sleep(0.25)

        loader = Loader("Loading with object...", "That was fast!", 0.05).start()
        for i in range(10):
            sleep(0.25)
        loader.stop()
        """
        self.desc = desc
        self.end = end
        self.timeout = timeout

        self._thread = Thread(target=self._animate, daemon=True)
        
        if steps == 'dots':
            self.steps = ["", "", "", "", "", "", "", ""]
        elif steps == 'cycle':
            self.steps = ['-', '/', '|', '\\']
        elif type(steps) == list:
            self.steps = steps
            
        self.done = False

    def start(self):
        self._thread.start()
        return self

    def _animate(self):
        for c in cycle(self.steps):
            if self.done:
                break
            print(f"\r{self.desc} {c}", flush=True, end="")
            sleep(self.timeout)

    def __enter__(self):
        self.start()

    def stop(self):
        self.done = True
        cols = get_terminal_size((80, 20)).columns
        print("\r" + " " * cols, end="", flush=True)
        print(f"\r{self.desc} {self.end}", flush=True)

    def __exit__(self, exc_type, exc_value, tb):
        # handle exceptions with those variables ^
        self.stop()
       
#%%
import time

class TicToc:
    '''
    # Example usage:
    tt = TicToc()
    tt.tic()
    time.sleep(2)  # Simulate a delay
    tt.toc()
    '''
    def __init__(self):
        self.start_time = None

    def tic(self):
        self.start_time = time.time()
        print("Tic...")

    def toc(self):
        if self.start_time is None:
            print("Toc: You need to call tic() first!")
        else:
            elapsed_time = time.time() - self.start_time
            print(f"Toc: {elapsed_time:.6f} seconds")
            self.start_time = None  # Reset start_time if you want to measure multiple intervals

if __name__ == "__main__":
    with Loader("Loading with context manager..."):
        for i in range(10):
            sleep(0.25)

    loader = Loader("Loading with object...", "That was fast!", 0.1, steps='cycle').start()
    for i in range(10):
        sleep(0.25)
    loader.stop()
    
#%%
import numpy as np

def create_new_array_with_renamed_fields(original_array, field_mapping, keep_original=None):
    # Extract the original dtype names and formats
    original_dtype = original_array.dtype
    original_fields = original_dtype.names
    
    # If keep_original is None, keep all original fields
    if keep_original is None:
        keep_original = original_fields
    
    # Create a new dtype list with the new field names
    new_dtype = []
    for field in original_fields:
        if field in keep_original:
            new_dtype.append((field, original_dtype[field]))
    
    # Add the new fields to the dtype list
    for old_field, new_field in field_mapping:
        new_dtype.append((new_field, original_dtype[old_field]))
    
    # Create the new array with the new dtype
    new_array = np.empty(original_array.shape, dtype=new_dtype)
    
    # Copy the data from the original fields to the new fields
    for field in original_fields:
        if field in keep_original:
            new_array[field] = original_array[field]
    
    for old_field, new_field in field_mapping:
        new_array[new_field] = original_array[old_field]
    
    return new_array

#%%
import re

def convert_numbers_to_bracket_form(name):
    # Use regex to find numbers surrounded by underscores and replace with "[number]."
    new_name = re.sub(r'_(\d+)_', r'[\1].', name)
    return new_name
 No newline at end of file
+0 −0

Empty file added.