code
stringlengths
1
5.19M
package
stringlengths
1
81
path
stringlengths
9
304
filename
stringlengths
4
145
import unittest from EEETools.MainModules.main_module import Block, Connection, ArrayHandler class BlockTestCases(unittest.TestCase): def testStr(self): array_handler = ArrayHandler() a = Block(1, array_handler) a.name = "prova" b = Block(2, array_handler) b.modify_ID(1) self.assertEqual(False, str(a) == str(b)) b.name = "prova" self.assertEqual(True, str(a) == str(b)) def testAdd(self): array_handler = ArrayHandler() a = Block(1, array_handler) conn1 = Connection(1) conn2 = Connection(2) a.add_connection(conn1, is_input=True) a.add_connection(conn2, is_input=False) b = Block(2, array_handler) b.add_connection(conn2, is_input=True) self.assertEqual(2, conn2.toID) b.modify_ID(3) self.assertEqual(3, conn2.toID) def testRemove(self): array_handler = ArrayHandler() a = Block(1, array_handler) conn1 = Connection(1) conn2 = Connection(2) a.add_connection(conn1, is_input=True) a.add_connection(conn2, is_input=False) b = Block(2, array_handler) b.add_connection(conn2, is_input=True) self.assertEqual(False, conn2.is_loss) b.remove_connection(conn2) self.assertEqual(-1, conn2.toID) self.assertEqual(True, conn2.is_loss) def testCheckCondition(self): class TestSubClass(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) def test_function(obj): try: obj.is_ready_for_calculation except: return False return True array_handler = ArrayHandler() a = Block(1, array_handler) b = TestSubClass(2, array_handler) self.assertTrue(test_function(a)) self.assertFalse(test_function(b)) def testListOrder(self): array_handler = ArrayHandler() block0 = Block(0, array_handler, is_support_block=True) block1 = Block(1, array_handler) block2 = Block(2, array_handler) block_list = list() block_list.append(block1) block_list.append(block0) block_list.append(block2) block_list.sort() print(block_list) self.assertTrue(block1 < block2) self.assertTrue(block0 > block2) self.assertTrue(block_list[-1] == block0) if __name__ == '__main__': unittest.main()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/test/test_block_class.py
test_block_class.py
from EEETools.Tools.GUIElements.connection_and_block_check import CheckConnectionWidget from EEETools.Tools.GUIElements.net_plot_modules import display_network from EEETools.Tools.API.ExcelAPI.modules_importer import import_excel_input from tkinter import filedialog import tkinter as tk import unittest class MyTestCase(unittest.TestCase): def test_block_connection(self): root = tk.Tk() root.withdraw() excel_path = filedialog.askopenfilename() array_handler = import_excel_input(excel_path) CheckConnectionWidget.launch(array_handler) self.assertEqual(True, True) def test_network(self): root = tk.Tk() root.withdraw() excel_path = filedialog.askopenfilename() array_handler = import_excel_input(excel_path) display_network(array_handler) self.assertEqual(True, True) def test_network_product_fuel(self): root = tk.Tk() root.withdraw() excel_path = filedialog.askopenfilename() array_handler = import_excel_input(excel_path) try: array_handler.calculate() except: pass display_network(array_handler.pf_diagram) self.assertEqual(True, True) if __name__ == '__main__': unittest.main()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/test/test_GUI.py
test_GUI.py
from EEETools.Tools.EESCodeGenerator.EES_creator_tool import DefineEESTextWidget from EEETools.Tools.EESCodeGenerator.EES_creator_tool import EESTextFilesManager from EEETools.Tools.EESCodeGenerator.EES_checker import Zones from EEETools.Tools.API.ExcelAPI.modules_importer import import_excel_input from PyQt5.QtWidgets import QApplication import sys, os, traceback, unittest from EEETools import costants def launch_app(widget): app = QApplication(sys.argv) pop_up = widget() pop_up.show() app.exec_() class InputEESTestCase(unittest.TestCase): def testRunMain(self): widget = DefineEESTextWidget launch_app(widget) self.assertTrue(True) def testRunManager(self): widget = EESTextFilesManager launch_app(widget) self.assertTrue(True) def testZoneCreator(self): zones_list = list() error_found = False resource_excel_path = os.path.join(costants.TEST_RES_DIR, "ImportTestResources", "ExcelTestFiles") i = 1 excel_path = os.path.join(resource_excel_path, "Sample Excel Input " + str(i) + ".xlsm") while os.path.isfile(excel_path): try: array_handler = import_excel_input(excel_path) zones_list.append(Zones(array_handler)) except: traceback.print_exc() error_found = True i += 1 excel_path = os.path.join(resource_excel_path, "Sample Excel Input " + str(i) + ".xlsm") self.assertFalse(error_found) if __name__ == '__main__': unittest.main()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/test/test_EES_generator_UI.py
test_EES_generator_UI.py
import unittest import tkinter as tk from tkinter import filedialog import EEETools.Tools.API.DatAPI.modules_importer from EEETools.Tools.API.ExcelAPI import modules_importer from EEETools.Tools.API.terminal_api import paste_default_excel_file class MyTestCase(unittest.TestCase): def test_excel_direct_calculation(self): root = tk.Tk() root.withdraw() excel_path = filedialog.askopenfilename() modules_importer.calculate_excel(excel_path) self.assertTrue(True) def test_dat_direct_calculation(self): root = tk.Tk() root.withdraw() excel_path = filedialog.askopenfilename() EEETools.Tools.API.DatAPI.modules_importer.calculate_dat(excel_path) self.assertTrue(True) def test_main_modules(self): paste_default_excel_file() self.assertTrue(True) def test_main_modules_calculation(self): import EEETools EEETools.calculate() self.assertTrue(True) if __name__ == '__main__': unittest.main()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/test/test_package.py
test_package.py
from EEETools.Tools.CostCorrelations.cost_correlation_gui import * from EEETools.Tools.CostCorrelations.CorrelationClasses.turton_correlation import * from PyQt5.QtWidgets import QApplication import unittest, sys def launch_app(widget): app = QApplication(sys.argv) pop_up = widget() pop_up.show() app.exec_() class CostCorrelationTestCase(unittest.TestCase): def test_correlation_handler(self): correlation_handler = CostCorrelationHandler() self.assertEqual(1, len(correlation_handler.list_modules())) def test_correlation_files_manager(self): widget = CostCorrelationFilesManager launch_app(widget) self.assertTrue(True) def test_header_widget(self): app = QApplication(sys.argv) correlation = TurtonCorrelation() main_class = TurtonEditCorrelationWidget(correlation) widget = TurtonHeaderWidget(main_class) widget.set_edit_layout = True widget.init_layout() widget.show() app.exec_() self.assertTrue(True) def test_parameter_widget(self): app = QApplication(sys.argv) correlation = TurtonCorrelation() base_class = BaseEditCorrelationWidget(correlation) widget = ParametersWidget(correlation.parameter_dict, base_class) widget.set_edit_layout = True widget.init_layout() widget.show() app.exec_() self.assertTrue(True) def test_coefficient_widget(self): app = QApplication(sys.argv) correlation = TurtonCorrelation() base_class = BaseEditCorrelationWidget(correlation) coeff_dict = correlation.coefficient_dict widget = CoefficientWidget(coeff_dict, base_class) widget.show() app.exec_() self.assertTrue(True) def test_list_view(self): app = QApplication(sys.argv) widget = QListView() correlation = TurtonCorrelation() model = QStandardItem for key in correlation.parameter_dict.keys(): widget.insertItem(key) widget.show() app.exec_() if __name__ == '__main__': unittest.main()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/test/test_cost_correlation.py
test_cost_correlation.py
from EEETools.Tools.API.DatAPI.modules_importer import import_dat from EEETools.Tools.API.ExcelAPI.modules_importer import * from EEETools import costants from tkinter import filedialog import tkinter as tk import unittest def import_matlab_result(excel_path): try: result_data = pandas.read_excel(excel_path, sheet_name="Eff Out").values return result_data[1, 6] except: return -100 class ImportTestCase(unittest.TestCase): def test_excel_import(self): array_handler_list = list() resource_excel_path = os.path.join(costants.TEST_RES_DIR, "ImportTestResources", "ExcelTestFiles") i = 1 excel_path = os.path.join(resource_excel_path, "Sample Excel Input " + str(i) + ".xlsm") while os.path.isfile(excel_path): array_handler = import_excel_input(excel_path) result = import_matlab_result(excel_path) if result != -100: array_handler.options.calculate_on_pf_diagram = False array_handler.calculate() print(array_handler) array_handler_list.append(array_handler) useful_effect = array_handler.useful_effect_connections[0] self.assertEqual(round(result, 6), round(useful_effect.rel_cost, 6)) i += 1 excel_path = os.path.join(resource_excel_path, "Sample Excel Input " + str(i) + ".xlsm") def test_excel_direct_calculation(self): root = tk.Tk() root.withdraw() excel_path = filedialog.askopenfilename() calculate_excel(excel_path) self.assertTrue(True) def test_dat_import_export(self): array_handler_list = list() resource_excel_path = os.path.join(costants.TEST_RES_DIR, "ImportTestResources", "ExcelTestFiles") resource_dat_path = os.path.join(costants.TEST_RES_DIR, "ImportTestResources", "DatTestFiles") i = 1 excel_path = os.path.join(resource_excel_path, "Sample Excel Input " + str(i) + ".xlsm") while os.path.isfile(excel_path): array_handler = import_excel_input(excel_path) array_handler.calculate() result_excel = array_handler.useful_effect_connections dat_path = os.path.join(resource_dat_path, "Sample Dat " + str(i) + ".dat") export_dat(dat_path, array_handler) array_handler_dat = import_dat(dat_path) array_handler_dat.options.calculate_on_pf_diagram = False array_handler_list.append(array_handler_dat) array_handler_dat.calculate() result_dat = array_handler_dat.useful_effect_connections difference = 0 sum_exergy = 0 for result in result_dat: difference += result.rel_cost*result.exergy_value sum_exergy += result.rel_cost*result.exergy_value for result in result_excel: difference -= result.rel_cost * result.exergy_value sum_exergy += result.rel_cost * result.exergy_value err = 2*difference/sum_exergy self.assertEqual(round(err, 7), 0) i += 1 excel_path = os.path.join(resource_excel_path, "Sample Excel Input " + str(i) + ".xlsm") def test_download_link(self): from EEETools.Tools.Other.fernet_handler import FernetHandler FernetHandler() self.assertTrue(True) def test_excel_calculate(self): import EEETools EEETools.calculate( calculate_on_pf_diagram=True, condenser_is_dissipative=True, loss_cost_is_zero=True, ) self.assertTrue(True) def test_excel_debug(self): import EEETools EEETools.export_debug_information(calculate_on_pf_diagram=True) self.assertTrue(True) def test_excel_update(self): resource_excel_path = os.path.join(costants.TEST_RES_DIR, "ImportTestResources", "ExcelTestFiles") excel_path = os.path.join(resource_excel_path, "BHE_simple_analysis.xlsx") updated_exergy_values = [ {"index": 1, "value": 82.86}, {"index": 2, "value": 87.76}, {"index": 3, "value": 91.91}, {"index": 4, "value": 86.54}, {"index": 20, "value": 0.5 * 9.81}, {"index": 21, "value": (343.63 - 343.63) * (1 - 292.15 / 325.15)}, {"index": 22, "value": 3.68} ] connection = updated_exergy_values[0] array_handler = calculate_excel(excel_path, new_exergy_list=updated_exergy_values, export_solution=False) self.assertEqual(connection["value"], array_handler.find_connection_by_index(connection["index"]).exergy_value) def test_sankey(self): import EEETools EEETools.plot_sankey(generate_on_pf_diagram=True, display_costs=False) self.assertTrue(True) def test_connection_check(self): import EEETools EEETools.launch_connection_debug() self.assertTrue(True) if __name__ == '__main__': unittest.main()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/test/test_import_module.py
test_import_module.py
import unittest from EEETools.MainModules.main_module import ArrayHandler, Connection def generate_test_array_handler(): array_handler = ArrayHandler() array_handler.append_block("Generic") array_handler.append_block("Generic") array_handler.append_block("Generic") array_handler.append_block("Generic") new_connection = array_handler.append_connection(to_block=array_handler.block_list[0]) new_connection.exergy_value = 400.0 new_connection.set_cost(10.0) new_connection = array_handler.append_connection(to_block=array_handler.block_list[2]) new_connection.exergy_value = 700.0 new_connection.set_cost(7.5) new_connection = array_handler.append_connection(from_block=0, to_block=1) new_connection.exergy_value = 300. new_connection = array_handler.append_connection(from_block=2, to_block=1) new_connection.exergy_value = 300. new_connection = array_handler.append_connection(from_block=1) new_connection.exergy_value = 100. new_connection = array_handler.append_connection(from_block=1, to_block=3) new_connection.exergy_value = 200. new_connection = array_handler.append_connection(from_block=3) new_connection.exergy_value = 150. new_connection.is_useful_effect = True return array_handler class MyTestCase(unittest.TestCase): def testDynamicImport(self): def import_and_check_name(name, block_arr): block_arr.append_block(name) return name == type(block_arr.block_list[-1]).__name__ array_handler = ArrayHandler() self.assertTrue(import_and_check_name("Expander", array_handler)) self.assertFalse(import_and_check_name("NotABlock", array_handler)) print(array_handler) def testCalculation(self): array_handler = generate_test_array_handler() print(array_handler) array_handler.calculate() self.assertAlmostEqual(61.667, array_handler.block_list[-1].output_connections[0].rel_cost, delta=2) if __name__ == '__main__': unittest.main()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/test/test_array_handler.py
test_array_handler.py
import os import unittest from EEETools.Tools.modules_handler import ModulesHandler class ModulesHandlerTestCase(unittest.TestCase): def testInitializeList(self): modules_handler = ModulesHandler() print(modules_handler.name_list) #If there were no errors the test succedeed self.assertTrue(True) def testConvertName(self): modules_handler = ModulesHandler() for filename in os.listdir(modules_handler.data_folder): index = modules_handler.get_name_index(filename) self.assertNotEqual(-1, index) std_name = modules_handler.name_list[index] module_name = modules_handler.get_module_name(std_name) self.assertEqual(filename, module_name) if __name__ == '__main__': unittest.main()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/test/test_modules_handler.py
test_modules_handler.py
import os # RUN MODE RUN_MODE = "administrator" # RUN_MODE = "standard" # ROOT DIRECTORIES ROOT_DIR = os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir))) RES_DIR = os.path.join(ROOT_DIR, "3ETool_res") TEST_RES_DIR = os.path.join(RES_DIR, "testResources") GOOGLE_DRIVE_RES_IDs = { "0.3.12": "1Exf-G2vXhPbSPKM2i5xhYNsCYNS4WsP5", "0.3.0": "11Yyl88YGVCEfeQKDryl4buHmq6Ejla36", "0.2.5": "1gn2RFJQcw-iSkINS1O8gINDYE75-S_vM" } # EES FORMAT STYLES STYLES = { "error": { "color": "#ff4d00", "font-weight": "bold", "font-style": "normal", "text-decoration": "none" }, "comments": {"color": "#8C8C8C", "font-weight": "bold", "font-style": "italic", "text-decoration": "none"}, "variable": {"color": "#0033B3", "font-weight": "bold", "font-style": "normal", "text-decoration": "none"}, "repeated_keyword": {"color": "#008080", "font-weight": "bold", "font-style": "normal", "text-decoration": "none"}, "known_keyword": {"color": "#008080", "font-weight": "bold", "font-style": "normal", "text-decoration": "none"}, "unknown_function": {"color": "#94558D", "font-weight": "bold", "font-style": "italic", "text-decoration": "underline"}, "known_function": {"color": "#94558D", "font-weight": "bold", "font-style": "normal", "text-decoration": "none"}, "default": {"color": "#000000", "font-weight": "bold", "font-style": "normal", "text-decoration": "none"} } EES_CODE_FONT_FAMILY = "Courier New" def get_html_string(key, text): if not key in STYLES.keys(): key = "default" style = STYLES[key] __html_text = '<span style="' __html_text += "color:" + style["color"] + "; " __html_text += "font-weight:" + style["font-weight"] + '; ' __html_text += "font-style:" + style["font-style"] + '; ' __html_text += "text-decoration:" + style["text-decoration"] + '"' __html_text += '>' + text + '</span>' return __html_text # ZONE TYPES ZONE_TYPE_FLUID = "fluid" ZONE_TYPE_FLOW_RATE = "flow rate" ZONE_TYPE_PRESSURE = "pressure" ZONE_TYPE_ENERGY = "energy" ZONES = [ZONE_TYPE_ENERGY, ZONE_TYPE_PRESSURE, ZONE_TYPE_FLUID, ZONE_TYPE_FLOW_RATE]
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/costants.py
costants.py
VERSION = "0.8.3"
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/version.py
version.py
import inspect called_from_setup = False for frame in inspect.stack(): if "setup.py" in frame.filename: called_from_setup = True break if not called_from_setup: from EEETools.Tools.API.terminal_api import ( paste_default_excel_file, paste_components_documentation, paste_user_manual ) from EEETools.Tools.API.terminal_api import ( calculate, launch_connection_debug, launch_network_display, plot_sankey, export_debug_information ) else: try: from EEETools.Tools.Other.resource_downloader import update_resource_folder update_resource_folder(force_update=True) except: pass
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/__init__.py
__init__.py
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.11.2) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\x06\x00\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x69\x73\x6f\ \x2d\x38\x38\x35\x39\x2d\x31\x22\x3f\x3e\x0d\x0a\x3c\x21\x2d\x2d\ \x20\x47\x65\x6e\x65\x72\x61\x74\x6f\x72\x3a\x20\x41\x64\x6f\x62\ \x65\x20\x49\x6c\x6c\x75\x73\x74\x72\x61\x74\x6f\x72\x20\x31\x39\ \x2e\x30\x2e\x30\x2c\x20\x53\x56\x47\x20\x45\x78\x70\x6f\x72\x74\ \x20\x50\x6c\x75\x67\x2d\x49\x6e\x20\x2e\x20\x53\x56\x47\x20\x56\ \x65\x72\x73\x69\x6f\x6e\x3a\x20\x36\x2e\x30\x30\x20\x42\x75\x69\ \x6c\x64\x20\x30\x29\x20\x20\x2d\x2d\x3e\x0d\x0a\x3c\x73\x76\x67\ \x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\x31\x22\x20\x69\ \x64\x3d\x22\x43\x61\x70\x61\x5f\x31\x22\x20\x78\x6d\x6c\x6e\x73\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\ \x6f\x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x20\x78\x6d\ \x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\ \x39\x2f\x78\x6c\x69\x6e\x6b\x22\x20\x78\x3d\x22\x30\x70\x78\x22\ \x20\x79\x3d\x22\x30\x70\x78\x22\x0d\x0a\x09\x20\x76\x69\x65\x77\ \x42\x6f\x78\x3d\x22\x30\x20\x30\x20\x32\x37\x35\x2e\x38\x33\x36\ \x20\x32\x37\x35\x2e\x38\x33\x36\x22\x20\x73\x74\x79\x6c\x65\x3d\ \x22\x65\x6e\x61\x62\x6c\x65\x2d\x62\x61\x63\x6b\x67\x72\x6f\x75\ \x6e\x64\x3a\x6e\x65\x77\x20\x30\x20\x30\x20\x32\x37\x35\x2e\x38\ \x33\x36\x20\x32\x37\x35\x2e\x38\x33\x36\x3b\x22\x20\x78\x6d\x6c\ \x3a\x73\x70\x61\x63\x65\x3d\x22\x70\x72\x65\x73\x65\x72\x76\x65\ \x22\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\ \x64\x3d\x22\x4d\x31\x39\x31\x2e\x33\x34\x34\x2c\x32\x30\x2e\x39\ \x32\x32\x6c\x2d\x39\x35\x2e\x31\x35\x35\x2c\x39\x35\x2e\x31\x35\ \x35\x63\x2d\x30\x2e\x37\x35\x36\x2c\x30\x2e\x37\x35\x36\x2d\x31\ \x2e\x32\x39\x37\x2c\x31\x2e\x36\x39\x39\x2d\x31\x2e\x35\x36\x35\ \x2c\x32\x2e\x37\x33\x34\x6c\x2d\x38\x2e\x31\x36\x37\x2c\x33\x31\ \x2e\x34\x35\x34\x63\x2d\x30\x2e\x35\x33\x34\x2c\x32\x2e\x30\x35\ \x39\x2c\x30\x2e\x30\x36\x31\x2c\x34\x2e\x32\x34\x36\x2c\x31\x2e\ \x35\x36\x35\x2c\x35\x2e\x37\x35\x31\x0d\x0a\x09\x09\x63\x31\x2e\ \x31\x34\x2c\x31\x2e\x31\x33\x39\x2c\x32\x2e\x36\x37\x31\x2c\x31\ \x2e\x37\x35\x37\x2c\x34\x2e\x32\x34\x32\x2c\x31\x2e\x37\x35\x37\ \x63\x30\x2e\x35\x30\x33\x2c\x30\x2c\x31\x2e\x30\x30\x39\x2d\x30\ \x2e\x30\x36\x33\x2c\x31\x2e\x35\x30\x38\x2d\x30\x2e\x31\x39\x32\ \x6c\x33\x31\x2e\x34\x35\x34\x2d\x38\x2e\x31\x36\x38\x63\x31\x2e\ \x30\x33\x35\x2d\x30\x2e\x32\x36\x39\x2c\x31\x2e\x39\x37\x39\x2d\ \x30\x2e\x38\x31\x2c\x32\x2e\x37\x33\x34\x2d\x31\x2e\x35\x36\x35\ \x0d\x0a\x09\x09\x6c\x39\x35\x2e\x31\x35\x33\x2d\x39\x35\x2e\x31\ \x35\x33\x63\x30\x2e\x30\x30\x32\x2d\x30\x2e\x30\x30\x32\x2c\x30\ \x2e\x30\x30\x34\x2d\x30\x2e\x30\x30\x33\x2c\x30\x2e\x30\x30\x35\ \x2d\x30\x2e\x30\x30\x34\x73\x30\x2e\x30\x30\x33\x2d\x30\x2e\x30\ \x30\x34\x2c\x30\x2e\x30\x30\x34\x2d\x30\x2e\x30\x30\x35\x6c\x31\ \x39\x2e\x31\x35\x36\x2d\x31\x39\x2e\x31\x35\x36\x63\x32\x2e\x33\ \x34\x34\x2d\x32\x2e\x33\x34\x33\x2c\x32\x2e\x33\x34\x34\x2d\x36\ \x2e\x31\x34\x32\x2c\x30\x2e\x30\x30\x31\x2d\x38\x2e\x34\x38\x34\ \x0d\x0a\x09\x09\x4c\x32\x31\x38\x2e\x39\x39\x34\x2c\x31\x2e\x37\ \x35\x38\x43\x32\x31\x37\x2e\x38\x36\x38\x2c\x30\x2e\x36\x33\x32\ \x2c\x32\x31\x36\x2e\x33\x34\x33\x2c\x30\x2c\x32\x31\x34\x2e\x37\ \x35\x31\x2c\x30\x63\x2d\x31\x2e\x35\x39\x31\x2c\x30\x2d\x33\x2e\ \x31\x31\x37\x2c\x30\x2e\x36\x33\x32\x2d\x34\x2e\x32\x34\x32\x2c\ \x31\x2e\x37\x35\x38\x6c\x2d\x31\x39\x2e\x31\x35\x35\x2c\x31\x39\ \x2e\x31\x35\x35\x0d\x0a\x09\x09\x63\x2d\x30\x2e\x30\x30\x32\x2c\ \x30\x2e\x30\x30\x32\x2d\x30\x2e\x30\x30\x34\x2c\x30\x2e\x30\x30\ \x33\x2d\x30\x2e\x30\x30\x35\x2c\x30\x2e\x30\x30\x34\x53\x31\x39\ \x31\x2e\x33\x34\x36\x2c\x32\x30\x2e\x39\x32\x31\x2c\x31\x39\x31\ \x2e\x33\x34\x34\x2c\x32\x30\x2e\x39\x32\x32\x7a\x20\x4d\x31\x32\ \x30\x2e\x36\x33\x31\x2c\x31\x33\x38\x2e\x32\x30\x38\x6c\x2d\x31\ \x39\x2e\x39\x39\x33\x2c\x35\x2e\x31\x39\x32\x6c\x35\x2e\x31\x39\ \x31\x2d\x31\x39\x2e\x39\x39\x33\x6c\x38\x39\x2e\x37\x36\x32\x2d\ \x38\x39\x2e\x37\x36\x32\x0d\x0a\x09\x09\x6c\x31\x34\x2e\x38\x30\ \x31\x2c\x31\x34\x2e\x38\x30\x32\x4c\x31\x32\x30\x2e\x36\x33\x31\ \x2c\x31\x33\x38\x2e\x32\x30\x38\x7a\x20\x4d\x32\x31\x34\x2e\x37\ \x35\x31\x2c\x31\x34\x2e\x34\x38\x35\x6c\x31\x34\x2e\x38\x30\x31\ \x2c\x31\x34\x2e\x38\x30\x32\x6c\x2d\x31\x30\x2e\x36\x37\x35\x2c\ \x31\x30\x2e\x36\x37\x35\x4c\x32\x30\x34\x2e\x30\x37\x36\x2c\x32\ \x35\x2e\x31\x36\x4c\x32\x31\x34\x2e\x37\x35\x31\x2c\x31\x34\x2e\ \x34\x38\x35\x7a\x22\x2f\x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\ \x64\x3d\x22\x4d\x32\x33\x38\x2e\x30\x33\x37\x2c\x36\x35\x2e\x30\ \x32\x32\x63\x2d\x33\x2e\x33\x31\x33\x2c\x30\x2d\x36\x2c\x32\x2e\ \x36\x38\x37\x2d\x36\x2c\x36\x76\x31\x39\x32\x2e\x38\x31\x33\x48\ \x34\x33\x2e\x37\x39\x39\x56\x33\x34\x2e\x34\x31\x37\x68\x31\x31\ \x31\x2e\x30\x36\x33\x63\x33\x2e\x33\x31\x33\x2c\x30\x2c\x36\x2d\ \x32\x2e\x36\x38\x37\x2c\x36\x2d\x36\x73\x2d\x32\x2e\x36\x38\x37\ \x2d\x36\x2d\x36\x2d\x36\x48\x33\x37\x2e\x37\x39\x39\x0d\x0a\x09\ \x09\x63\x2d\x33\x2e\x33\x31\x33\x2c\x30\x2d\x36\x2c\x32\x2e\x36\ \x38\x37\x2d\x36\x2c\x36\x76\x32\x34\x31\x2e\x34\x31\x39\x63\x30\ \x2c\x33\x2e\x33\x31\x33\x2c\x32\x2e\x36\x38\x37\x2c\x36\x2c\x36\ \x2c\x36\x68\x32\x30\x30\x2e\x32\x33\x38\x63\x33\x2e\x33\x31\x33\ \x2c\x30\x2c\x36\x2d\x32\x2e\x36\x38\x37\x2c\x36\x2d\x36\x56\x37\ \x31\x2e\x30\x32\x32\x0d\x0a\x09\x09\x43\x32\x34\x34\x2e\x30\x33\ \x37\x2c\x36\x37\x2e\x37\x30\x39\x2c\x32\x34\x31\x2e\x33\x35\x31\ \x2c\x36\x35\x2e\x30\x32\x32\x2c\x32\x33\x38\x2e\x30\x33\x37\x2c\ \x36\x35\x2e\x30\x32\x32\x7a\x22\x2f\x3e\x0d\x0a\x3c\x2f\x67\x3e\ \x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\ \x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\ \x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\ \x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\ \x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\ \x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\ \x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\ \x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\ \x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\ \x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\ \x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x2f\x73\x76\x67\x3e\x0d\x0a\ \x00\x00\x05\xeb\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x69\x73\x6f\ \x2d\x38\x38\x35\x39\x2d\x31\x22\x3f\x3e\x0d\x0a\x3c\x21\x2d\x2d\ \x20\x47\x65\x6e\x65\x72\x61\x74\x6f\x72\x3a\x20\x41\x64\x6f\x62\ \x65\x20\x49\x6c\x6c\x75\x73\x74\x72\x61\x74\x6f\x72\x20\x31\x39\ \x2e\x30\x2e\x30\x2c\x20\x53\x56\x47\x20\x45\x78\x70\x6f\x72\x74\ \x20\x50\x6c\x75\x67\x2d\x49\x6e\x20\x2e\x20\x53\x56\x47\x20\x56\ \x65\x72\x73\x69\x6f\x6e\x3a\x20\x36\x2e\x30\x30\x20\x42\x75\x69\ \x6c\x64\x20\x30\x29\x20\x20\x2d\x2d\x3e\x0d\x0a\x3c\x73\x76\x67\ \x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\x31\x22\x20\x69\ \x64\x3d\x22\x43\x61\x70\x61\x5f\x31\x22\x20\x78\x6d\x6c\x6e\x73\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\ \x6f\x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x20\x78\x6d\ \x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\ \x39\x2f\x78\x6c\x69\x6e\x6b\x22\x20\x78\x3d\x22\x30\x70\x78\x22\ \x20\x79\x3d\x22\x30\x70\x78\x22\x0d\x0a\x09\x20\x76\x69\x65\x77\ \x42\x6f\x78\x3d\x22\x30\x20\x30\x20\x32\x39\x34\x2e\x38\x34\x33\ \x20\x32\x39\x34\x2e\x38\x34\x33\x22\x20\x73\x74\x79\x6c\x65\x3d\ \x22\x65\x6e\x61\x62\x6c\x65\x2d\x62\x61\x63\x6b\x67\x72\x6f\x75\ \x6e\x64\x3a\x6e\x65\x77\x20\x30\x20\x30\x20\x32\x39\x34\x2e\x38\ \x34\x33\x20\x32\x39\x34\x2e\x38\x34\x33\x3b\x22\x20\x78\x6d\x6c\ \x3a\x73\x70\x61\x63\x65\x3d\x22\x70\x72\x65\x73\x65\x72\x76\x65\ \x22\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\ \x64\x3d\x22\x4d\x36\x2c\x34\x30\x2e\x37\x37\x63\x33\x2e\x33\x31\ \x33\x2c\x30\x2c\x36\x2d\x32\x2e\x36\x38\x36\x2c\x36\x2d\x36\x63\ \x30\x2d\x39\x2e\x32\x35\x36\x2c\x37\x2e\x35\x33\x2d\x31\x36\x2e\ \x37\x38\x36\x2c\x31\x36\x2e\x37\x38\x36\x2d\x31\x36\x2e\x37\x38\ \x36\x68\x35\x33\x2e\x36\x37\x35\x6c\x34\x32\x2e\x32\x34\x33\x2c\ \x34\x36\x2e\x31\x34\x37\x0d\x0a\x09\x09\x63\x31\x2e\x31\x33\x37\ \x2c\x31\x2e\x32\x34\x32\x2c\x32\x2e\x37\x34\x33\x2c\x31\x2e\x39\ \x34\x39\x2c\x34\x2e\x34\x32\x36\x2c\x31\x2e\x39\x34\x39\x68\x31\ \x33\x36\x2e\x39\x32\x38\x63\x39\x2e\x32\x35\x36\x2c\x30\x2c\x31\ \x36\x2e\x37\x38\x36\x2c\x37\x2e\x35\x33\x2c\x31\x36\x2e\x37\x38\ \x36\x2c\x31\x36\x2e\x37\x38\x36\x63\x30\x2c\x33\x2e\x33\x31\x34\ \x2c\x32\x2e\x36\x38\x37\x2c\x36\x2c\x36\x2c\x36\x73\x36\x2d\x32\ \x2e\x36\x38\x36\x2c\x36\x2d\x36\x0d\x0a\x09\x09\x63\x30\x2d\x31\ \x35\x2e\x38\x37\x33\x2d\x31\x32\x2e\x39\x31\x33\x2d\x32\x38\x2e\ \x37\x38\x36\x2d\x32\x38\x2e\x37\x38\x36\x2d\x32\x38\x2e\x37\x38\ \x36\x48\x31\x33\x31\x2e\x37\x37\x31\x4c\x38\x39\x2e\x35\x32\x39\ \x2c\x37\x2e\x39\x33\x33\x63\x2d\x31\x2e\x31\x33\x37\x2d\x31\x2e\ \x32\x34\x32\x2d\x32\x2e\x37\x34\x33\x2d\x31\x2e\x39\x34\x39\x2d\ \x34\x2e\x34\x32\x36\x2d\x31\x2e\x39\x34\x39\x48\x32\x38\x2e\x37\ \x38\x36\x0d\x0a\x09\x09\x43\x31\x32\x2e\x39\x31\x33\x2c\x35\x2e\ \x39\x38\x34\x2c\x30\x2c\x31\x38\x2e\x38\x39\x37\x2c\x30\x2c\x33\ \x34\x2e\x37\x37\x43\x30\x2c\x33\x38\x2e\x30\x38\x33\x2c\x32\x2e\ \x36\x38\x37\x2c\x34\x30\x2e\x37\x37\x2c\x36\x2c\x34\x30\x2e\x37\ \x37\x7a\x22\x2f\x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\x64\x3d\ \x22\x4d\x32\x36\x36\x2e\x30\x35\x37\x2c\x39\x34\x2e\x31\x30\x34\ \x48\x31\x33\x31\x2e\x37\x37\x31\x4c\x38\x39\x2e\x35\x32\x39\x2c\ \x34\x37\x2e\x39\x35\x37\x63\x2d\x31\x2e\x31\x33\x37\x2d\x31\x2e\ \x32\x34\x32\x2d\x32\x2e\x37\x34\x33\x2d\x31\x2e\x39\x34\x39\x2d\ \x34\x2e\x34\x32\x36\x2d\x31\x2e\x39\x34\x39\x48\x32\x38\x2e\x37\ \x38\x36\x43\x31\x32\x2e\x39\x31\x33\x2c\x34\x36\x2e\x30\x30\x38\ \x2c\x30\x2c\x35\x38\x2e\x39\x32\x31\x2c\x30\x2c\x37\x34\x2e\x37\ \x39\x33\x0d\x0a\x09\x09\x76\x31\x31\x38\x2e\x36\x32\x38\x63\x30\ \x2c\x33\x2e\x33\x31\x33\x2c\x32\x2e\x36\x38\x37\x2c\x36\x2c\x36\ \x2c\x36\x73\x36\x2d\x32\x2e\x36\x38\x37\x2c\x36\x2d\x36\x56\x37\ \x34\x2e\x37\x39\x33\x63\x30\x2d\x39\x2e\x32\x35\x36\x2c\x37\x2e\ \x35\x33\x2d\x31\x36\x2e\x37\x38\x36\x2c\x31\x36\x2e\x37\x38\x36\ \x2d\x31\x36\x2e\x37\x38\x36\x68\x35\x33\x2e\x36\x37\x35\x6c\x34\ \x32\x2e\x32\x34\x33\x2c\x34\x36\x2e\x31\x34\x37\x0d\x0a\x09\x09\ \x63\x31\x2e\x31\x33\x37\x2c\x31\x2e\x32\x34\x32\x2c\x32\x2e\x37\ \x34\x33\x2c\x31\x2e\x39\x34\x39\x2c\x34\x2e\x34\x32\x36\x2c\x31\ \x2e\x39\x34\x39\x68\x31\x33\x36\x2e\x39\x32\x38\x63\x39\x2e\x32\ \x35\x36\x2c\x30\x2c\x31\x36\x2e\x37\x38\x36\x2c\x37\x2e\x35\x33\ \x2c\x31\x36\x2e\x37\x38\x36\x2c\x31\x36\x2e\x37\x38\x36\x76\x31\ \x33\x37\x2e\x31\x38\x34\x63\x30\x2c\x39\x2e\x32\x35\x35\x2d\x37\ \x2e\x35\x33\x2c\x31\x36\x2e\x37\x38\x36\x2d\x31\x36\x2e\x37\x38\ \x36\x2c\x31\x36\x2e\x37\x38\x36\x0d\x0a\x09\x09\x48\x32\x38\x2e\ \x37\x38\x36\x63\x2d\x39\x2e\x32\x35\x36\x2c\x30\x2d\x31\x36\x2e\ \x37\x38\x36\x2d\x37\x2e\x35\x33\x2d\x31\x36\x2e\x37\x38\x36\x2d\ \x31\x36\x2e\x37\x38\x36\x63\x30\x2d\x33\x2e\x33\x31\x33\x2d\x32\ \x2e\x36\x38\x37\x2d\x36\x2d\x36\x2d\x36\x73\x2d\x36\x2c\x32\x2e\ \x36\x38\x37\x2d\x36\x2c\x36\x63\x30\x2c\x31\x35\x2e\x38\x37\x33\ \x2c\x31\x32\x2e\x39\x31\x33\x2c\x32\x38\x2e\x37\x38\x36\x2c\x32\ \x38\x2e\x37\x38\x36\x2c\x32\x38\x2e\x37\x38\x36\x68\x32\x33\x37\ \x2e\x32\x37\x31\x0d\x0a\x09\x09\x63\x31\x35\x2e\x38\x37\x33\x2c\ \x30\x2c\x32\x38\x2e\x37\x38\x36\x2d\x31\x32\x2e\x39\x31\x33\x2c\ \x32\x38\x2e\x37\x38\x36\x2d\x32\x38\x2e\x37\x38\x36\x56\x31\x32\ \x32\x2e\x38\x39\x43\x32\x39\x34\x2e\x38\x34\x33\x2c\x31\x30\x37\ \x2e\x30\x31\x37\x2c\x32\x38\x31\x2e\x39\x33\x2c\x39\x34\x2e\x31\ \x30\x34\x2c\x32\x36\x36\x2e\x30\x35\x37\x2c\x39\x34\x2e\x31\x30\ \x34\x7a\x22\x2f\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\ \x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\ \x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\ \x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\ \x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\ \x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\ \x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\ \x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\ \x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\ \x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\ \x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\ \x0d\x0a\x3c\x2f\x73\x76\x67\x3e\x0d\x0a\ \x00\x00\x03\xd9\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x69\x73\x6f\ \x2d\x38\x38\x35\x39\x2d\x31\x22\x3f\x3e\x0d\x0a\x3c\x21\x2d\x2d\ \x20\x47\x65\x6e\x65\x72\x61\x74\x6f\x72\x3a\x20\x41\x64\x6f\x62\ \x65\x20\x49\x6c\x6c\x75\x73\x74\x72\x61\x74\x6f\x72\x20\x31\x39\ \x2e\x30\x2e\x30\x2c\x20\x53\x56\x47\x20\x45\x78\x70\x6f\x72\x74\ \x20\x50\x6c\x75\x67\x2d\x49\x6e\x20\x2e\x20\x53\x56\x47\x20\x56\ \x65\x72\x73\x69\x6f\x6e\x3a\x20\x36\x2e\x30\x30\x20\x42\x75\x69\ \x6c\x64\x20\x30\x29\x20\x20\x2d\x2d\x3e\x0d\x0a\x3c\x73\x76\x67\ \x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\x31\x22\x20\x69\ \x64\x3d\x22\x43\x61\x70\x61\x5f\x31\x22\x20\x78\x6d\x6c\x6e\x73\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\ \x6f\x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x20\x78\x6d\ \x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\ \x39\x2f\x78\x6c\x69\x6e\x6b\x22\x20\x78\x3d\x22\x30\x70\x78\x22\ \x20\x79\x3d\x22\x30\x70\x78\x22\x0d\x0a\x09\x20\x76\x69\x65\x77\ \x42\x6f\x78\x3d\x22\x30\x20\x30\x20\x32\x39\x34\x2e\x38\x33\x34\ \x20\x32\x39\x34\x2e\x38\x33\x34\x22\x20\x73\x74\x79\x6c\x65\x3d\ \x22\x65\x6e\x61\x62\x6c\x65\x2d\x62\x61\x63\x6b\x67\x72\x6f\x75\ \x6e\x64\x3a\x6e\x65\x77\x20\x30\x20\x30\x20\x32\x39\x34\x2e\x38\ \x33\x34\x20\x32\x39\x34\x2e\x38\x33\x34\x3b\x22\x20\x78\x6d\x6c\ \x3a\x73\x70\x61\x63\x65\x3d\x22\x70\x72\x65\x73\x65\x72\x76\x65\ \x22\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\ \x64\x3d\x22\x4d\x32\x38\x38\x2e\x38\x33\x34\x2c\x30\x48\x34\x37\ \x2e\x34\x31\x33\x63\x2d\x33\x2e\x33\x31\x33\x2c\x30\x2d\x36\x2c\ \x32\x2e\x36\x38\x37\x2d\x36\x2c\x36\x76\x31\x37\x2e\x33\x39\x38\ \x63\x30\x2c\x33\x2e\x33\x31\x33\x2c\x32\x2e\x36\x38\x37\x2c\x36\ \x2c\x36\x2c\x36\x73\x36\x2d\x32\x2e\x36\x38\x37\x2c\x36\x2d\x36\ \x56\x31\x32\x68\x32\x32\x39\x2e\x34\x32\x31\x76\x32\x32\x39\x2e\ \x34\x32\x31\x68\x2d\x31\x31\x2e\x33\x39\x38\x0d\x0a\x09\x09\x63\ \x2d\x33\x2e\x33\x31\x33\x2c\x30\x2d\x36\x2c\x32\x2e\x36\x38\x37\ \x2d\x36\x2c\x36\x73\x32\x2e\x36\x38\x37\x2c\x36\x2c\x36\x2c\x36\ \x68\x31\x37\x2e\x33\x39\x38\x63\x33\x2e\x33\x31\x33\x2c\x30\x2c\ \x36\x2d\x32\x2e\x36\x38\x37\x2c\x36\x2d\x36\x56\x36\x43\x32\x39\ \x34\x2e\x38\x33\x34\x2c\x32\x2e\x36\x38\x37\x2c\x32\x39\x32\x2e\ \x31\x34\x37\x2c\x30\x2c\x32\x38\x38\x2e\x38\x33\x34\x2c\x30\x7a\ \x22\x2f\x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\x64\x3d\x22\x4d\ \x32\x34\x37\x2e\x34\x32\x31\x2c\x34\x31\x2e\x34\x31\x33\x48\x36\ \x63\x2d\x33\x2e\x33\x31\x33\x2c\x30\x2d\x36\x2c\x32\x2e\x36\x38\ \x37\x2d\x36\x2c\x36\x76\x32\x34\x31\x2e\x34\x32\x31\x63\x30\x2c\ \x33\x2e\x33\x31\x33\x2c\x32\x2e\x36\x38\x37\x2c\x36\x2c\x36\x2c\ \x36\x68\x32\x34\x31\x2e\x34\x32\x31\x63\x33\x2e\x33\x31\x33\x2c\ \x30\x2c\x36\x2d\x32\x2e\x36\x38\x37\x2c\x36\x2d\x36\x56\x34\x37\ \x2e\x34\x31\x33\x0d\x0a\x09\x09\x43\x32\x35\x33\x2e\x34\x32\x31\ \x2c\x34\x34\x2e\x31\x2c\x32\x35\x30\x2e\x37\x33\x34\x2c\x34\x31\ \x2e\x34\x31\x33\x2c\x32\x34\x37\x2e\x34\x32\x31\x2c\x34\x31\x2e\ \x34\x31\x33\x7a\x20\x4d\x32\x34\x31\x2e\x34\x32\x31\x2c\x32\x38\ \x32\x2e\x38\x33\x34\x48\x31\x32\x56\x35\x33\x2e\x34\x31\x33\x68\ \x32\x32\x39\x2e\x34\x32\x31\x56\x32\x38\x32\x2e\x38\x33\x34\x7a\ \x22\x2f\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\ \x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\ \x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\ \x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\ \x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\ \x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\ \x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\ \x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\ \x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\ \x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\ \x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\ \x3c\x2f\x73\x76\x67\x3e\x0d\x0a\ \x00\x00\x05\xdd\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x69\x73\x6f\ \x2d\x38\x38\x35\x39\x2d\x31\x22\x3f\x3e\x0d\x0a\x3c\x21\x2d\x2d\ \x20\x47\x65\x6e\x65\x72\x61\x74\x6f\x72\x3a\x20\x41\x64\x6f\x62\ \x65\x20\x49\x6c\x6c\x75\x73\x74\x72\x61\x74\x6f\x72\x20\x31\x39\ \x2e\x30\x2e\x30\x2c\x20\x53\x56\x47\x20\x45\x78\x70\x6f\x72\x74\ \x20\x50\x6c\x75\x67\x2d\x49\x6e\x20\x2e\x20\x53\x56\x47\x20\x56\ \x65\x72\x73\x69\x6f\x6e\x3a\x20\x36\x2e\x30\x30\x20\x42\x75\x69\ \x6c\x64\x20\x30\x29\x20\x20\x2d\x2d\x3e\x0d\x0a\x3c\x73\x76\x67\ \x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\x31\x22\x20\x69\ \x64\x3d\x22\x43\x61\x70\x61\x5f\x31\x22\x20\x78\x6d\x6c\x6e\x73\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\ \x6f\x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x20\x78\x6d\ \x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\ \x39\x2f\x78\x6c\x69\x6e\x6b\x22\x20\x78\x3d\x22\x30\x70\x78\x22\ \x20\x79\x3d\x22\x30\x70\x78\x22\x0d\x0a\x09\x20\x76\x69\x65\x77\ \x42\x6f\x78\x3d\x22\x30\x20\x30\x20\x32\x39\x34\x2e\x37\x37\x34\ \x20\x32\x39\x34\x2e\x37\x37\x34\x22\x20\x73\x74\x79\x6c\x65\x3d\ \x22\x65\x6e\x61\x62\x6c\x65\x2d\x62\x61\x63\x6b\x67\x72\x6f\x75\ \x6e\x64\x3a\x6e\x65\x77\x20\x30\x20\x30\x20\x32\x39\x34\x2e\x37\ \x37\x34\x20\x32\x39\x34\x2e\x37\x37\x34\x3b\x22\x20\x78\x6d\x6c\ \x3a\x73\x70\x61\x63\x65\x3d\x22\x70\x72\x65\x73\x65\x72\x76\x65\ \x22\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\ \x64\x3d\x22\x4d\x32\x35\x31\x2e\x36\x33\x2c\x34\x33\x2e\x31\x37\ \x39\x63\x2d\x31\x31\x2e\x32\x39\x35\x2d\x31\x31\x2e\x32\x39\x35\ \x2d\x32\x33\x2e\x39\x33\x31\x2d\x32\x30\x2e\x34\x37\x32\x2d\x33\ \x37\x2e\x35\x35\x36\x2d\x32\x37\x2e\x32\x37\x36\x63\x2d\x32\x2e\ \x39\x36\x36\x2d\x31\x2e\x34\x38\x32\x2d\x36\x2e\x35\x36\x38\x2d\ \x30\x2e\x32\x37\x37\x2d\x38\x2e\x30\x34\x38\x2c\x32\x2e\x36\x38\ \x37\x0d\x0a\x09\x09\x63\x2d\x31\x2e\x34\x38\x2c\x32\x2e\x39\x36\ \x35\x2d\x30\x2e\x32\x37\x37\x2c\x36\x2e\x35\x36\x38\x2c\x32\x2e\ \x36\x38\x37\x2c\x38\x2e\x30\x34\x38\x63\x31\x32\x2e\x34\x36\x37\ \x2c\x36\x2e\x32\x32\x36\x2c\x32\x34\x2e\x30\x35\x32\x2c\x31\x34\ \x2e\x36\x34\x36\x2c\x33\x34\x2e\x34\x33\x32\x2c\x32\x35\x2e\x30\ \x32\x36\x63\x35\x32\x2e\x38\x30\x31\x2c\x35\x32\x2e\x38\x30\x31\ \x2c\x35\x32\x2e\x38\x30\x31\x2c\x31\x33\x38\x2e\x37\x31\x34\x2c\ \x30\x2c\x31\x39\x31\x2e\x35\x31\x35\x0d\x0a\x09\x09\x73\x2d\x31\ \x33\x38\x2e\x37\x31\x34\x2c\x35\x32\x2e\x38\x30\x31\x2d\x31\x39\ \x31\x2e\x35\x31\x35\x2c\x30\x73\x2d\x35\x32\x2e\x38\x30\x31\x2d\ \x31\x33\x38\x2e\x37\x31\x34\x2c\x30\x2d\x31\x39\x31\x2e\x35\x31\ \x35\x43\x37\x37\x2e\x32\x30\x37\x2c\x32\x36\x2e\x30\x38\x36\x2c\ \x31\x31\x31\x2e\x32\x31\x35\x2c\x31\x32\x2c\x31\x34\x37\x2e\x33\ \x38\x36\x2c\x31\x32\x63\x33\x2e\x33\x31\x33\x2c\x30\x2c\x36\x2d\ \x32\x2e\x36\x38\x37\x2c\x36\x2d\x36\x73\x2d\x32\x2e\x36\x38\x37\ \x2d\x36\x2d\x36\x2d\x36\x0d\x0a\x09\x09\x43\x31\x30\x38\x2e\x30\ \x30\x39\x2c\x30\x2c\x37\x30\x2e\x39\x38\x39\x2c\x31\x35\x2e\x33\ \x33\x34\x2c\x34\x33\x2e\x31\x34\x34\x2c\x34\x33\x2e\x31\x37\x39\ \x63\x2d\x35\x37\x2e\x34\x37\x39\x2c\x35\x37\x2e\x34\x37\x39\x2d\ \x35\x37\x2e\x34\x37\x39\x2c\x31\x35\x31\x2e\x30\x30\x36\x2c\x30\ \x2c\x32\x30\x38\x2e\x34\x38\x35\x63\x32\x38\x2e\x37\x34\x2c\x32\ \x38\x2e\x37\x34\x2c\x36\x36\x2e\x34\x39\x31\x2c\x34\x33\x2e\x31\ \x31\x2c\x31\x30\x34\x2e\x32\x34\x33\x2c\x34\x33\x2e\x31\x31\x0d\ \x0a\x09\x09\x73\x37\x35\x2e\x35\x30\x33\x2d\x31\x34\x2e\x33\x37\ \x2c\x31\x30\x34\x2e\x32\x34\x33\x2d\x34\x33\x2e\x31\x31\x43\x33\ \x30\x39\x2e\x31\x30\x39\x2c\x31\x39\x34\x2e\x31\x38\x35\x2c\x33\ \x30\x39\x2e\x31\x30\x39\x2c\x31\x30\x30\x2e\x36\x35\x38\x2c\x32\ \x35\x31\x2e\x36\x33\x2c\x34\x33\x2e\x31\x37\x39\x7a\x22\x2f\x3e\ \x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\x64\x3d\x22\x4d\x31\x34\x37\ \x2e\x33\x38\x37\x2c\x35\x31\x2e\x39\x39\x32\x63\x2d\x33\x2e\x33\ \x31\x33\x2c\x30\x2d\x36\x2c\x32\x2e\x36\x38\x37\x2d\x36\x2c\x36\ \x76\x31\x37\x38\x2e\x38\x35\x39\x63\x30\x2c\x33\x2e\x33\x31\x34\ \x2c\x32\x2e\x36\x38\x37\x2c\x36\x2c\x36\x2c\x36\x73\x36\x2d\x32\ \x2e\x36\x38\x36\x2c\x36\x2d\x36\x56\x35\x37\x2e\x39\x39\x32\x0d\ \x0a\x09\x09\x43\x31\x35\x33\x2e\x33\x38\x37\x2c\x35\x34\x2e\x36\ \x37\x38\x2c\x31\x35\x30\x2e\x37\x2c\x35\x31\x2e\x39\x39\x32\x2c\ \x31\x34\x37\x2e\x33\x38\x37\x2c\x35\x31\x2e\x39\x39\x32\x7a\x22\ \x2f\x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\x64\x3d\x22\x4d\x31\ \x37\x31\x2e\x33\x38\x37\x2c\x31\x35\x33\x2e\x34\x32\x31\x68\x36\ \x35\x2e\x34\x33\x63\x33\x2e\x33\x31\x33\x2c\x30\x2c\x36\x2d\x32\ \x2e\x36\x38\x37\x2c\x36\x2d\x36\x73\x2d\x32\x2e\x36\x38\x37\x2d\ \x36\x2d\x36\x2d\x36\x68\x2d\x36\x35\x2e\x34\x33\x63\x2d\x33\x2e\ \x33\x31\x33\x2c\x30\x2d\x36\x2c\x32\x2e\x36\x38\x37\x2d\x36\x2c\ \x36\x53\x31\x36\x38\x2e\x30\x37\x33\x2c\x31\x35\x33\x2e\x34\x32\ \x31\x2c\x31\x37\x31\x2e\x33\x38\x37\x2c\x31\x35\x33\x2e\x34\x32\ \x31\x7a\x22\x0d\x0a\x09\x09\x2f\x3e\x0d\x0a\x09\x3c\x70\x61\x74\ \x68\x20\x64\x3d\x22\x4d\x35\x37\x2e\x39\x35\x37\x2c\x31\x34\x31\ \x2e\x34\x32\x31\x63\x2d\x33\x2e\x33\x31\x33\x2c\x30\x2d\x36\x2c\ \x32\x2e\x36\x38\x37\x2d\x36\x2c\x36\x73\x32\x2e\x36\x38\x37\x2c\ \x36\x2c\x36\x2c\x36\x68\x36\x33\x2e\x34\x33\x63\x33\x2e\x33\x31\ \x33\x2c\x30\x2c\x36\x2d\x32\x2e\x36\x38\x37\x2c\x36\x2d\x36\x73\ \x2d\x32\x2e\x36\x38\x37\x2d\x36\x2d\x36\x2d\x36\x48\x35\x37\x2e\ \x39\x35\x37\x7a\x22\x2f\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\ \x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\ \x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\ \x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\ \x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\ \x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\ \x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\ \x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\ \x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\ \x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\ \x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\ \x67\x3e\x0d\x0a\x3c\x2f\x73\x76\x67\x3e\x0d\x0a\ \x00\x00\x06\xed\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x69\x73\x6f\ \x2d\x38\x38\x35\x39\x2d\x31\x22\x3f\x3e\x0d\x0a\x3c\x21\x2d\x2d\ \x20\x47\x65\x6e\x65\x72\x61\x74\x6f\x72\x3a\x20\x41\x64\x6f\x62\ \x65\x20\x49\x6c\x6c\x75\x73\x74\x72\x61\x74\x6f\x72\x20\x31\x39\ \x2e\x30\x2e\x30\x2c\x20\x53\x56\x47\x20\x45\x78\x70\x6f\x72\x74\ \x20\x50\x6c\x75\x67\x2d\x49\x6e\x20\x2e\x20\x53\x56\x47\x20\x56\ \x65\x72\x73\x69\x6f\x6e\x3a\x20\x36\x2e\x30\x30\x20\x42\x75\x69\ \x6c\x64\x20\x30\x29\x20\x20\x2d\x2d\x3e\x0d\x0a\x3c\x73\x76\x67\ \x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\x31\x22\x20\x69\ \x64\x3d\x22\x43\x61\x70\x61\x5f\x31\x22\x20\x78\x6d\x6c\x6e\x73\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\ \x6f\x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x20\x78\x6d\ \x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\ \x39\x2f\x78\x6c\x69\x6e\x6b\x22\x20\x78\x3d\x22\x30\x70\x78\x22\ \x20\x79\x3d\x22\x30\x70\x78\x22\x0d\x0a\x09\x20\x76\x69\x65\x77\ \x42\x6f\x78\x3d\x22\x30\x20\x30\x20\x32\x39\x34\x2e\x38\x34\x33\ \x20\x32\x39\x34\x2e\x38\x34\x33\x22\x20\x73\x74\x79\x6c\x65\x3d\ \x22\x65\x6e\x61\x62\x6c\x65\x2d\x62\x61\x63\x6b\x67\x72\x6f\x75\ \x6e\x64\x3a\x6e\x65\x77\x20\x30\x20\x30\x20\x32\x39\x34\x2e\x38\ \x34\x33\x20\x32\x39\x34\x2e\x38\x34\x33\x3b\x22\x20\x78\x6d\x6c\ \x3a\x73\x70\x61\x63\x65\x3d\x22\x70\x72\x65\x73\x65\x72\x76\x65\ \x22\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\ \x64\x3d\x22\x4d\x31\x34\x37\x2e\x34\x32\x31\x2c\x30\x43\x36\x36\ \x2e\x31\x33\x33\x2c\x30\x2c\x30\x2c\x36\x36\x2e\x31\x33\x33\x2c\ \x30\x2c\x31\x34\x37\x2e\x34\x32\x31\x73\x36\x36\x2e\x31\x33\x33\ \x2c\x31\x34\x37\x2e\x34\x32\x31\x2c\x31\x34\x37\x2e\x34\x32\x31\ \x2c\x31\x34\x37\x2e\x34\x32\x31\x63\x33\x38\x2e\x32\x38\x37\x2c\ \x30\x2c\x37\x34\x2e\x35\x36\x37\x2d\x31\x34\x2e\x36\x30\x39\x2c\ \x31\x30\x32\x2e\x31\x35\x39\x2d\x34\x31\x2e\x31\x33\x36\x0d\x0a\ \x09\x09\x63\x32\x2e\x33\x38\x39\x2d\x32\x2e\x32\x39\x36\x2c\x32\ \x2e\x34\x36\x34\x2d\x36\x2e\x30\x39\x35\x2c\x30\x2e\x31\x36\x37\ \x2d\x38\x2e\x34\x38\x33\x63\x2d\x32\x2e\x32\x39\x35\x2d\x32\x2e\ \x33\x38\x38\x2d\x36\x2e\x30\x39\x33\x2d\x32\x2e\x34\x36\x34\x2d\ \x38\x2e\x34\x38\x33\x2d\x30\x2e\x31\x36\x37\x63\x2d\x32\x35\x2e\ \x33\x34\x35\x2c\x32\x34\x2e\x33\x36\x37\x2d\x35\x38\x2e\x36\x37\ \x32\x2c\x33\x37\x2e\x37\x38\x36\x2d\x39\x33\x2e\x38\x34\x32\x2c\ \x33\x37\x2e\x37\x38\x36\x0d\x0a\x09\x09\x43\x37\x32\x2e\x37\x35\ \x2c\x32\x38\x32\x2e\x38\x34\x33\x2c\x31\x32\x2c\x32\x32\x32\x2e\ \x30\x39\x33\x2c\x31\x32\x2c\x31\x34\x37\x2e\x34\x32\x31\x53\x37\ \x32\x2e\x37\x35\x2c\x31\x32\x2c\x31\x34\x37\x2e\x34\x32\x31\x2c\ \x31\x32\x73\x31\x33\x35\x2e\x34\x32\x31\x2c\x36\x30\x2e\x37\x35\ \x2c\x31\x33\x35\x2e\x34\x32\x31\x2c\x31\x33\x35\x2e\x34\x32\x31\ \x63\x30\x2c\x31\x36\x2e\x38\x34\x32\x2d\x33\x2e\x30\x35\x32\x2c\ \x33\x33\x2e\x32\x37\x33\x2d\x39\x2e\x30\x37\x31\x2c\x34\x38\x2e\ \x38\x33\x35\x0d\x0a\x09\x09\x63\x2d\x31\x2e\x31\x39\x35\x2c\x33\ \x2e\x30\x39\x31\x2c\x30\x2e\x33\x34\x31\x2c\x36\x2e\x35\x36\x35\ \x2c\x33\x2e\x34\x33\x32\x2c\x37\x2e\x37\x36\x31\x63\x33\x2e\x30\ \x39\x32\x2c\x31\x2e\x31\x39\x33\x2c\x36\x2e\x35\x36\x35\x2d\x30\ \x2e\x33\x34\x31\x2c\x37\x2e\x37\x36\x31\x2d\x33\x2e\x34\x33\x32\ \x63\x36\x2e\x35\x35\x35\x2d\x31\x36\x2e\x39\x34\x39\x2c\x39\x2e\ \x38\x37\x39\x2d\x33\x34\x2e\x38\x33\x36\x2c\x39\x2e\x38\x37\x39\ \x2d\x35\x33\x2e\x31\x36\x35\x0d\x0a\x09\x09\x43\x32\x39\x34\x2e\ \x38\x34\x33\x2c\x36\x36\x2e\x31\x33\x33\x2c\x32\x32\x38\x2e\x37\ \x31\x2c\x30\x2c\x31\x34\x37\x2e\x34\x32\x31\x2c\x30\x7a\x22\x2f\ \x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\x64\x3d\x22\x4d\x31\x36\ \x37\x2e\x36\x31\x39\x2c\x31\x36\x30\x2e\x31\x33\x34\x63\x2d\x32\ \x2e\x33\x37\x2d\x32\x2e\x33\x31\x39\x2d\x36\x2e\x31\x36\x38\x2d\ \x32\x2e\x32\x37\x37\x2d\x38\x2e\x34\x38\x35\x2c\x30\x2e\x30\x39\ \x63\x2d\x32\x2e\x33\x31\x38\x2c\x32\x2e\x33\x36\x38\x2d\x32\x2e\ \x32\x37\x37\x2c\x36\x2e\x31\x36\x37\x2c\x30\x2e\x30\x39\x2c\x38\ \x2e\x34\x38\x35\x6c\x34\x37\x2e\x32\x33\x36\x2c\x34\x36\x2e\x32\ \x33\x36\x0d\x0a\x09\x09\x63\x31\x2e\x31\x36\x38\x2c\x31\x2e\x31\ \x34\x33\x2c\x32\x2e\x36\x38\x33\x2c\x31\x2e\x37\x31\x32\x2c\x34\ \x2e\x31\x39\x37\x2c\x31\x2e\x37\x31\x32\x63\x31\x2e\x35\x35\x37\ \x2c\x30\x2c\x33\x2e\x31\x31\x33\x2d\x30\x2e\x36\x30\x33\x2c\x34\ \x2e\x32\x38\x38\x2d\x31\x2e\x38\x30\x33\x63\x32\x2e\x33\x31\x38\ \x2d\x32\x2e\x33\x36\x38\x2c\x32\x2e\x32\x37\x37\x2d\x36\x2e\x31\ \x36\x37\x2d\x30\x2e\x30\x39\x2d\x38\x2e\x34\x38\x35\x4c\x31\x36\ \x37\x2e\x36\x31\x39\x2c\x31\x36\x30\x2e\x31\x33\x34\x7a\x22\x2f\ \x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\x64\x3d\x22\x4d\x31\x32\ \x35\x2e\x31\x37\x38\x2c\x31\x33\x33\x2e\x36\x36\x33\x63\x31\x2e\ \x31\x37\x31\x2c\x31\x2e\x31\x37\x31\x2c\x32\x2e\x37\x30\x37\x2c\ \x31\x2e\x37\x35\x37\x2c\x34\x2e\x32\x34\x33\x2c\x31\x2e\x37\x35\ \x37\x73\x33\x2e\x30\x37\x31\x2d\x30\x2e\x35\x38\x36\x2c\x34\x2e\ \x32\x34\x33\x2d\x31\x2e\x37\x35\x37\x63\x32\x2e\x33\x34\x33\x2d\ \x32\x2e\x33\x34\x33\x2c\x32\x2e\x33\x34\x33\x2d\x36\x2e\x31\x34\ \x32\x2c\x30\x2d\x38\x2e\x34\x38\x35\x0d\x0a\x09\x09\x4c\x38\x38\ \x2e\x34\x32\x38\x2c\x37\x39\x2e\x39\x34\x32\x63\x2d\x32\x2e\x33\ \x34\x33\x2d\x32\x2e\x33\x34\x33\x2d\x36\x2e\x31\x34\x33\x2d\x32\ \x2e\x33\x34\x33\x2d\x38\x2e\x34\x38\x35\x2c\x30\x63\x2d\x32\x2e\ \x33\x34\x33\x2c\x32\x2e\x33\x34\x33\x2d\x32\x2e\x33\x34\x33\x2c\ \x36\x2e\x31\x34\x32\x2c\x30\x2c\x38\x2e\x34\x38\x35\x4c\x31\x32\ \x35\x2e\x31\x37\x38\x2c\x31\x33\x33\x2e\x36\x36\x33\x7a\x22\x2f\ \x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\x64\x3d\x22\x4d\x32\x31\ \x34\x2e\x39\x2c\x37\x39\x2e\x39\x34\x32\x63\x2d\x32\x2e\x33\x34\ \x33\x2d\x32\x2e\x33\x34\x33\x2d\x36\x2e\x31\x34\x33\x2d\x32\x2e\ \x33\x34\x33\x2d\x38\x2e\x34\x38\x35\x2c\x30\x4c\x37\x39\x2e\x39\ \x34\x32\x2c\x32\x30\x36\x2e\x34\x31\x35\x63\x2d\x32\x2e\x33\x34\ \x33\x2c\x32\x2e\x33\x34\x33\x2d\x32\x2e\x33\x34\x33\x2c\x36\x2e\ \x31\x34\x32\x2c\x30\x2c\x38\x2e\x34\x38\x35\x0d\x0a\x09\x09\x63\ \x31\x2e\x31\x37\x31\x2c\x31\x2e\x31\x37\x31\x2c\x32\x2e\x37\x30\ \x37\x2c\x31\x2e\x37\x35\x37\x2c\x34\x2e\x32\x34\x33\x2c\x31\x2e\ \x37\x35\x37\x73\x33\x2e\x30\x37\x31\x2d\x30\x2e\x35\x38\x36\x2c\ \x34\x2e\x32\x34\x33\x2d\x31\x2e\x37\x35\x37\x4c\x32\x31\x34\x2e\ \x39\x2c\x38\x38\x2e\x34\x32\x38\x43\x32\x31\x37\x2e\x32\x34\x33\ \x2c\x38\x36\x2e\x30\x38\x34\x2c\x32\x31\x37\x2e\x32\x34\x33\x2c\ \x38\x32\x2e\x32\x38\x36\x2c\x32\x31\x34\x2e\x39\x2c\x37\x39\x2e\ \x39\x34\x32\x7a\x22\x2f\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\ \x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\ \x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\ \x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\ \x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\ \x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\ \x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\ \x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\ \x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\ \x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\ \x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\ \x67\x3e\x0d\x0a\x3c\x2f\x73\x76\x67\x3e\x0d\x0a\ \x00\x00\x07\x53\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x69\x73\x6f\ \x2d\x38\x38\x35\x39\x2d\x31\x22\x3f\x3e\x0d\x0a\x3c\x21\x2d\x2d\ \x20\x47\x65\x6e\x65\x72\x61\x74\x6f\x72\x3a\x20\x41\x64\x6f\x62\ \x65\x20\x49\x6c\x6c\x75\x73\x74\x72\x61\x74\x6f\x72\x20\x31\x39\ \x2e\x30\x2e\x30\x2c\x20\x53\x56\x47\x20\x45\x78\x70\x6f\x72\x74\ \x20\x50\x6c\x75\x67\x2d\x49\x6e\x20\x2e\x20\x53\x56\x47\x20\x56\ \x65\x72\x73\x69\x6f\x6e\x3a\x20\x36\x2e\x30\x30\x20\x42\x75\x69\ \x6c\x64\x20\x30\x29\x20\x20\x2d\x2d\x3e\x0d\x0a\x3c\x73\x76\x67\ \x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\x31\x22\x20\x69\ \x64\x3d\x22\x43\x61\x70\x61\x5f\x31\x22\x20\x78\x6d\x6c\x6e\x73\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\ \x6f\x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x20\x78\x6d\ \x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\ \x39\x2f\x78\x6c\x69\x6e\x6b\x22\x20\x78\x3d\x22\x30\x70\x78\x22\ \x20\x79\x3d\x22\x30\x70\x78\x22\x0d\x0a\x09\x20\x76\x69\x65\x77\ \x42\x6f\x78\x3d\x22\x30\x20\x30\x20\x32\x39\x33\x2e\x32\x34\x36\ \x20\x32\x39\x33\x2e\x32\x34\x36\x22\x20\x73\x74\x79\x6c\x65\x3d\ \x22\x65\x6e\x61\x62\x6c\x65\x2d\x62\x61\x63\x6b\x67\x72\x6f\x75\ \x6e\x64\x3a\x6e\x65\x77\x20\x30\x20\x30\x20\x32\x39\x33\x2e\x32\ \x34\x36\x20\x32\x39\x33\x2e\x32\x34\x36\x3b\x22\x20\x78\x6d\x6c\ \x3a\x73\x70\x61\x63\x65\x3d\x22\x70\x72\x65\x73\x65\x72\x76\x65\ \x22\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\ \x64\x3d\x22\x4d\x37\x37\x2e\x39\x31\x36\x2c\x38\x39\x2e\x35\x36\ \x32\x63\x2d\x31\x39\x2e\x39\x32\x32\x2c\x30\x2d\x33\x37\x2e\x34\ \x38\x32\x2c\x31\x30\x2e\x32\x37\x2d\x34\x37\x2e\x36\x39\x32\x2c\ \x32\x35\x2e\x37\x38\x35\x48\x36\x63\x2d\x33\x2e\x33\x31\x33\x2c\ \x30\x2d\x36\x2c\x32\x2e\x36\x38\x37\x2d\x36\x2c\x36\x73\x32\x2e\ \x36\x38\x37\x2c\x36\x2c\x36\x2c\x36\x68\x31\x38\x2e\x32\x31\x33\ \x0d\x0a\x09\x09\x63\x2d\x32\x2e\x31\x36\x39\x2c\x36\x2e\x30\x32\ \x35\x2d\x33\x2e\x33\x35\x39\x2c\x31\x32\x2e\x35\x31\x34\x2d\x33\ \x2e\x33\x35\x39\x2c\x31\x39\x2e\x32\x37\x36\x63\x30\x2c\x33\x31\ \x2e\x34\x36\x34\x2c\x32\x35\x2e\x35\x39\x38\x2c\x35\x37\x2e\x30\ \x36\x32\x2c\x35\x37\x2e\x30\x36\x32\x2c\x35\x37\x2e\x30\x36\x32\ \x73\x35\x37\x2e\x30\x36\x32\x2d\x32\x35\x2e\x35\x39\x38\x2c\x35\ \x37\x2e\x30\x36\x32\x2d\x35\x37\x2e\x30\x36\x32\x0d\x0a\x09\x09\ \x53\x31\x30\x39\x2e\x33\x38\x2c\x38\x39\x2e\x35\x36\x32\x2c\x37\ \x37\x2e\x39\x31\x36\x2c\x38\x39\x2e\x35\x36\x32\x7a\x20\x4d\x37\ \x37\x2e\x39\x31\x36\x2c\x31\x39\x31\x2e\x36\x38\x35\x63\x2d\x32\ \x34\x2e\x38\x34\x37\x2c\x30\x2d\x34\x35\x2e\x30\x36\x32\x2d\x32\ \x30\x2e\x32\x31\x35\x2d\x34\x35\x2e\x30\x36\x32\x2d\x34\x35\x2e\ \x30\x36\x32\x73\x32\x30\x2e\x32\x31\x35\x2d\x34\x35\x2e\x30\x36\ \x32\x2c\x34\x35\x2e\x30\x36\x32\x2d\x34\x35\x2e\x30\x36\x32\x0d\ \x0a\x09\x09\x73\x34\x35\x2e\x30\x36\x32\x2c\x32\x30\x2e\x32\x31\ \x35\x2c\x34\x35\x2e\x30\x36\x32\x2c\x34\x35\x2e\x30\x36\x32\x53\ \x31\x30\x32\x2e\x37\x36\x33\x2c\x31\x39\x31\x2e\x36\x38\x35\x2c\ \x37\x37\x2e\x39\x31\x36\x2c\x31\x39\x31\x2e\x36\x38\x35\x7a\x22\ \x2f\x3e\x0d\x0a\x09\x3c\x70\x61\x74\x68\x20\x64\x3d\x22\x4d\x32\ \x38\x37\x2e\x32\x34\x36\x2c\x31\x31\x35\x2e\x33\x34\x37\x68\x2d\ \x32\x37\x2e\x30\x35\x63\x2d\x32\x2e\x38\x39\x36\x2d\x34\x2e\x34\ \x31\x34\x2d\x36\x2e\x34\x30\x32\x2d\x38\x2e\x34\x34\x37\x2d\x31\ \x30\x2e\x34\x36\x2d\x31\x31\x2e\x39\x34\x37\x63\x2d\x31\x30\x2e\ \x33\x34\x35\x2d\x38\x2e\x39\x32\x34\x2d\x32\x33\x2e\x35\x37\x35\ \x2d\x31\x33\x2e\x38\x33\x38\x2d\x33\x37\x2e\x32\x35\x33\x2d\x31\ \x33\x2e\x38\x33\x38\x0d\x0a\x09\x09\x63\x2d\x32\x30\x2e\x34\x33\ \x32\x2c\x30\x2d\x33\x38\x2e\x33\x38\x31\x2c\x31\x30\x2e\x38\x30\ \x31\x2d\x34\x38\x2e\x34\x36\x32\x2c\x32\x36\x2e\x39\x38\x36\x63\ \x2d\x34\x2e\x33\x37\x36\x2d\x35\x2e\x35\x39\x35\x2d\x31\x31\x2e\ \x31\x38\x33\x2d\x39\x2e\x32\x30\x32\x2d\x31\x38\x2e\x38\x32\x31\ \x2d\x39\x2e\x32\x30\x32\x63\x2d\x34\x2e\x30\x30\x32\x2c\x30\x2d\ \x37\x2e\x39\x36\x34\x2c\x31\x2e\x30\x31\x31\x2d\x31\x31\x2e\x34\ \x35\x37\x2c\x32\x2e\x39\x32\x32\x0d\x0a\x09\x09\x63\x2d\x32\x2e\ \x39\x30\x37\x2c\x31\x2e\x35\x39\x31\x2d\x33\x2e\x39\x37\x34\x2c\ \x35\x2e\x32\x33\x37\x2d\x32\x2e\x33\x38\x33\x2c\x38\x2e\x31\x34\ \x35\x63\x31\x2e\x35\x39\x2c\x32\x2e\x39\x30\x36\x2c\x35\x2e\x32\ \x33\x36\x2c\x33\x2e\x39\x37\x32\x2c\x38\x2e\x31\x34\x34\x2c\x32\ \x2e\x33\x38\x33\x63\x31\x2e\x37\x35\x37\x2d\x30\x2e\x39\x36\x32\ \x2c\x33\x2e\x36\x37\x33\x2d\x31\x2e\x34\x34\x39\x2c\x35\x2e\x36\ \x39\x36\x2d\x31\x2e\x34\x34\x39\x0d\x0a\x09\x09\x63\x36\x2e\x35\ \x35\x36\x2c\x30\x2c\x31\x31\x2e\x38\x39\x2c\x35\x2e\x33\x33\x34\ \x2c\x31\x31\x2e\x38\x39\x2c\x31\x31\x2e\x38\x39\x63\x30\x2c\x30\ \x2e\x34\x30\x38\x2c\x30\x2e\x30\x34\x32\x2c\x30\x2e\x38\x30\x37\ \x2c\x30\x2e\x31\x31\x39\x2c\x31\x2e\x31\x39\x33\x63\x2d\x31\x2e\ \x31\x36\x37\x2c\x34\x2e\x35\x34\x2d\x31\x2e\x37\x38\x38\x2c\x39\ \x2e\x32\x39\x36\x2d\x31\x2e\x37\x38\x38\x2c\x31\x34\x2e\x31\x39\ \x35\x0d\x0a\x09\x09\x63\x30\x2c\x33\x31\x2e\x34\x36\x34\x2c\x32\ \x35\x2e\x35\x39\x38\x2c\x35\x37\x2e\x30\x36\x32\x2c\x35\x37\x2e\ \x30\x36\x32\x2c\x35\x37\x2e\x30\x36\x32\x63\x32\x33\x2e\x36\x32\ \x33\x2c\x30\x2c\x34\x35\x2e\x30\x38\x37\x2d\x31\x34\x2e\x38\x34\ \x38\x2c\x35\x33\x2e\x34\x31\x34\x2d\x33\x36\x2e\x39\x34\x36\x63\ \x31\x2e\x31\x36\x38\x2d\x33\x2e\x31\x30\x31\x2d\x30\x2e\x33\x39\ \x38\x2d\x36\x2e\x35\x36\x32\x2d\x33\x2e\x35\x2d\x37\x2e\x37\x32\ \x39\x0d\x0a\x09\x09\x63\x2d\x33\x2e\x31\x2d\x31\x2e\x31\x37\x2d\ \x36\x2e\x35\x36\x32\x2c\x30\x2e\x33\x39\x37\x2d\x37\x2e\x37\x33\ \x2c\x33\x2e\x34\x39\x39\x63\x2d\x36\x2e\x35\x37\x35\x2c\x31\x37\ \x2e\x34\x35\x31\x2d\x32\x33\x2e\x35\x32\x37\x2c\x32\x39\x2e\x31\ \x37\x37\x2d\x34\x32\x2e\x31\x38\x34\x2c\x32\x39\x2e\x31\x37\x37\ \x63\x2d\x32\x34\x2e\x38\x34\x37\x2c\x30\x2d\x34\x35\x2e\x30\x36\ \x32\x2d\x32\x30\x2e\x32\x31\x35\x2d\x34\x35\x2e\x30\x36\x32\x2d\ \x34\x35\x2e\x30\x36\x32\x0d\x0a\x09\x09\x73\x32\x30\x2e\x32\x31\ \x35\x2d\x34\x35\x2e\x30\x36\x32\x2c\x34\x35\x2e\x30\x36\x32\x2d\ \x34\x35\x2e\x30\x36\x32\x63\x32\x32\x2e\x33\x32\x38\x2c\x30\x2c\ \x34\x31\x2e\x30\x34\x38\x2c\x31\x35\x2e\x39\x37\x39\x2c\x34\x34\ \x2e\x35\x31\x32\x2c\x33\x37\x2e\x39\x39\x35\x63\x30\x2e\x35\x31\ \x35\x2c\x33\x2e\x32\x37\x33\x2c\x33\x2e\x35\x38\x34\x2c\x35\x2e\ \x35\x30\x38\x2c\x36\x2e\x38\x36\x2c\x34\x2e\x39\x39\x34\x0d\x0a\ \x09\x09\x63\x33\x2e\x32\x37\x33\x2d\x30\x2e\x35\x31\x35\x2c\x35\ \x2e\x35\x30\x39\x2d\x33\x2e\x35\x38\x36\x2c\x34\x2e\x39\x39\x35\ \x2d\x36\x2e\x38\x35\x39\x63\x2d\x30\x2e\x35\x35\x37\x2d\x33\x2e\ \x35\x34\x32\x2d\x31\x2e\x34\x35\x39\x2d\x37\x2e\x30\x30\x32\x2d\ \x32\x2e\x36\x36\x2d\x31\x30\x2e\x33\x34\x35\x68\x32\x31\x2e\x30\ \x35\x37\x63\x33\x2e\x33\x31\x33\x2c\x30\x2c\x36\x2d\x32\x2e\x36\ \x38\x37\x2c\x36\x2d\x36\x0d\x0a\x09\x09\x53\x32\x39\x30\x2e\x35\ \x36\x2c\x31\x31\x35\x2e\x33\x34\x37\x2c\x32\x38\x37\x2e\x32\x34\ \x36\x2c\x31\x31\x35\x2e\x33\x34\x37\x7a\x22\x2f\x3e\x0d\x0a\x3c\ \x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\ \x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\ \x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\ \x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\ \x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\ \x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\ \x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\ \x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\ \x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\ \x67\x3e\x0d\x0a\x3c\x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\ \x67\x3e\x0d\x0a\x3c\x2f\x67\x3e\x0d\x0a\x3c\x2f\x73\x76\x67\x3e\ \x0d\x0a\ " qt_resource_name = b"\ \x00\x0b\ \x05\x1a\xe3\xf9\ \x00\x69\ \x00\x63\x00\x6f\x00\x6e\x00\x2d\x00\x6d\x00\x6f\x00\x64\x00\x69\x00\x66\x00\x79\ \x00\x09\ \x06\x14\xb9\xfe\ \x00\x69\ \x00\x63\x00\x6f\x00\x6e\x00\x2d\x00\x6f\x00\x70\x00\x65\x00\x6e\ \x00\x0e\ \x03\xed\xf4\xc5\ \x00\x69\ \x00\x63\x00\x6f\x00\x6e\x00\x2d\x00\x64\x00\x75\x00\x70\x00\x6c\x00\x69\x00\x63\x00\x61\x00\x74\x00\x65\ \x00\x08\ \x0a\x61\x3a\x44\ \x00\x69\ \x00\x63\x00\x6f\x00\x6e\x00\x2d\x00\x61\x00\x64\x00\x64\ \x00\x0b\ \x03\x77\x60\x85\ \x00\x69\ \x00\x63\x00\x6f\x00\x6e\x00\x2d\x00\x64\x00\x65\x00\x6c\x00\x65\x00\x74\x00\x65\ \x00\x09\ \x06\x14\x10\x87\ \x00\x69\ \x00\x63\x00\x6f\x00\x6e\x00\x2d\x00\x76\x00\x69\x00\x65\x00\x77\ " qt_resource_struct_v1 = b"\ \x00\x00\x00\x00\x00\x02\x00\x00\x00\x06\x00\x00\x00\x01\ \x00\x00\x00\x6c\x00\x00\x00\x00\x00\x01\x00\x00\x15\xb1\ \x00\x00\x00\x34\x00\x00\x00\x00\x00\x01\x00\x00\x0b\xf3\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\ \x00\x00\x00\x88\x00\x00\x00\x00\x00\x01\x00\x00\x1c\xa2\ \x00\x00\x00\x1c\x00\x00\x00\x00\x00\x01\x00\x00\x06\x04\ \x00\x00\x00\x56\x00\x00\x00\x00\x00\x01\x00\x00\x0f\xd0\ " qt_resource_struct_v2 = b"\ \x00\x00\x00\x00\x00\x02\x00\x00\x00\x06\x00\x00\x00\x01\ \x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x6c\x00\x00\x00\x00\x00\x01\x00\x00\x15\xb1\ \x00\x00\x01\x77\x1a\xa4\x9c\x9c\ \x00\x00\x00\x34\x00\x00\x00\x00\x00\x01\x00\x00\x0b\xf3\ \x00\x00\x01\x77\x1a\xa4\x4a\x29\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\ \x00\x00\x01\x77\x1a\xa4\x04\x57\ \x00\x00\x00\x88\x00\x00\x00\x00\x00\x01\x00\x00\x1c\xa2\ \x00\x00\x01\x77\x1a\xa7\xce\xbf\ \x00\x00\x00\x1c\x00\x00\x00\x00\x00\x01\x00\x00\x06\x04\ \x00\x00\x01\x77\x1a\xa4\x29\x49\ \x00\x00\x00\x56\x00\x00\x00\x00\x00\x01\x00\x00\x0f\xd0\ \x00\x00\x01\x77\x1a\xa4\x8d\xa7\ " qt_version = [int(v) for v in QtCore.qVersion().split('.')] if qt_version < [5, 8, 0]: rcc_version = 1 qt_resource_struct = qt_resource_struct_v1 else: rcc_version = 2 qt_resource_struct = qt_resource_struct_v2 def qInitResources(): QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) def qCleanupResources(): QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) qInitResources()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/qrc_resources.py
qrc_resources.py
from EEETools.Tools.Other.handler import Handler from EEETools import costants import os class ModulesHandler(Handler): def __init__(self): super().__init__() self.current_folder = os.path.join(costants.ROOT_DIR, "EEETools", "Tools") self.data_folder = os.path.join(costants.ROOT_DIR, "3ETool_res", "EES Code Data") self.subclass_directory_path = "EEETools.BlockSubClasses" self.name_list = self.list_modules() self.translationDict = {"Alternatore" : "Alternator", "Caldaia" : "Boiler", "Camera di Combustione" : "Combustion Chamber", "Compressore" : "Compressor", "Condensatore" : "Condenser", "Evaporatore" : "Evaporator", "Generico" : "Generic", "Ingresso Fuel" : "Fuel Input", "Miscelatore" : "Mixer", "Pompa" : "Pump", "Scambiatore" : "Heat Exchanger", "Scambiatore - Multi Fuel" : "Heat Exchanger", "Scambiatore - Multi Product" : "Heat Exchanger", "Separatore" : "Separator", "Turbina" : "Expander", "Uscita Effetto Utile" : "Usefull Effect", "Valvola Laminazione" : "Valve"} def get_name_index(self, name: str): if " " in name: __std_name = name else: __std_name = self.get_std_name(name) if __std_name in self.name_list: return self.name_list.index(__std_name) else: return -1 def check_data_folder(self): if not os.path.isdir(self.data_folder): try: os.mkdir(self.data_folder) except: return for name in self.name_list: folder_name = self.get_module_name(name) name_folder_path = os.path.join(self.data_folder, folder_name) if not os.path.isdir(name_folder_path): try: os.mkdir(name_folder_path) except: pass def import_correct_sub_class(self, subclass_name): try: result = super(ModulesHandler, self).import_correct_sub_class(subclass_name) except: subclass_name = self.__translate_subclass_name(subclass_name) result = super(ModulesHandler, self).import_correct_sub_class(subclass_name) return result def __translate_subclass_name(self, subclass_name): if subclass_name in self.translationDict.keys(): return self.translationDict[subclass_name] else: return subclass_name
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/modules_handler.py
modules_handler.py
from EEETools import costants class Zones: def __init__(self, array_handler): self.array_handler = array_handler self.__initialize_zones() def __initialize_zones(self): self.zones = dict() for zone_type in costants.ZONES: zone_list = list() first_connection = self.__find_new_first_connection(zone_list) while first_connection is not None: zone_list.append(Zone(zone_type, first_connection)) first_connection = self.__find_new_first_connection(zone_list) self.zones.update({zone_type: zone_list}) def __find_new_first_connection(self, zone_list): for connection in self.array_handler.connection_list: if connection.is_fluid_stream: found = False for zone in zone_list: if zone.contains(connection): found = True break if not found: return connection return None class Zone: def __init__(self, type, first_connection): self.connections = list() self.type = type self.is_defined = False self.add_connections(first_connection) def add_connections(self, first_connection): self.add_connection(first_connection) def add_connection(self, connection): if connection not in self.connections: if not connection.zones[self.type] is None: connection.zones[self.type].remove_connection(connection) connection.add_zone(self) self.connections.append(connection) for new_connection in connection.return_other_zone_connections(self): self.add_connection(new_connection) def remove_connection(self, connection): self.connections.remove(connection) connection.zones[self.type] = None def contains(self, connection): return connection in self.connections
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/EESCodeGenerator/EES_checker.py
EES_checker.py
from rply import LexerGenerator, ParserGenerator, Token from rply.token import BaseBox from EEETools.costants import get_html_string class EESCodeAnalyzer: def __init__(self): self.__init_lexer_generator() self.__init_parser_generator() self.__init_lexer_generator(init_splitter=True) self.__init_splitting_parser_generator() def get_code_parts(self, input_string: str, print_token=False): if not input_string == "": if print_token: tokens_res = self.splitting_lexer.lex(input_string) for token in tokens_res: print(token) print() try: tokens_res = self.splitting_lexer.lex(input_string) parsed_string = self.splitting_parser.parse(tokens_res) return_list = list() parsed_string.update_list(return_list) return return_list except: if not print_token: self.get_code_parts(input_string, True) else: raise else: return None def parse_string(self, input_string: str, print_token=False): if not input_string == "": if print_token: tokens_res = self.lexer.lex(input_string) for token in tokens_res: print(token) print() try: tokens_res = self.lexer.lex(input_string) parsed_string = self.parser.parse(tokens_res) return parsed_string except: if not print_token: self.parse_string(input_string, True) else: raise else: return None # LINE CODE ANALYSIS # main lexer generation methods def __init_lexer_generator(self, init_splitter=False): self.lg = LexerGenerator() if init_splitter: self.splitting_tokens_list = list() else: self.tokensList = list() self.__define_simple_tokens(init_splitter) self.__define_keywords_tokens(init_splitter) self.__define_operator_tokens(init_splitter) self.__define_bracket_tokens(init_splitter) self.__define_other_tokens(init_splitter) if not init_splitter: self.lg.ignore(r'\s+') if init_splitter: self.splitting_lexer = self.lg.build() else: self.lexer = self.lg.build() def __define_simple_tokens(self, is_splitter): self.__add_token('NUMBER', r'\d+', is_splitter) def __define_keywords_tokens(self, is_splitter): if is_splitter: self.__add_token('OPTIONAL', r'optional', is_splitter) self.__add_token('REPEAT_KEYWORD', r'sum|multiply|repeat', is_splitter) self.__add_token('INPUT', r'input', is_splitter) self.__add_token('BLOCK_INDEX', r'block_index', is_splitter) self.__add_token('FLUID', r'fluid', is_splitter) self.__add_token('CALL', r'Call', is_splitter) def __define_operator_tokens(self, is_splitter): self.__add_token('DOLLAR', r'\$', is_splitter) self.__add_token('AMPERSAND', r'\&', is_splitter) self.__add_token('DOUBLE_QUOTE', r'\"', is_splitter) self.__add_token('COMMA', r'\,', is_splitter) self.__add_token('PLUS', r'\+', is_splitter) self.__add_token('MINUS', r'-', is_splitter) self.__add_token('MUL', r'\*', is_splitter) self.__add_token('DIV', r'/', is_splitter) self.__add_token('EQUAL', r'=', is_splitter) def __define_bracket_tokens(self, is_splitter): self.__add_token('OPEN_ROUND_BRACKET', r'\(', is_splitter) self.__add_token('CLOSE_ROUND_BRACKET', r'\)', is_splitter) self.__add_token('OPEN_SQUARED_BRACKET', r'\[', is_splitter) self.__add_token('CLOSE_SQUARED_BRACKET', r'\]', is_splitter) self.__add_token('OPEN_CURLY_BRACKET', r'\{', is_splitter) self.__add_token('CLOSE_CURLY_BRACKET', r'\}', is_splitter) def __define_other_tokens(self, is_splitter): if is_splitter: self.__add_token('SPACE', r'[\s]', is_splitter) self.__add_token('IDENTIFIER', r'[_a-zA-Z][_a-zA-Z0-9]*', is_splitter) self.__add_token('TEXT', r'[\S]*', is_splitter) # main parser generation methods def __init_parser_generator(self): self.pg = ParserGenerator( # A list of all token names, accepted by the parser. self.tokensList, # A list of precedence rules with ascending precedence, to # disambiguate ambiguous production rules. precedence=[ ('left', ['PLUS', 'MINUS']), ('left', ['MUL', 'DIV']) ] ) self.__add_line_rules() self.__add_comment_rules() self.__add_expression_rules() self.__add_atoms_rules() @self.pg.error def error_handler(token): raise ValueError( "Ran into a " + str(token.gettokentype()) + " where it wasn't expected! Token: " + str(token)) self.parser = self.pg.build() def __add_atoms_rules(self): # NUMBER # e.g. 10 @self.pg.production('atom : NUMBER') def expression_number(p): # p is a list of the pieces matched by the right hand side of the # rule return Number(int(p[0].getstr())) # IDENTIFIER # e.g. h_iso @self.pg.production('atom : IDENTIFIER') def expression_number(p): # p is a list of the pieces matched by the right hand side of the # rule return Identifier(p[0].getstr()) # VARIABLE # e.g. P[$0] @self.pg.production('atom : IDENTIFIER OPEN_SQUARED_BRACKET DOLLAR NUMBER CLOSE_SQUARED_BRACKET') def expression_parens(p): return Variable(p[0].getstr(), int(p[3].getstr())) # VARIABLE WITH BLOCK INDEX # e.g. P[$block_index] @self.pg.production('atom : IDENTIFIER OPEN_SQUARED_BRACKET DOLLAR BLOCK_INDEX CLOSE_SQUARED_BRACKET') def expression_parens(p): return Variable(p[0].getstr(), -1, is_block_index=True) # FLUID VARIABLE # e.g. $fluid @self.pg.production('atom : DOLLAR FLUID') def expression_parens(p): return Variable("fluid", -1, is_fluid=True) def __add_expression_rules(self): # REPEAT KEYWORD EXPRESSION # e.g. $repeat{ ... } @self.pg.production('expression : AMPERSAND REPEAT_KEYWORD OPEN_CURLY_BRACKET expression CLOSE_CURLY_BRACKET') def expression_parens(p): return RepeatKeywordExpression(p[1].getstr(), p[3]) # FUNCTION # e.g. Enthalpy(fluid, P = P[$0], T = T[$1]) @self.pg.production('expression : IDENTIFIER OPEN_ROUND_BRACKET arguments CLOSE_ROUND_BRACKET') def expression_parens(p): return Function(p[0].getstr(), p[2]) # FUNCTION ARGUMENTS # e.g. fluid, ... @self.pg.production('arguments : argument COMMA arguments') def expression_parens(p): return FunctionArgument(p[0], p[2]) @self.pg.production('arguments : argument') def expression_parens(p): return FunctionArgument(p[0]) # FUNCTION ARGUMENT # e.g. fluid or P = P[$0] @self.pg.production('argument : atom') def expression_parens(p): return p[0] @self.pg.production('argument : atom EQUAL atom') def expression_parens(p): return BinaryOp(p[0], p[2], "=") # ROUND BRACKET EXPRESSION # e.g. (10 + 20) @self.pg.production('expression : OPEN_ROUND_BRACKET expression CLOSE_ROUND_BRACKET') def expression_parens(p): return RoundedBracket(p[1]) @self.pg.production('expression : expression EQUAL expression') @self.pg.production('expression : expression MUL expression') @self.pg.production('expression : expression DIV expression') @self.pg.production('expression : expression PLUS expression') @self.pg.production('expression : expression MINUS expression') def expression_binop(p): left = p[0] right = p[2] if p[1].gettokentype() == 'PLUS': return BinaryOp(left, right, "+") elif p[1].gettokentype() == 'MINUS': return BinaryOp(left, right, "-") elif p[1].gettokentype() == 'MUL': return BinaryOp(left, right, "*") elif p[1].gettokentype() == 'DIV': return BinaryOp(left, right, "/") elif p[1].gettokentype() == 'EQUAL': return BinaryOp(left, right, "=") else: raise AssertionError('Oops, this should not be possible!') # BASE EXPRESSION @self.pg.production('expression : atom') def expression_parens(p): return p[0] def __add_comment_rules(self): @self.pg.production('comments : comment comments') def expression_comment_string(p): return CommentString(p[0], p[1]) @self.pg.production('comments : comment') def expression_comment_string(p): return CommentString(p[0]) for token in self.tokensList: if not token == 'NEW_LINE': input_str = 'comment : ' + token @self.pg.production(input_str) def expression_comment_string(p): return p[0].getstr() def __add_line_rules(self): # LINE WITH COMMENT # e.g. Delta_p[$blockIndex] = $input[2] "in [Pa]" @self.pg.production('line : line DOUBLE_QUOTE comments') def expression_line(p): return Line(p[0], Comment(p[2])) # COMMENT LINE # e.g. "this is a comment" @self.pg.production('line : DOUBLE_QUOTE comments') @self.pg.production('line : DOUBLE_QUOTE comments DOUBLE_QUOTE') def expression_line(p): return Line(input_comment=Comment(p[1])) # SIMPLE LINE @self.pg.production('line : expression') @self.pg.production('line : input_line') @self.pg.production('line : call_line') def expression_comment(p): return Line(input_expression=p[0]) # INPUT LINE # e.g. Delta_p[$blockIndex] = $input[2] input_str = 'input_line : expression EQUAL DOLLAR INPUT OPEN_SQUARED_BRACKET NUMBER CLOSE_SQUARED_BRACKET' @self.pg.production(input_str) def expression_parens(p): if type(p[0]) is Identifier or type(p[0]) is Variable: input = Variable(p[0].name, int(p[5].getstr()), is_input=True) return InputBlock(p[0], input) else: error_text = "you provided input as " + str(type(p[0])) + " = $input[#]. " error_text += "But input must be written as name = $input[#]!" raise ValueError(error_text) # FUNCTION CALL # e.g. Call calculate_cost(A[$block_index], k_0, k_1) @self.pg.production('call_line : CALL expression') def expression_parens(p): if type(p[1]) is Function: p[1].is_called = True return p[1] else: error_text = "you provided function call as Call " + str(type(p[1])) + ". " error_text += "But function call must be written as Call FUNCTION!" raise ValueError(error_text) # CODE SPLITTING PARSER AND LEXER DEFINITION # Code Splitting generation methods def __init_splitting_parser_generator(self): self.splitting_pg = ParserGenerator( # A list of all token names, accepted by the parser. self.splitting_tokens_list, # A list of precedence rules with ascending precedence, to # disambiguate ambiguous production rules. precedence=[] ) self.__add_main_rules() self.__add_code_rules() self.__add_token_rules() @self.splitting_pg.error def error_handler(token): raise ValueError( "Ran into a " + str(token.gettokentype()) + " where it wasn't expected! Token: " + str(token)) self.splitting_parser = self.splitting_pg.build() def __add_main_rules(self): @self.splitting_pg.production('main_code : code_container main_code') @self.splitting_pg.production('main_code : code_container') def add_optional_code_container(p): if len(p) == 2: p[0].set_next(p[1]) return p[0] def __add_code_rules(self): @self.splitting_pg.production( 'code_container : code_identifier OPEN_CURLY_BRACKET code_parts CLOSE_CURLY_BRACKET') def add_optional_code_container(p): __identifier_list = p[0] container_type = __identifier_list[0] container_name = __identifier_list[1] return CodeSection(input_type=container_type, input_name=container_name, expression=p[2]) @self.splitting_pg.production('code_identifier : AMPERSAND REPEAT_KEYWORD') @self.splitting_pg.production( 'code_identifier : AMPERSAND OPTIONAL OPEN_ROUND_BRACKET IDENTIFIER CLOSE_ROUND_BRACKET') def add_code_container_information(p): container_type = p[1].getstr() if len(p) > 2: container_name = p[3].getstr() else: container_name = "" return [container_type, container_name] @self.splitting_pg.production('code_container : OPEN_ROUND_BRACKET code_parts CLOSE_ROUND_BRACKET') def add_code_in_bracket(p): if issubclass(BaseBox, type(p[1])): result = p[1] elif type(p[0]) is Token: result = CodePart(p[1].getstr()) else: result = CodePart(str(p[1])) if len(p) == 2: result.set_next(p[1]) result.has_bracket = True return result @self.splitting_pg.production('code_container : code_parts') def add_optional_code_container(p): return CodeSection(p[0]) @self.splitting_pg.production('code_parts : code_part code_parts') @self.splitting_pg.production('code_parts : code_part') def add_code(p): if issubclass(BaseBox, type(p[0])): result = p[0] elif type(p[0]) is Token: result = CodePart(p[0].getstr()) else: result = CodePart(str(p[0])) if len(p) == 2: result.set_next(p[1]) return result def __add_token_rules(self): preserved_token = ["OPEN_CURLY_BRACKET", "CLOSE_CURLY_BRACKET", "OPEN_CURLY_BRACKET", "CLOSE_CURLY_BRACKET", "REPEAT_KEYWORD", "OPTIONAL", "AMPERSAND"] for token in self.splitting_tokens_list: if token not in preserved_token: input_str = 'code_part : ' + token @self.splitting_pg.production(input_str) def add_code(p): return CodePart(p[0].getstr()) # SUPPORT FUNCTIONS def __add_token(self, name, rule, is_splitting=False): self.lg.add(name, rule) if is_splitting: self.splitting_tokens_list.append(name) else: self.tokensList.append(name) # <--------------------- Code Element Classes ---------------------> # Main Parser Classes class EESBaseBox(BaseBox): def __init__(self): self.is_input = False self.is_variable = False self.expression = None self.left = None self.right = None self.next = None def append_variable_to_list(self, variable_list: list): if self.is_variable: variable_list.append(self) for element in [self.next, self.expression, self.right, self.left]: if element is not None: element.append_variable_to_list(variable_list) class Line(EESBaseBox): def __init__(self, input_expression=None, input_comment=None, input_next=None): super().__init__() if type(input_expression) is Line: if input_expression is not None: __tmp_expression = input_expression input_expression = __tmp_expression.expression input_comment = __tmp_expression.comment self.expression = input_expression self.comment = input_comment self.next = input_next @property def rich_text(self): __rich_text = "" if self.expression is not None: __rich_text += self.expression.rich_text if self.comment is not None: __rich_text += self.comment.rich_text if self.next is not None: __rich_text += "<br>" __rich_text += self.next.rich_text return __rich_text class Comment(EESBaseBox): def __init__(self, comment_string): super().__init__() self.comment_string = comment_string @property def rich_text(self): __rich_text = get_html_string("comments", "\"") __rich_text += self.comment_string.rich_text return __rich_text def append_variable_to_list(self, variable_list: list): # comment does not contain variables pass class CommentString(EESBaseBox): def __init__(self, text, next_input=None): super().__init__() self.text = text self.next = next_input @property def rich_text(self): __rich_text = get_html_string("comments", self.text) if not self.next is None: __rich_text += get_html_string("comments", " ") __rich_text += self.next.rich_text return __rich_text class Variable(EESBaseBox): def __init__(self, name, index, is_block_index=False, is_input=False, is_fluid=False): super().__init__() self.name = name self.index = index self.is_variable = True self.is_block_index = is_block_index self.is_input = is_input self.is_fluid = is_fluid @property def rich_text(self): if self.is_input: __rich_text = get_html_string("variable", "$input[" + str(self.index) + "]") elif self.is_fluid: __rich_text = get_html_string("variable", "$fluid") else: __rich_text = get_html_string("default", str(self.name) + "[") if self.is_block_index: __rich_text += get_html_string("variable", "$block_index") else: __rich_text += get_html_string("variable", "$" + str(self.index)) __rich_text += get_html_string("default", "]") return __rich_text class Number(EESBaseBox): def __init__(self, value): super().__init__() self.value = value @property def rich_text(self): __rich_text = get_html_string("default", str(self.value)) return __rich_text class Identifier(EESBaseBox): def __init__(self, name): super().__init__() self.name = name @property def rich_text(self): __rich_text = get_html_string("default", str(self.name)) return __rich_text class RepeatKeywordExpression(EESBaseBox): def __init__(self, key_word, expression): super().__init__() self.key_word = key_word self.expression = expression @property def rich_text(self): __rich_text = get_html_string("repeated_keyword", "&" + str(self.key_word)) __rich_text += get_html_string("default", "{") __rich_text += self.expression.rich_text __rich_text += get_html_string("default", "}") return __rich_text class Function(EESBaseBox): def __init__(self, name, expression): super().__init__() self.name = name self.expression = expression self.is_called = False @property def rich_text(self): __rich_text = "" if self.is_called: __rich_text = get_html_string("known_keyword", "Call ") __rich_text += get_html_string("unknown_function", str(self.name)) __rich_text += get_html_string("default", "(") __rich_text += self.expression.rich_text __rich_text += get_html_string("default", ")") return __rich_text class FunctionArgument(EESBaseBox): def __init__(self, expression, input_next=None): super().__init__() self.expression = expression self.next = input_next @property def rich_text(self): __rich_text = self.expression.rich_text if not self.next is None: __rich_text += get_html_string("default", ", ") __rich_text += self.next.rich_text return __rich_text class RoundedBracket(EESBaseBox): def __init__(self, expression): super().__init__() self.expression = expression @property def rich_text(self): __rich_text = get_html_string("default", "(") __rich_text += self.expression.rich_text __rich_text += get_html_string("default", ")") return __rich_text class InputBlock(EESBaseBox): def __init__(self, variable: Variable, input: Variable): super().__init__() self.variable = variable self.input = input self.input.is_input = True self.input.name = self.variable.name @property def rich_text(self): __rich_text = self.variable.rich_text __rich_text += get_html_string("default", " = ") __rich_text += self.input.rich_text return __rich_text def append_variable_to_list(self, variable_list: list): self.variable.append_variable_to_list(variable_list) self.input.append_variable_to_list(variable_list) class BinaryOp(EESBaseBox): def __init__(self, left, right, type): super().__init__() self.left = left self.right = right self.type = type @property def rich_text(self): __rich_text = self.left.rich_text __rich_text += get_html_string("default", " " + str(self.type) + " ") __rich_text += self.right.rich_text return __rich_text # Splitting Parser Classes class CodeSection(BaseBox): def __init__(self, expression, input_name="main", input_type="default", input_next=None): super().__init__() self.name = input_name self.type = input_type if issubclass(BaseBox, type(expression)): self.expression = expression else: self.expression = CodePart(str(expression)) self.next = input_next def set_next(self, input_next): self.next = input_next def update_list(self, input_list: list): if len(input_list) > 0: if self.type == "default" and input_list[-1]["type"] == "default": self.__extend_list_expression(input_list) elif self.type not in ["optional", "default"]: self.__extend_list_expression(input_list) else: self.__append_to_list(input_list) else: self.__append_to_list(input_list) if self.next is not None: self.next.update_list(input_list) def __append_to_list(self, input_list): input_list.append({"name": self.name, "type": self.type, "expression": self.plain_text}) def __extend_list_expression(self, input_list): input_list[-1]["expression"] += self.plain_text @property def plain_text(self): if self.type not in ["optional", "default"]: return "&" + self.type + "{" + self.expression.plain_text + "}" else: return self.expression.plain_text class CodePart(BaseBox): def __init__(self, input_expression, input_next=None, has_bracket=False): self.expression = input_expression self.next = input_next self.has_bracket = has_bracket @property def plain_text(self): if self.has_bracket: __plain_text = "(" else: __plain_text = "" __plain_text += str(self.expression) if self.has_bracket: __plain_text += ")" if self.next is not None: __plain_text += self.next.plain_text return __plain_text def set_next(self, input_next): self.next = input_next def __str__(self): return self.plain_text
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/EESCodeGenerator/EES_parser.py
EES_parser.py
from EEETools.Tools.EESCodeGenerator.EES_code import Code from EEETools.Tools.modules_handler import ModulesHandler from EEETools.Tools.GUIElements.gui_base_classes import * from PyQt5.QtWidgets import * from PyQt5.QtGui import QFont, QKeySequence from PyQt5.QtCore import Qt from shutil import copy2 as copy_file import os from EEETools import costants class DefineEESTextWidget(QDialog): # noinspection PyArgumentList def __init__(self, flags=None, *args, **kwargs): super().__init__(flags, *args, **kwargs) self.modules_handler = ModulesHandler() self.init_title() self.tables = dict() self.main_layout = QVBoxLayout(self) self.init_h_layout(0) self.init_h_layout(1) self.init_h_layout(2) self.init_h_layout(3) self.setLayout(self.main_layout) self.file_manager = None self.__enable_buttons() def init_title(self, EES_code_name="New EES code"): self.EES_code_name = EES_code_name self.is_saved = False self.__update_title() def init_h_layout(self, layout_layer): h_layout_new = QHBoxLayout() if layout_layer == 0: name_label = QLabel("Insert a name:") name_label.setFont(QFont("Helvetica 20")) name_label.setMinimumWidth(100) name_label.setMaximumWidth(100) self.name_edit_text = QLineEdit() self.name_edit_text.setFont(QFont("Helvetica 20 Bold")) self.name_edit_text.textChanged.connect(self.on_text_changed) h_layout_new.addWidget(name_label) h_layout_new.addWidget(self.name_edit_text) elif layout_layer == 1: name_label = QLabel("Select the Type:") name_label.setFont(QFont("Helvetica 20")) name_label.setMinimumWidth(100) name_label.setMaximumWidth(100) self.type_combobox = QComboBox() self.type_combobox.addItems(self.modules_handler.name_list) self.type_combobox.currentIndexChanged.connect(self.on_combo_box_changed) self.type_combobox.setFont(QFont("Helvetica 20 Bold")) h_layout_new.addWidget(name_label) h_layout_new.addWidget(self.type_combobox) elif layout_layer == 2: h_layout_new.addLayout(self.init_left_layout()) h_layout_new.addLayout(self.init_right_layout()) else: self.button_save = QPushButton() self.button_save.setText("Save (CTRL-S)") self.button_save.clicked.connect(self.on_save_button_pressed) self.button_new = QPushButton() self.button_new.setText("New (CTRL-N)") self.button_new.clicked.connect(self.on_new_button_pressed) self.__set_buttons_shortcut() h_layout_new.addWidget(self.button_save) h_layout_new.addWidget(self.button_new) self.__enable_buttons() self.main_layout.addLayout(h_layout_new) def init_left_layout(self): font = QFont() font.setFamily(costants.EES_CODE_FONT_FAMILY) font.setBold(True) self.input_script = QTextEdit("\"insert here your EES code ...\"") self.input_script.setMinimumWidth(400) self.input_script.setAcceptRichText(True) self.input_script.textChanged.connect(self.on_text_changed) self.input_script.setFont(font) self.code = Code(self) self.on_format_pressed() self.button_format = QPushButton() self.button_format.setText("Format Code (CTRL-F)") self.button_format.pressed.connect(self.on_format_pressed) v_layout_left = QVBoxLayout() v_layout_left.addWidget(self.input_script) v_layout_left.addWidget(self.button_format) return v_layout_left def init_right_layout(self): self.tables = dict() v_layout_right = QVBoxLayout() v_splitter = QSplitter(Qt.Vertical) v_splitter = self.init_table_view(v_splitter, "Input Indices") v_splitter = self.init_table_view(v_splitter, "Parameters Indices") v_splitter = self.init_table_view(v_splitter, "Equations") v_layout_right.addWidget(v_splitter) return v_layout_right def init_table_view(self, layout, title_str): widget = QWidget() v_layout = QVBoxLayout() title_label_input = QLabel(title_str, font=QFont('Helvetica 30 bold')) new_table = AbstractTable(self, title_str) new_table.setMinimumWidth(350) new_table.setMaximumWidth(350) header = new_table.horizontalHeader() header.setSectionResizeMode(0, QHeaderView.Stretch) header.setSectionResizeMode(1, QHeaderView.ResizeToContents) if title_str in ["Input Indices", "Parameters Indices"]: header.setSectionResizeMode(2, QHeaderView.ResizeToContents) v_layout.addWidget(title_label_input) v_layout.addWidget(new_table) widget.setLayout(v_layout) layout.addWidget(widget) self.tables.update({title_str: new_table}) return layout def open_file(self, file_path): try: root = self.code.read_file(file_path) except: save_warning_dialog = WarningDialog(self) save_warning_dialog.set_label_text("The file has been compromised and cannot be opened.\n" "An empty file will be opened instead") save_warning_dialog.show_only_one_button = True save_warning_dialog.set_button_text("ok", set_button_yes=True) save_warning_dialog.show() self.__reset_dialog() else: header = root.find("header") code_name = header.get("name") component_type = header.get("component_type") EES_code = root.find("EESCode").text self.name_edit_text.setText(code_name) self.input_script.setText(EES_code) self.set_combobox_name(component_type) file_name = code_name + ".xml" folder_name = self.modules_handler.get_module_name(component_type) self.EES_code_name = os.path.join(folder_name, file_name) self.__update_title() self.on_format_pressed() def set_combobox_name(self, name): index = self.modules_handler.get_name_index(name) if index == -1: index = 0 self.type_combobox.setCurrentIndex(index) def on_combo_box_changed(self): new_model = IndexSetterTableModel(self, "Input Indices") self.tables["Input Indices"].setModel(new_model) new_model = IndexSetterTableModel(self, "Equations") self.tables["Equations"].setModel(new_model) def on_text_changed(self): try: self.__enable_buttons() self.is_saved = False self.__update_title() except: pass def on_new_button_pressed(self): self.new_warning_dialog = WarningDialog(self) self.new_warning_dialog.set_label_text("By clicking \"Continue\" all your progress will be lost") self.new_warning_dialog.set_buttons_on_click(self.on_new_warning_clicked) self.new_warning_dialog.set_button_text("Continue", set_button_yes=True) self.new_warning_dialog.set_button_text("Cancel", set_button_yes=False) self.new_warning_dialog.show() def on_new_warning_clicked(self): sender = self.sender() if sender.is_yes_button: self.__reset_dialog() self.new_warning_dialog.close() def on_save_button_pressed(self): self.save_warning_dialog = WarningDialog(self) self.save_warning_dialog.set_label_text("Do you want to save the file? Data will be overwritten") self.save_warning_dialog.set_buttons_on_click(self.on_save_warning_clicked) self.save_warning_dialog.set_button_text("Continue", set_button_yes=True) self.save_warning_dialog.set_button_text("Cancel", set_button_yes=False) self.save_warning_dialog.show() def on_save_warning_clicked(self): sender = self.sender() if sender.is_yes_button: self.__save() self.save_warning_dialog.close() def on_format_pressed(self): self.code.update() self.input_script.setHtml(self.code.rich_text) self.input_script.repaint() if hasattr(self, 'tables'): if "Parameters Indices" in self.tables.keys(): new_model = IndexSetterTableModel(self, "Parameters Indices") new_model.load_data(self.code.inputs) self.tables["Parameters Indices"].setModel(new_model) self.tables["Parameters Indices"].repaint() def __enable_buttons(self): self.button_save.setEnabled(self.is_ready_for_saving) def __reset_dialog(self): self.init_title() self.name_edit_text.setText("") self.input_script.setText("\"insert here your EES code ...\"") self.name_edit_text.setEnabled(True) self.type_combobox.setEnabled(True) self.on_format_pressed() def __save(self): return_list = self.code.save() folder_name = return_list[0] file_name = return_list[1] self.is_saved = True self.EES_code_name = os.path.join(folder_name, file_name) self.name_edit_text.setEnabled(False) self.type_combobox.setEnabled(False) self.__update_title() def __set_buttons_shortcut(self): sequence_save = QKeySequence(Qt.CTRL + Qt.Key_S) self.button_save.setShortcut(sequence_save) sequence_new = QKeySequence(Qt.CTRL + Qt.Key_N) self.button_new.setShortcut(sequence_new) sequence_format = QKeySequence(Qt.CTRL + Qt.Key_F) self.button_format.setShortcut(sequence_format) def __update_title(self): title = self.EES_code_name + " - " if not self.is_saved: title += "Not " title += "Saved" self.setWindowTitle(title) @property def is_ready_for_saving(self): __name = self.name_edit_text.text() __input_script = self.input_script.toPlainText() return not __name == "" and not (__input_script == "" or __input_script == "\"insert here your EES code ...\"") class EESTextFilesManager(AbstractFilesManager): def __init__(self, flags=None, *args, **kwargs): super().__init__(flags, *args, **kwargs) self.title = "EES File Manager" self.modules_handler = ModulesHandler() def on_button_add_pressed(self): self.file_edit = DefineEESTextWidget(self) if not os.path.isdir(self.selected_element_path): dir_name = os.path.dirname(self.selected_element_path) else: dir_name = self.selected_element_path self.file_edit.set_combobox_name(os.path.basename(dir_name)) self.file_edit.type_combobox.setEnabled(False) self.file_edit.show() def on_button_modify_pressed(self): self.file_edit = DefineEESTextWidget(self) self.file_edit.open_file(self.selected_element_path) self.file_edit.name_edit_text.setEnabled(False) self.file_edit.type_combobox.setEnabled(False) self.file_edit.show() def on_button_delete_pressed(self): dir_name = os.path.dirname(self.selected_element_path) dir_name = os.path.basename(dir_name) filename = os.path.basename(self.selected_element_path) warning_text = "Do you really want to delete file " warning_text += os.path.join(dir_name, filename) warning_text += "?" self.delete_warning_dialog = WarningDialog(self) self.delete_warning_dialog.set_label_text(warning_text) self.delete_warning_dialog.set_buttons_on_click(self.on_delete_warning_clicked) self.delete_warning_dialog.set_button_text("Yes", set_button_yes=True) self.delete_warning_dialog.set_button_text("No", set_button_yes=False) self.delete_warning_dialog.show() def on_delete_warning_clicked(self): sender = self.sender() if sender.is_yes_button: if os.path.exists(self.selected_element_path): os.remove(self.selected_element_path) self.__enable_buttons() self.delete_warning_dialog.close() def on_button_rename_pressed(self): dir_name = os.path.dirname(self.selected_element_path) dir_name = os.path.basename(dir_name) filename = os.path.basename(self.selected_element_path) label_text = "insert new name for file " label_text += os.path.join(dir_name, filename) self.rename_line_edit = QLineEdit() hint_label = QLabel("new name:") hLayout = QHBoxLayout() hLayout.addWidget(hint_label) hLayout.addWidget(self.rename_line_edit) self.rename_warning_dialog = WarningDialog(self) self.rename_warning_dialog.set_layout(hLayout) self.rename_warning_dialog.set_label_text(label_text) self.rename_warning_dialog.set_buttons_on_click(self.on_rename_warning_clicked) self.rename_warning_dialog.set_button_text("Rename", set_button_yes=True) self.rename_warning_dialog.set_button_text("Cancel", set_button_yes=False) self.rename_warning_dialog.show() def on_rename_warning_clicked(self): sender = self.sender() if sender.is_yes_button: new_name = self.rename_line_edit.text() self.__rename_file(new_name, self.selected_element_path) self.__enable_buttons() self.rename_warning_dialog.close() def on_button_duplicate_pressed(self): dir_name = os.path.dirname(self.selected_element_path) dir_name = os.path.basename(dir_name) filename = os.path.basename(self.selected_element_path) warning_text = "Do you really want to duplicate file " warning_text += os.path.join(dir_name, filename) warning_text += "?" self.duplicate_warning_dialog = WarningDialog(self) self.duplicate_warning_dialog.set_label_text(warning_text) self.duplicate_warning_dialog.set_buttons_on_click(self.on_duplicate_warning_pressed) self.duplicate_warning_dialog.set_button_text("Yes", set_button_yes=True) self.duplicate_warning_dialog.set_button_text("No", set_button_yes=False) self.duplicate_warning_dialog.show() def on_duplicate_warning_pressed(self): sender = self.sender() if sender.is_yes_button: if os.path.exists(self.selected_element_path): dir_name = os.path.dirname(self.selected_element_path) filename = os.path.basename(self.selected_element_path) if ".dat" in filename: filename = filename.split(".dat")[0] file_extension = ".dat" elif ".xml" in filename: filename = filename.split(".xml")[0] file_extension = ".xml" else: file_extension = "" i = 1 new_path = os.path.join(dir_name, filename + "(1)" + file_extension) while os.path.exists(new_path): i += 1 new_path = os.path.join(dir_name, filename + "(" + str(i) + ")" + file_extension) copy_file(self.selected_element_path, new_path) self.duplicate_warning_dialog.close() def __rename_file(self, new_name, file_path): Code.rename_file(new_name, file_path) super(EESTextFilesManager, self).__rename_file(new_name, file_path)
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/EESCodeGenerator/EES_creator_tool.py
EES_creator_tool.py
from EEETools.Tools.EESCodeGenerator.EES_parser import EESCodeAnalyzer from EEETools.Tools.Other.fernet_handler import FernetHandler from EEETools.Tools.modules_handler import ModulesHandler from EEETools.costants import get_html_string import xml.etree.ElementTree as ETree import os class Code: def __init__(self, modify_widget=None): self.modify_widget = modify_widget self.code_analyzer = EESCodeAnalyzer() self.modules_handler = ModulesHandler() self.blocks = list() self.inputs = dict() self.options = list() self.plain_text = "" self.rich_text = "" self.parsed_code = None self.update() def update(self): if self.modify_widget is not None: text = self.modify_widget.input_script.toPlainText() else: text = self.plain_text self.blocks = list() try: __block_list = self.code_analyzer.get_code_parts(text) except: self.blocks.append(CodeBlock(input_text=text)) else: for __block_element in __block_list: __name = __block_element["name"] __type = __block_element["type"] __text = __block_element["expression"] self.blocks.append(CodeBlock(input_name=__name, input_type=__type, input_text=__text)) self.plain_text = text self.set_rich_text() self.__update_inputs() def set_rich_text(self): self.rich_text = "<!DOCTYPE html>" self.rich_text += "<html><head>" self.rich_text += "<style>tab{margin-left: 10px;display:block;}</style>" self.rich_text += "</head><body><div contenteditable><p>" for line in self.blocks: self.rich_text += line.rich_text self.rich_text += "</p></div></body></html>" def __update_inputs(self): self.inputs = dict() for block in self.blocks: if block.has_input: self.inputs.update(block.inputs) def __update_options(self): self.options = list() for block in self.blocks: if block.type == "optional": self.options.append(block.name) # <----------------- READ & SAVE METHODS ---------------> def save(self): # This class save the code data to a .dat file containing an encrypted xml tree. Encryption is useful in # order to prevent the user from modifying the file manually without going through the editor. # # The method generate the xml tree and pass it to the "__save_to_file" method that is in charge of the # encryption and file saving processes. # # here is an example of EES code xml file: # # <data> # # <header name="standard" component_type="Expander"> # # <options> # # <option name="set_delta_P"/> # # </options> # <inputs> # # <input name="Eff", index="1", related_option = "none"/> # <input name="Delta_P", index="0", related_option = "set_delta_P"/> # # </inputs> # # <variables> # # <variable name="power input", index="0", multiple_check="False" /> # <variable name="flow input", index="1", multiple_check="False" /> # <variable name="flow output", index="2", multiple_check="False" /> # # </variables> # # </header> # # <EESCode> # # "Turbine " # Eff[$block_index] = $input[0] # # &optional(set_delta_P){ # # Delta_P[$block_index] = $input[1] # P[$2] = P[$1] - Delta_P[$block_index] # # } # # h_iso[$2] = enthalpy($fluid, P = P[$1], s = s[$1]) # # h[$2] = h[$1] + (h_iso[$2] - h[$1]) * Eff[$block_index] # s[$2] = entropy($fluid, P = P[$2], h = h[$2]) # T[$2] = temperature($fluid, P = P[$2], h = h[$2]) # # m_dot[$2] = m_dot[$1] # W[$0] = (h[$1] - h[$2]) * m_dot[$1] # # </EESCode> # # </data> if self.modify_widget is not None: data = ETree.Element("data") # <--------- HEADER DEFINITION ---------> header = ETree.SubElement(data, "header") code_name = self.modify_widget.name_edit_text.text().lower() component_type = self.modify_widget.type_combobox.currentText() header.set("name", code_name) header.set("component_type", component_type) # <--------- OPTIONS DEFINITION ---------> options = ETree.SubElement(header, "options") for option in self.options: input_element = ETree.SubElement(options, "option") input_element.set("name", str(option)) # <--------- INPUTS DEFINITION ---------> inputs = ETree.SubElement(header, "inputs") inputs_dict = self.inputs for key in inputs_dict.keys(): input_element = ETree.SubElement(inputs, "input") input_element.set("name", str(key)) input_element.set("index", str(inputs_dict[key][0])) input_element.set("related_option", str(inputs_dict[key][1])) # <--------- VARIABLES DEFINITION ---------> variables = ETree.SubElement(header, "variables") variable_dict = self.modify_widget.tables["Input Indices"].model().data_dict for key in variable_dict.keys(): variable = ETree.SubElement(variables, "variable") variable.set("name", str(key)) variable.set("index", str((variable_dict[key])[0])) variable.set("multiple_check", str((variable_dict[key])[1])) # <--------- EES CODE DEFINITION ---------> EES_code = ETree.SubElement(data, "EESCode") EES_code.text = self.plain_text # <--------- FILE PATH DEFINITION ---------> main_folder = self.modules_handler.data_folder folder_name = self.modules_handler.get_module_name(component_type) file_name = code_name + ".dat" file_path = os.path.join(main_folder, folder_name, file_name) self.__save_to_file(data, file_path) else: folder_name = "" file_name = "" return [folder_name, file_name] def read_file(self, file_path): root = self.__read_file(file_path) EES_code = root.find("EESCode").text self.plain_text = EES_code return root @classmethod def rename_file(cls, new_name, file_path): root = cls.__read_file(file_path) header = root.find("header") header.attrib["name"] = new_name cls.__save_to_file(root, file_path) @staticmethod def __read_file(file_path): if ".xml" not in file_path: fernet = FernetHandler() root = fernet.read_file(file_path) else: data = file_path tree = ETree.parse(data) root = tree.getroot() return root @staticmethod def __save_to_file(root: ETree.Element, file_path): fernet = FernetHandler() fernet.save_file(file_path, root) class CodeBlock: def __init__(self, input_type="default", input_name="", input_text=""): self.code_analyzer = EESCodeAnalyzer() self.modules_handler = ModulesHandler() self.lines = list() self.inputs = dict() self.type = input_type self.name = input_name self.plain_text = input_text self.rich_text = "" self.parsed_code = None self.update(self.plain_text) def update(self, text): self.lines = list() self.plain_text = text if not text == "": for line_text in text.splitlines(): new_code_line = CodeLine(self.code_analyzer, line_text) self.lines.append(new_code_line) self.set_rich_text() self.__update_inputs() def set_rich_text(self): self.rich_text = "" __tabulation = "" if self.type == "optional": self.rich_text += "<br>" self.rich_text += get_html_string("repeated_keyword", "&optional") self.rich_text += get_html_string("default", "(") self.rich_text += get_html_string("variable", self.name) self.rich_text += get_html_string("default", ")") self.rich_text += get_html_string("default", "{") self.rich_text += "<tab>" self.rich_text += self.lines[0].rich_text if len(self.lines) > 1: for line in self.lines[1:]: self.rich_text += "<br>" self.rich_text += line.rich_text if self.type == "optional": self.rich_text += "</tab>" self.rich_text += "<br>" self.rich_text += get_html_string("default", "}") def __update_inputs(self): self.inputs = dict() if self.type == "default": __related_option = "none" else: __related_option = self.name for line in self.lines: if line.has_input: self.inputs.update(line.inputs) for key in self.inputs.keys(): self.inputs[key].append(__related_option) @property def has_input(self): return not len(self.inputs) == 0 class CodeLine: def __init__(self, code_analyzer: EESCodeAnalyzer, plain_text: str): self.code_analyzer = code_analyzer self.parsed_text = None self.plain_text = plain_text self.rich_text = "" self.comment = "" self.inputs = dict() self.variables = list() self.__parse_text() def __parse_text(self): try: self.parsed_text = self.code_analyzer.parse_string(self.plain_text) except: self.has_error = True self.parsed_text = None self.rich_text = get_html_string("error", self.plain_text) else: self.has_error = False if not self.parsed_text is None: self.rich_text = self.parsed_text.rich_text self.__find_variables() def __find_variables(self): self.inputs = dict() self.variables = list() if self.parsed_text is not None: __tmp_variables = list() self.parsed_text.append_variable_to_list(__tmp_variables) for variable in __tmp_variables: self.variables.append(variable) if variable.is_input: self.inputs.update({variable.name: [variable.index]}) @property def has_input(self): return not len(self.inputs) == 0
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/EESCodeGenerator/EES_code.py
EES_code.py
from EEETools.Tools.API.ExcelAPI.modules_importer import calculate_excel, import_excel_input, export_debug_info_to_excel from EEETools.Tools.GUIElements.connection_and_block_check import CheckConnectionWidget from EEETools.Tools.GUIElements.net_plot_modules import display_network from EEETools.MainModules.main_module import CalculationOptions from EEETools.Tools.API.Tools.file_handler import get_file_position from tkinter import filedialog from shutil import copyfile import tkinter as tk import os, warnings def calculate( excel_path="", calculate_on_pf_diagram=True, loss_cost_is_zero=True, valve_is_dissipative=True, condenser_is_dissipative=True ): excel_path = __find_excel_path(excel_path) if excel_path == "": return option = CalculationOptions() option.calculate_on_pf_diagram = calculate_on_pf_diagram option.loss_cost_is_zero = loss_cost_is_zero option.valve_is_dissipative = valve_is_dissipative option.condenser_is_dissipative = condenser_is_dissipative with warnings.catch_warnings(): warnings.simplefilter("ignore") calculate_excel(excel_path, option) def export_debug_information( excel_path="", calculate_on_pf_diagram=True, loss_cost_is_zero=True, valve_is_dissipative=True, condenser_is_dissipative=True ): excel_path = __find_excel_path(excel_path) if excel_path == "": return option = CalculationOptions() option.calculate_on_pf_diagram = calculate_on_pf_diagram option.loss_cost_is_zero = loss_cost_is_zero option.valve_is_dissipative = valve_is_dissipative option.condenser_is_dissipative = condenser_is_dissipative with warnings.catch_warnings(): warnings.simplefilter("ignore") array_handler = calculate_excel(excel_path, option, export_solution=False) export_debug_info_to_excel(excel_path, array_handler) def launch_connection_debug(excel_path=""): excel_path = __find_excel_path(excel_path) if excel_path == "": return array_handler = import_excel_input(excel_path) CheckConnectionWidget.launch(array_handler) def launch_network_display(excel_path=""): excel_path = __find_excel_path(excel_path) if excel_path == "": return array_handler = import_excel_input(excel_path) display_network(array_handler) def plot_sankey( excel_path="", show_component_mixers=False, generate_on_pf_diagram=True, display_costs=False, font_size=15, min_opacity_perc=0.15 ): from EEETools.Tools.API.Tools.sankey_diagram_generation import SankeyDiagramGenerator, SankeyDiagramOptions excel_path = __find_excel_path(excel_path) if excel_path == "": return array_handler = import_excel_input(excel_path) options = SankeyDiagramOptions() options.generate_on_pf_diagram = generate_on_pf_diagram options.show_component_mixers = show_component_mixers options.display_costs = display_costs options.font_size = font_size options.min_opacity_perc = min_opacity_perc SankeyDiagramGenerator(array_handler, options).show() def paste_default_excel_file(): __import_file("Default Excel Input_eng.xlsm") def paste_user_manual(): __import_file("User Guide-eng.pdf") def paste_components_documentation(): __import_file("Component Documentation-eng.pdf") def __import_file(filename): root = tk.Tk() root.withdraw() dir_path = filedialog.askdirectory() if dir_path == "": return file_path = os.path.join(dir_path, filename) file_position = get_file_position(filename) if file_position == "": warning_message = "\n\n<----------------- !WARNING! ------------------->\n" warning_message += "Unable to save the file to the desired location!\n\n" warning_message += "file name:\t\t\t" + filename + "\n" warning_message += "file position:\t\t" + file_position + "\n" warning_message += "new file position:\t" + file_path + "\n\n" warnings.warn(warning_message) else: try: copyfile(file_position, file_path) except: warning_message = "\n\n<----------------- !WARNING! ------------------->\n" warning_message += "Unable to copy the file to the desired location!\n\n" else: warning_message = "\n\n<----------------- !SUCCESS! ------------------->\n" warning_message += "File successfully copied to the desired location!\n\n" warning_message += "file name:\t\t\t" + filename + "\n" warning_message += "file position:\t" + file_path + "\n\n" warnings.warn(warning_message) def __find_excel_path(excel_path): if excel_path == "": root = tk.Tk() root.withdraw() excel_path = filedialog.askopenfilename() return excel_path
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/API/terminal_api.py
terminal_api.py
from EEETools.Tools.API.Tools.main_tools import get_result_data_frames, update_exergy_values, get_debug_data_frames from EEETools.Tools.API.DatAPI.modules_importer import export_dat from EEETools.MainModules.main_module import CalculationOptions from openpyxl import Workbook, load_workbook, styles, utils from EEETools.MainModules.main_module import ArrayHandler from datetime import date, datetime import math, pandas, os import warnings def calculate_excel(excel_path, calculation_option=None, new_exergy_list=None, export_solution=True): array_handler = import_excel_input(excel_path, calculation_option) if new_exergy_list is not None: array_handler = update_exergy_values(array_handler, new_exergy_list) array_handler.calculate() if export_solution: export_solution_to_excel(excel_path, array_handler) return array_handler def convert_excel_to_dat(excel_path: str): array_handler = import_excel_input(excel_path) if ".xlsm" in excel_path: dat_path = excel_path.replace(".xlsm", ".dat") elif ".xlsx" in excel_path: dat_path = excel_path.replace(".xlsx", ".dat") else: dat_path = excel_path.replace(".xls", ".dat") export_dat(dat_path, array_handler) def import_excel_input(excel_path, calculation_option=None) -> ArrayHandler: with warnings.catch_warnings(): warnings.simplefilter("ignore") __check_excel_version(excel_path) array_handler = ArrayHandler() if calculation_option is not None and type(calculation_option) == CalculationOptions: array_handler.options = calculation_option # import connections excel_connection_data = pandas.read_excel(excel_path, sheet_name="Stream") for line in excel_connection_data.values: line = line.tolist() if not math.isnan(line[0]): new_conn = array_handler.append_connection() new_conn.index = line[0] new_conn.name = str(line[1]) new_conn.exergy_value = line[2] # import blocks excel_block_data = pandas.read_excel(excel_path, sheet_name="Componenti") for line in excel_block_data.values: line = line.tolist() if not (math.isnan(line[0]) or type(line[0]) is str): if line[0] > 0: if "Heat Exchanger" in str(line[2]) or "Scambiatore" in str(line[2]): new_block = array_handler.append_block("Heat Exchanger") excel_connection_list = list() excel_connection_list.append(str(line[2])) excel_connection_list.extend(line[5:]) else: new_block = array_handler.append_block(str(line[2])) excel_connection_list = line[5:] new_block.index = line[0] new_block.name = str(line[1]) new_block.comp_cost = line[3] new_block.initialize_connection_list(excel_connection_list) else: array_handler.append_excel_costs_and_useful_output(line[5:-1], line[0] == 0, line[3]) return array_handler def export_solution_to_excel(excel_path, array_handler: ArrayHandler): result_df = get_result_data_frames(array_handler) __write_excel_file(excel_path, result_df) def export_debug_info_to_excel(excel_path, array_handler: ArrayHandler): result_df = get_debug_data_frames(array_handler) __write_excel_file(excel_path, result_df) def __write_excel_file(excel_path, result_df): # Generation of time stamps for Excel sheet name today = date.today() now = datetime.now() today_str = today.strftime("%d %b") now_str = now.strftime("%H.%M") for key in result_df.keys(): __write_excel_sheet( excel_path, sheet_name=(key + " - " + today_str + " - " + now_str), data_frame=result_df[key] ) def __write_excel_sheet(excel_path, sheet_name, data_frame: dict): data_frame = __convert_result_data_frames(data_frame) if not os.path.isfile(str(excel_path)): wb = Workbook() else: wb = load_workbook(excel_path) if not sheet_name in wb.sheetnames: wb.create_sheet(sheet_name) sheet = wb[sheet_name] col = 2 for key in data_frame.keys(): row = 2 sub_data_frame = data_frame[key] n_sub_element = len(sub_data_frame["unit"]) if key == "Name": column_dimension = 35 elif key == "Stream": column_dimension = 8 else: column_dimension = 20 if n_sub_element == 0: sheet.merge_cells(start_row=row, start_column=col, end_row=row + 1, end_column=col) n_sub_element = 1 else: if n_sub_element > 1: sheet.merge_cells(start_row=row, start_column=col, end_row=row, end_column=col + n_sub_element - 1) for n in range(n_sub_element): row = 3 cell = sheet.cell(row, col + n, value="[" + sub_data_frame["unit"][n] + "]") cell.alignment = styles.Alignment(horizontal="center", vertical="center") cell.font = styles.Font(italic=True, size=10) cell = sheet.cell(2, col, value=key) cell.alignment = styles.Alignment(horizontal="center", vertical="center") cell.font = styles.Font(bold=True) for n in range(n_sub_element): row = 5 data_list = (sub_data_frame["values"])[n][0] sheet.column_dimensions[utils.get_column_letter(col)].width = column_dimension for data in data_list: sheet.cell(row, col, value=data) row += 1 col += 1 wb.save(excel_path) def __convert_result_data_frames(data_frame: dict) -> dict: new_data_frame = dict() for key in data_frame.keys(): sub_dict = __get_sub_dict(key) sub_dict.update({"values": list()}) if not sub_dict["name"] in new_data_frame.keys(): new_data_frame.update({sub_dict["name"]: sub_dict}) else: (new_data_frame[sub_dict["name"]])["unit"].append(sub_dict["unit"][0]) (new_data_frame[sub_dict["name"]])["values"].append([data_frame[key]]) return new_data_frame def __get_sub_dict(key): if "[" in key: parts = key.split("[") name = parts[0].replace("[", "") measure_unit = [parts[1].split("]")[0].replace("]", "")] else: name = key measure_unit = list() return {"name": name, "unit": measure_unit} def __check_excel_version(excel_path): pass
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/API/ExcelAPI/modules_importer.py
modules_importer.py
from EEETools.costants import RES_DIR import os def get_file_position(file_name): file_position = os.path.join(RES_DIR, "Other", file_name) if not os.path.isfile(file_position): try: from EEETools.Tools.Other.resource_downloader import update_resource_folder update_resource_folder() except: return "" return file_position
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/API/Tools/file_handler.py
file_handler.py
from EEETools.MainModules.pf_diagram_generation_module import ArrayHandler import math class SankeyDiagramOptions: def __init__(self): self.generate_on_pf_diagram = False self.show_component_mixers = False self.display_costs = False self.font_size = 15 self.colors = { "Destruction": [150, 0, 0], "Losses": [50, 125, 150], "Default": [250, 210, 20], "Cost": [40, 170, 60], "Components Cost": [110, 200, 255], "Redistributed Cost": [255, 200, 110] } self.opacity = { "nodes": 1, "links": 0.6, "DL_links": 0.25, "Components Cost": 0.1, "Redistributed Cost": 0.20 } self.min_opacity_perc = 0.15 def define_color(self, block_label, is_link, cost_perc=1): return "rgba({}, {})".format(self.get_color(block_label), self.get_opacity(block_label, is_link, cost_perc)) def get_color(self, block_label): if block_label in ["Destruction", "Losses", "Components Cost", "Redistributed Cost"]: color = self.colors[block_label] elif block_label == "Redistributed Cost": return self.get_color("Destruction") else: if self.display_costs: color = self.colors["Cost"] else: color = self.colors["Default"] return "{}, {}, {}".format(color[0], color[1], color[2]) def get_opacity(self, block_label, is_link, cost_perc=1): if not math.isfinite(cost_perc): cost_perc = 1 if is_link: if block_label in ["Destruction", "Losses"]: return self.opacity["DL_links"] * cost_perc elif block_label in ["Redistributed Cost", "Components Cost"]: return self.opacity[block_label] * cost_perc return self.opacity["links"] * cost_perc else: return self.opacity["nodes"] * cost_perc class SankeyDiagramGenerator: def __init__(self, input_array_handler: ArrayHandler, options: SankeyDiagramOptions = SankeyDiagramOptions()): super().__init__() self.options = options self.input_array_handler = input_array_handler self.array_handler = None # ------------------------------------- # ------- Sankey Diagram Methods ------ # ------------------------------------- def show(self): import plotly.graph_objects as go self.__init_sankey_dicts() fig = go.Figure( data=[ go.Sankey( arrangement="snap", node=self.nodes_dict, link=self.link_dict ) ] ) fig.update_layout(title_text="", font_size=self.options.font_size) fig.show() def __init_sankey_dicts(self): self.nodes_dict = { "label": list(), "color": list() } self.link_dict = { "source": list(), "target": list(), "value": list(), "color": list() } if self.options.display_costs: self.input_array_handler.calculate() if self.options.generate_on_pf_diagram: self.array_handler = self.input_array_handler.get_pf_diagram() else: self.array_handler = self.input_array_handler if not self.options.display_costs: self.array_handler.prepare_system() self.__fill_sankey_diagram_dicts() def __fill_sankey_diagram_dicts(self): for conn in self.array_handler.connection_list: from_block_label, to_block_label = self.__get_node_labels_from_connection(conn) if not from_block_label == to_block_label: self.__update_link_dict(from_block_label, to_block_label, conn.exergy_value, conn=conn) if not self.options.display_costs: self.__append_destruction() else: self.__append_redistributed_cost() self.__append_components_cost() def __update_link_dict(self, from_block_label, to_block_label, value, conn=None): self.__check_label(from_block_label) self.__check_label(to_block_label) self.link_dict["source"].append(self.nodes_dict["label"].index(from_block_label)) self.link_dict["target"].append(self.nodes_dict["label"].index(to_block_label)) if not self.options.display_costs: self.link_dict["value"].append(value) self.link_dict["color"].append(self.options.define_color(to_block_label, is_link=True)) else: if "Redistributed Cost" in [to_block_label, from_block_label]: color = self.options.define_color("Redistributed Cost", is_link=True) elif "Components Cost" in [to_block_label, from_block_label]: color = self.options.define_color("Components Cost", is_link=True) else: value = conn.abs_cost rel_cost = conn.rel_cost max_rel_cost = self.__get_maximum_rel_cost() if max_rel_cost == 0: perc = 1 else: perc = rel_cost / max_rel_cost * (1 - self.options.min_opacity_perc) + self.options.min_opacity_perc color = self.options.define_color(to_block_label, is_link=True, cost_perc=perc) self.link_dict["value"].append(value) self.link_dict["color"].append(color) def __check_label(self, label): if label not in self.nodes_dict["label"]: self.nodes_dict["label"].append(label) self.nodes_dict["color"].append(self.options.define_color(label, is_link=False)) def __append_destruction(self): for block in self.array_handler.block_list: from_block_label = self.__get_node_label(block) self.__update_link_dict(from_block_label, "Destruction", block.exergy_balance) def __append_redistributed_cost(self): for block in self.array_handler.block_list: if block.is_dissipative: from_block_label = self.__get_node_label(block) self.__update_link_dict(from_block_label, "Redistributed Cost", block.difference_cost) red_sum = block.redistribution_sum for non_dissipative_blocks in block.redistribution_block_list: to_block_label = self.__get_node_label(non_dissipative_blocks) red_perc = round(non_dissipative_blocks.redistribution_index / red_sum, 2) self.__update_link_dict( "Redistributed Cost", to_block_label, block.difference_cost*red_perc ) def __append_components_cost(self): for block in self.array_handler.block_list: to_block_label = self.__get_node_label(block) self.__update_link_dict("Components Cost", to_block_label, block.comp_cost) def __get_node_labels_from_connection(self, conn): if conn.is_system_output: from_block_label = self.__get_node_label(conn.from_block) if conn.is_loss: to_block_label = "Losses" else: to_block_label = conn.name elif conn.is_system_input: from_block_label = conn.name to_block_label = self.__get_node_label(conn.to_block) else: from_block_label = self.__get_node_label(conn.from_block) to_block_label = self.__get_node_label(conn.to_block) return from_block_label, to_block_label def __get_node_label(self, block): if block.is_support_block: main_block = block.main_block if main_block is not None and not self.options.show_component_mixers: return self.__get_node_label(main_block) else: return "{}".format(block.ID) else: return "{}".format(block.name) def __get_maximum_rel_cost(self): max_rel_cost = 0. for conn in self.array_handler.connection_list: if not conn.is_loss: if conn.rel_cost > max_rel_cost: max_rel_cost = conn.rel_cost return max_rel_cost
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/API/Tools/sankey_diagram_generation.py
sankey_diagram_generation.py
from EEETools.MainModules import ArrayHandler def update_exergy_values(array_handler: ArrayHandler, exergy_list: list) -> ArrayHandler: """ :param array_handler: an array_handler :param exergy_list: a list of dictionaries having the following keys: "index" -> stream index as defined in the array_handler "value" -> exergy value for the specified stream in [kW] :return: the updated array handler """ for stream in exergy_list: connection = array_handler.find_connection_by_index(stream["index"]) connection.exergy_value = stream["value"] return array_handler def get_result_data_frames(array_handler: ArrayHandler) -> dict: if array_handler.options.calculate_component_decomposition: return { "Stream Out": __get_stream_data_frame(array_handler), "Comp Out": __get_comp_data_frame(array_handler), "Cost Dec Out": __get_cost_dec_data_frame(array_handler), "Eff Out": __get_useful_data_frame(array_handler) } else: return { "Stream Out": __get_stream_data_frame(array_handler), "Comp Out": __get_comp_data_frame(array_handler), "Eff Out": __get_useful_data_frame(array_handler) } def get_debug_data_frames(array_handler: ArrayHandler) -> dict: if not array_handler.options.calculate_on_pf_diagram: return { "Main Matrix": __get_main_matrix_data_frame(array_handler), "Connections List": __get_connections_list_data_frame(array_handler) } else: return { "Debug - Matrix": __get_main_matrix_data_frame(array_handler), "Debug - Block": __get_block_list_data_frame(array_handler), "Debug - Connections": __get_connections_list_data_frame(array_handler) } def __get_stream_data_frame(array_handler: ArrayHandler): stream_data = { "Stream": list(), "Name": list(), "Exergy Value [kW]": list(), "Specific Cost [€/kJ]": list(), "Specific Cost [€/kWh]": list(), "Total Cost [€/s]": list() } for conn in array_handler.connection_list: if not conn.is_internal_stream: stream_data["Stream"].append(conn.index) stream_data["Name"].append(conn.name) stream_data["Exergy Value [kW]"].append(conn.exergy_value) stream_data["Specific Cost [€/kJ]"].append(conn.rel_cost) stream_data["Specific Cost [€/kWh]"].append(conn.rel_cost * 3600) stream_data["Total Cost [€/s]"].append(conn.rel_cost * conn.exergy_value) return stream_data def __get_comp_data_frame(array_handler: ArrayHandler): comp_data = { "Name": list(), "Comp Cost [€/s]": list(), "Exergy_fuel [kW]": list(), "Exergy_product [kW]": list(), "Exergy_destruction [kW]": list(), "Exergy_loss [kW]": list(), "Exergy_dl [kW]": list(), "Fuel Cost [€/kWh]": list(), "Fuel Cost [€/s]": list(), "Product Cost [€/kWh]": list(), "Product Cost [€/s]": list(), "Destruction Cost [€/kWh]": list(), "Destruction Cost [€/s]": list(), "eta": list(), "r": list(), "f": list(), "y": list() } block_list = array_handler.blocks_by_index for block in block_list: if not block.is_support_block: comp_data["Name"].append(block.name) comp_data["Comp Cost [€/s]"].append(block.comp_cost) comp_data["Exergy_fuel [kW]"].append(block.exergy_analysis["fuel"]) comp_data["Exergy_product [kW]"].append(block.exergy_analysis["product"]) comp_data["Exergy_destruction [kW]"].append(block.exergy_analysis["distruction"]) comp_data["Exergy_loss [kW]"].append(block.exergy_analysis["losses"]) comp_data["Exergy_dl [kW]"].append(block.exergy_analysis["distruction"] + block.exergy_analysis["losses"]) try: comp_data["Fuel Cost [€/kWh]"].append(block.coefficients["c_fuel"] * 3600) comp_data["Product Cost [€/kWh]"].append(block.output_cost * 3600) comp_data["Destruction Cost [€/kWh]"].append(block.coefficients["c_dest"] * 3600) comp_data["Fuel Cost [€/s]"].append(block.coefficients["c_fuel"] * block.exergy_analysis["fuel"]) comp_data["Product Cost [€/s]"].append(block.output_cost * block.exergy_analysis["product"]) comp_data["Destruction Cost [€/s]"].append( block.coefficients["c_dest"] * ( block.exergy_analysis["distruction"] + block.exergy_analysis["losses"]) ) comp_data["eta"].append(block.coefficients["eta"]) comp_data["r"].append(block.coefficients["r"]) comp_data["f"].append(block.coefficients["f"]) comp_data["y"].append(block.coefficients["y"]) except: comp_data["Fuel Cost [€/kWh]"].append(0) comp_data["Product Cost [€/kWh]"].append(0) comp_data["Destruction Cost [€/kWh]"].append(0) comp_data["Fuel Cost [€/s]"].append(0) comp_data["Product Cost [€/s]"].append(0) comp_data["Destruction Cost [€/s]"].append(0) comp_data["eta"].append(0) comp_data["r"].append(0) comp_data["f"].append(0) comp_data["y"].append(0) return comp_data def __get_cost_dec_data_frame(array_handler: ArrayHandler): cost_dec_data = {"Name": list()} block_list = array_handler.blocks_by_index for block in block_list: if not block.is_support_block: cost_dec_data["Name"].append(block.name) for name in block.output_cost_decomposition.keys(): if name not in cost_dec_data.keys(): cost_dec_data.update({name: list()}) cost_dec_data[name].append(block.output_cost_decomposition[name]) return cost_dec_data def __get_useful_data_frame(array_handler: ArrayHandler): useful_data = { "Stream": list(), "Name": list(), "Exergy Value [kW]": list(), "Specific Cost [€/kJ]": list(), "Specific Cost [€/kWh]": list(), "Total Cost [€/s]": list() } for conn in array_handler.useful_effect_connections: useful_data["Stream"].append(conn.index) useful_data["Name"].append(conn.name) useful_data["Exergy Value [kW]"].append(conn.exergy_value) useful_data["Specific Cost [€/kJ]"].append(conn.rel_cost) useful_data["Specific Cost [€/kWh]"].append(conn.rel_cost * 3600) useful_data["Total Cost [€/s]"].append(conn.rel_cost * conn.exergy_value) return useful_data def __get_main_matrix_data_frame(array_handler: ArrayHandler): if array_handler.options.calculate_on_pf_diagram: array_handler = array_handler.pf_diagram block_list = array_handler.block_list useful_data = {"names": list()} for block in block_list: useful_data.update({"{}-{}".format(block.ID, block.name): list()}) useful_data.update({"constants": list()}) for block in block_list: useful_data["names"].append("{}-{}".format(block.ID, block.name)) useful_data["constants"].append(array_handler.vector[block.ID]) for other_block in block_list: key = "{}-{}".format(other_block.ID, other_block.name) useful_data[key].append(array_handler.matrix[block.ID][other_block.ID]) return useful_data def __get_block_list_data_frame(array_handler: ArrayHandler): if array_handler.options.calculate_on_pf_diagram: array_handler = array_handler.pf_diagram block_list = array_handler.block_list max_con_blocks = 0. for block in block_list: con_blocks = len(block.contained_blocks) if con_blocks > max_con_blocks: max_con_blocks = con_blocks useful_data = { "Block ID": list(), "Name": list(), "Cost [€/s]": list() } for i in range(max_con_blocks): useful_data.update({"{} Cont. Blocks".format(i + 1): list()}) for block in block_list: useful_data["Block ID"].append(block.index) useful_data["Name"].append(block.name) useful_data["Cost [€/s]"].append(block.comp_cost) i = 1 for cont_block in block.contained_blocks: useful_data["{} Cont. Blocks".format(i)].append("{}-{}".format(cont_block.ID, cont_block.name)) i += 1 return useful_data def __get_connections_list_data_frame(array_handler: ArrayHandler): if array_handler.options.calculate_on_pf_diagram: array_handler = array_handler.pf_diagram useful_data = { "Stream": list(), "Name": list(), "From": list(), "To": list(), "Exergy Value [kW]": list() } for conn in array_handler.connection_list: useful_data["Stream"].append(conn.index) useful_data["Name"].append(conn.name) if conn.from_block is not None: useful_data["From"].append("{}-{}".format(conn.from_block.ID, conn.from_block.name)) else: useful_data["From"].append("-") if conn.to_block is not None: useful_data["To"].append("{}-{}".format(conn.to_block.ID, conn.to_block.name)) else: useful_data["To"].append("-") useful_data["Exergy Value [kW]"].append(conn.exergy_value) return useful_data
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/API/Tools/main_tools.py
main_tools.py
from EEETools.Tools.API.Tools.main_tools import get_result_data_frames from EEETools.Tools.Other.fernet_handler import FernetHandler from EEETools.MainModules import ArrayHandler from datetime import date, datetime import os, pandas def calculate_dat(dat_path): array_handler = import_dat(dat_path) array_handler.calculate() write_csv_solution(dat_path, array_handler) def export_dat(dat_path, array_handler: ArrayHandler): fernet = FernetHandler() fernet.save_file(dat_path, array_handler.xml) def import_dat(dat_path) -> ArrayHandler: array_handler = ArrayHandler() fernet = FernetHandler() root = fernet.read_file(dat_path) array_handler.xml = root return array_handler def write_csv_solution(dat_path, array_handler): result_df = get_result_data_frames(array_handler) # generation of time stamps for excel sheet name today = date.today() now = datetime.now() today_str = today.strftime("%d %b") now_str = now.strftime("%H.%M") dir_path = os.path.dirname(dat_path) for key in result_df.keys(): csv_path = key + " - " + today_str + " - " + now_str + ".csv" csv_path = os.path.join(dir_path, csv_path) pandas_df = pandas.DataFrame(data=result_df[key]) pandas_df.to_csv(path_or_buf=csv_path, sep="\t")
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/API/DatAPI/modules_importer.py
modules_importer.py
import win32com.client class UNISIMConnector: def __init__(self, filepath=None): self.app = win32com.client.Dispatch('UnisimDesign.Application') self.__doc = None self.solver = None self.block_names = list() self.stream_names = list() self.open(filepath) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): try: self.doc.Visible = False self.__doc.Close() except: pass self.app.Visible = False self.app.Quit() def get_spreadsheet(self, spreadsheet_name): try: spreadsheet = UNISIMSpreadsheet(self, spreadsheet_name) except: return None return spreadsheet def generate_excel_file(self): pass def show(self): try: self.app.Visible = True self.doc.Visible = True except: pass def open(self, filepath): if self.is_ready: self.__doc.Close() if filepath is None: self.doc = self.app.SimulationCases.Add() else: self.doc = self.app.SimulationCases.Open(filepath) def get_block(self, block_name): if block_name not in self.block_names: return None else: return self.doc.Flowsheet.Operations.Item(block_name) def get_stream(self, stream_name): if stream_name not in self.stream_names: return None else: return self.doc.Flowsheet.Streams.Item(stream_name) @property def doc(self): return self.__doc @doc.setter def doc(self, doc): try: self.solver = doc.Solver except: self.__doc = None self.solver = None self.block_names = list() self.stream_names = list() else: self.__doc = doc self.block_names = self.doc.Flowsheet.Operations.Names self.stream_names = self.doc.Flowsheet.Streams.Names @property def is_ready(self): return self.__doc is not None def wait_solution(self): try: while self.solver.IsSolving: pass except: pass class UNISIMSpreadsheet: def __init__(self, parent:UNISIMConnector, spreadsheet_name): self.parent = parent self.spreadsheet = parent.doc.Flowsheet.Operations.Item(spreadsheet_name) def set_cell_from_list(self, input_list: list): for value_dict in input_list: self.set_cell_value(value_dict["cell name"], value_dict["value"]) def get_value_from_list(self, input_list: list): return_dict = dict() for cell_name in input_list: return_dict.update({cell_name: self.get_cell_value(cell_name)}) def set_cell_value(self, cell_name, value): try: cell = self.spreadsheet.Cell(cell_name) cell.CellValue = value except: pass def get_cell_value(self, cell_name): try: cell = self.spreadsheet.Cell(cell_name) value = cell.CellValue except: return None return value
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/Other/unisim_connect.py
unisim_connect.py
import importlib, inspect from EEETools import costants class Handler: """This is the base class for classes that have to handle a group of subclasses collected in a specific folder: - Import_correct_sub_class method return the correct subclass element from a given name - Other methods are related with handling of the format for module and class names !!!ATTENTION!!! In creating the sub-classes the user must care to overload: - "self.data_folder" variable with the path to the folder containing the subclasses (e.g. "EEETools\BlockSubClasses") - "self.subclass_directory_path" variable variable with the path to the folder containing the subclasses using dots as separators ( e.g. "EEETools.BlockSubClasses") """ def __init__(self): self.current_folder = costants.ROOT_DIR self.data_folder = self.current_folder self.__subclass_directory_path = "" self.__subclass_folder_path = "" @property def subclass_directory_path(self): return self.__subclass_directory_path @subclass_directory_path.setter def subclass_directory_path(self, input_path): self.__subclass_directory_path = input_path self.__subclass_folder_path = input_path + "." def import_correct_sub_class(self, subclass_name): """This method import the correct block subclass. Subclasses modules must be placed inside "EEETools.BlockSubClasses" Package. Subclasses name must be capitalized. In addition, subclass module name must be the same but without capital letters e.g subClasses "Expander" must be in module "expander". The static function called "__get_subclass_module_names" generates from "subclass_name" the correct "__module_name" and "__subclass_name" """ __tmp_result = self.__get_subclass_module_names(subclass_name) __module_name = __tmp_result[0] __subclass_name = __tmp_result[1] __importString = self.__subclass_folder_path + __module_name __blockModule = importlib.import_module(__importString) return getattr(__blockModule, __subclass_name) def get_module_name(self, std_name: str): return self.__get_subclass_module_names(std_name)[0] def check_data_folder(self): pass def list_modules(self) -> list: raw_names = self.__get_raw_names() for i in range(len(raw_names)): name = raw_names[i] if "_" in name: __tmp_list = name.split("_") new_name = __tmp_list[0].capitalize() for __tmp_array in __tmp_list[1:]: new_name += " " + __tmp_array.capitalize() else: new_name = name.capitalize() raw_names[i] = new_name return raw_names def __get_raw_names(self) -> list: member_list = list() __members = inspect.getmembers(importlib.import_module(self.__subclass_directory_path)) for __member in __members: if "__" not in __member[0] and __member[0].islower(): member_list.append(__member[0]) return member_list @staticmethod def get_std_name(input_name: str): # This method performs the reverse operation with respect to "__get_subclass_module_names" module. # "input_name" could have two format: # # "__module_name" format: # # - in case of multi-word names (e.g. "Heat Exchanger") the words is connected by an underscore ("_") # - each word must be lowercase # - for example: "Heat Exchanger" -> "heat_exchanger" # # "__subclass_name" format: # # - in case of multi-word names (e.g. "Heat Exchanger") the space is removed # - each word must be capitalized # - for example: "Heat Exchanger" -> "HeatExchanger" # # The method returns the name in the standard format: # # - in case of multi-word names (e.g. "Heat Exchanger") the words are separeted by a space (" ") # - each word must be capitalized # - for example: "heat_exchanger" -> "Heat Exchanger" # # Whatever the input format the program scrolls the string searching for "_" or for uppercase letters: # # - if "_" is found, it is replaced with a space " " # - if an uppercase letter is found, a space " " is inserted in the string before the letter. # - otherwise the letter is simply copied into "__std_name" string __name_index = list(input_name) __std_name = str(__name_index[0]).capitalize() capitalize_next = False for letter in __name_index[1:]: if letter == "_": __std_name += " " capitalize_next = True elif letter.isupper(): __std_name += " " + str(letter) else: if capitalize_next: __std_name += str(letter).capitalize() capitalize_next = False else: __std_name += str(letter) return __std_name @staticmethod def __get_subclass_module_names(input_name: str): # this method generates from "input_name" the correct "__module_name" and "__subclass_name". # # "__module_name" must have the following format: # # - in case of multi-word names (e.g. "Heat Exchanger") the words must be connected by an underscore ("_") # - each word must be lowercase # - for example: "Heat Exchanger" -> "heat_exchanger" # # "__subclass_name" must have the following format: # # - in case of multi-word names (e.g. "Heat Exchanger") the space must be removed # - each word must be capitalized # - for example: "Heat Exchanger" -> "HeatExchanger" __tmp_list = input_name.split(" ") if len(__tmp_list) == 1: __module_name = input_name.lower() __subclass_name = input_name.lower().capitalize() else: __module_name = __tmp_list[0].lower() __subclass_name = __tmp_list[0].lower().capitalize() for string in __tmp_list[1:]: __module_name += "_" + string.lower() __subclass_name += string.lower().capitalize() return [__module_name.strip(), __subclass_name]
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/Other/handler.py
handler.py
from EEETools.Tools.Other.resource_downloader import update_resource_folder from cryptography.fernet import Fernet from EEETools import costants import xml.etree.ElementTree as ETree import os, base64 class FernetHandler: def __init__(self): self.__fernet_key_path = os.path.join(costants.RES_DIR, "Other", "fernet_key.dat") self.key = self.__initialize_key_value() def __initialize_key_value(self, retrieve_if_necessary=True): """This method retrieve the cryptographic key stored in 'fernet_key.dat' file. If the key file is not present in the local resources, python will try to download it from the firebase storage. If also this last passage fails, probably due to a bad internet connection, the application will trow an exception as such key is mandatory for the calculations """ if os.path.isfile(self.__fernet_key_path): file = open(self.__fernet_key_path, "rb") key = base64.urlsafe_b64encode(file.read()) file.close() elif retrieve_if_necessary: try: update_resource_folder() key = self.__initialize_key_value(retrieve_if_necessary=False) except: raise Exception( "Unable to reach resources, cryptography key can not be retrieved hence the " "application can not be started. Check your internet connection and retry" ) else: raise Exception( "Unable to find resources, cryptography key can not be retrieved hence the " "application can not be started. Check your internet connection and retry" ) return key def read_file(self, file_path): """ This method retrieve the data from the .dat file and convert it back to the original unencrypted xml. The method return an xml tree initialized according to the stored data""" file = open(file_path, "rb") data = file.read() file.close() fernet = Fernet(self.key) data = fernet.decrypt(data) return ETree.fromstring(data) def save_file(self, file_path, root: ETree.Element): """ This method encrypted and save the input xml tree in a .dat file. Encryption is used to prevent users from modifying the file manually without going through the editor. """ str_data = ETree.tostring(root) fernet = Fernet(self.key) str_data = fernet.encrypt(str_data) xml_file = open(file_path, "wb") xml_file.write(str_data) xml_file.close()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/Other/fernet_handler.py
fernet_handler.py
from __future__ import print_function import requests import zipfile import warnings from sys import stdout from os import makedirs from os.path import dirname from os.path import exists class GoogleDriveDownloader: """ Minimal class to download shared files from Google Drive. """ CHUNK_SIZE = 32768 DOWNLOAD_URL = 'https://docs.google.com/uc?export=download' @staticmethod def download_file_from_google_drive(file_id, dest_path, overwrite=False, unzip=False, showsize=False): """ Downloads a shared file from google drive into a given folder. Optionally unzips it. Parameters ---------- file_id: str the file identifier. You can obtain it from the sharable link. dest_path: str the destination where to save the downloaded file. Must be a path (for example: './downloaded_file.txt') overwrite: bool optional, if True forces re-download and overwrite. unzip: bool optional, if True unzips a file. If the file is not a zip file, ignores it. showsize: bool optional, if True print the current download size. Returns ------- None """ destination_directory = dirname(dest_path) if not exists(destination_directory): makedirs(destination_directory) if not exists(dest_path) or overwrite: session = requests.Session() print('Downloading {} into {}... '.format(file_id, dest_path), end='') stdout.flush() response = session.get(GoogleDriveDownloader.DOWNLOAD_URL, params={'id': file_id}, stream=True) token = GoogleDriveDownloader._get_confirm_token(response) if token: params = {'id': file_id, 'confirm': token} response = session.get(GoogleDriveDownloader.DOWNLOAD_URL, params=params, stream=True) if showsize: print() # Skip to the next line current_download_size = [0] GoogleDriveDownloader._save_response_content(response, dest_path, showsize, current_download_size) print('Done.') if unzip: try: print('Unzipping...', end='') stdout.flush() with zipfile.ZipFile(dest_path, 'r') as z: z.extractall(destination_directory) print('Done.') except zipfile.BadZipfile: warnings.warn('Ignoring `unzip` since "{}" does not look like a valid zip file'.format(file_id)) @staticmethod def _get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith('download_warning'): return value return None @staticmethod def _save_response_content(response, destination, showsize, current_size): with open(destination, 'wb') as f: for chunk in response.iter_content(GoogleDriveDownloader.CHUNK_SIZE): if chunk: # filter out keep-alive new chunks f.write(chunk) if showsize: print('\r' + GoogleDriveDownloader.sizeof_fmt(current_size[0]), end=' ') stdout.flush() current_size[0] += GoogleDriveDownloader.CHUNK_SIZE # From https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size @staticmethod def sizeof_fmt(num, suffix='B'): for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return '{:.1f} {}{}'.format(num, unit, suffix) num /= 1024.0 return '{:.1f} {}{}'.format(num, 'Yi', suffix)
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/Other/google_drive_downloader.py
google_drive_downloader.py
from EEETools.Tools.Other.google_drive_downloader import GoogleDriveDownloader as gdd from EEETools.costants import GOOGLE_DRIVE_RES_IDs, ROOT_DIR, RES_DIR from EEETools.version import VERSION import os, shutil def __download_resource_folder(file_position, version, failure_possible): if os.path.exists(file_position): try: shutil.rmtree(file_position) except: pass try: gdd.download_file_from_google_drive( file_id=GOOGLE_DRIVE_RES_IDs[version], dest_path=file_position, overwrite=True, unzip=True ) except: warning_message = "\n\n<----------------- !ERROR! ------------------->\n" warning_message += "Unable to download the resources!\n" warning_message += "Check your internet connection and retry!\n" if not failure_possible: raise RuntimeError(warning_message) else: print(warning_message) def __get_res_version(file_version): res_version = list(GOOGLE_DRIVE_RES_IDs.keys())[-1] for key in GOOGLE_DRIVE_RES_IDs.keys(): if key <= file_version: res_version = key break return res_version def update_resource_folder(file_version=VERSION, failure_possible=True, force_update=False): file_position = os.path.join(ROOT_DIR, "new_res.zip") res_version = __get_res_version(file_version) if force_update: __download_resource_folder(file_position, res_version, failure_possible=False) else: if not os.path.isdir(RES_DIR): __download_resource_folder(file_position, res_version, failure_possible=False) else: __version_file = os.path.join(RES_DIR, "res_version.dat") if not os.path.isfile(__version_file): __download_resource_folder(file_position, res_version, failure_possible=failure_possible) else: with open(__version_file) as file: resource_version = str(file.readline()).strip() if not (resource_version == res_version): __download_resource_folder(file_position, res_version, failure_possible=failure_possible)
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/Other/resource_downloader.py
resource_downloader.py
from scipy.linalg import diagsvd from copy import deepcopy import numpy.linalg class MatrixAnalyzer: def __init__(self, matrix: numpy.ndarray, vector: numpy.ndarray, main_matrix=None, try_system_decomposition=False): self.matrix = deepcopy(matrix) self.vector = vector self.__inv_matrix = None self.re_matrix = self.matrix self.re_vector = self.vector self.main_matrix = main_matrix self.sub_matrix = None self.has_assignment = False self.n_row = self.matrix.shape[0] self.n_col = self.matrix.shape[1] self.elements = list() self.vector_list = None self.columns = MatrixLineList(contains_rows=False) self.rows = MatrixLineList(contains_rows=True) self.__initialize_matrix() self.rows.check() self.columns.check() self.__check_assignments() self.__ill_conditioned_matrix_warning = False self.try_system_decomposition = try_system_decomposition def __initialize_matrix(self): for i in range(self.n_row): row_list = list() for j in range(self.n_col): new_element = MatrixElement(self.matrix[i, j], [i, j]) row_list.append(new_element) self.elements.append(row_list) self.rows.add_to_list(row_list, i) for j in range(self.n_col): col_list = list() for i in range(self.n_row): element = self.elements[i][j] col_list.append(element) self.columns.add_to_list(col_list, j) __tmp_vector_list = list() for i in range(self.n_row): __tmp_vector_list.append(MatrixElement(self.vector[i], [i, -1])) self.vector_list = MatrixColumn(__tmp_vector_list, -1) def __check_assignments(self): for row in self.rows: if row.is_assignment: self.has_assignment = True def solve(self): if self.has_assignment: non_assignment_rows_indices = self.__calculate_assignment() if len(non_assignment_rows_indices) > 0: __return = self.__identify_new_matrix_and_vector(non_assignment_rows_indices) non_solved_columns = self.columns.non_solved self.sub_matrix = MatrixAnalyzer(__return["new_matrix"], __return["new_vector"], self) sub_solution = self.sub_matrix.solve() for i in range(len(non_solved_columns)): non_solved_columns[i].set_solution(sub_solution[i]) else: self.re_matrix, self.re_vector = self.__rearrange_matrix(self.matrix, self.vector) try: sol = self.__std_solve() except: if self.try_system_decomposition: try: A, B = self.__decompose_matrix() sol_prev = self.__svd_solve(A, self.vector) matrix = B matrix_prev = A counter = 0 while True: sol = self.__svd_solve(matrix, self.vector - matrix_prev.dot(sol_prev)) error = abs(numpy.max(numpy.abs(sol_prev - sol)) / numpy.max(sol_prev)) if error < 0.01: break else: sol_prev = (sol + sol_prev) / 2 matrix_tmp = matrix_prev matrix_prev = matrix matrix = matrix_tmp counter += 1 if counter > 100: raise except: sol = self.__lstsq_solve() else: sol = self.__lstsq_solve() for i in range(len(self.columns)): self.columns[i].set_solution(sol[i]) return self.solution def __calculate_assignment(self) -> list: non_assignment_rows_indices = list() for row in self.rows: if row.is_assignment: assignment_elem = row.non_zero_element[0] assignment_vector = self.vector_list.get_from_list(assignment_elem.initial_position[0]) solution = assignment_vector.value / assignment_elem.value assignment_column = self.columns.get_from_list(assignment_elem.initial_position[1]) assignment_column.set_solution(solution) else: non_assignment_rows_indices.append(row.initial_position) return non_assignment_rows_indices def __identify_new_matrix_and_vector(self, non_assignment_rows_indices): # prepare new sub_matrix n_elements = len(non_assignment_rows_indices) new_matrix = numpy.zeros((n_elements, n_elements)) new_vector = self.vector_list.return_numpy_array(indices=non_assignment_rows_indices) i = 0 for column in self.columns: row_element = column.return_numpy_array(indices=non_assignment_rows_indices) if column.is_solved: new_vector -= row_element * column.solution else: new_matrix[:, i] = row_element i += 1 return {"new_matrix": new_matrix, "new_vector": new_vector} def __decompose_matrix(self): m, n = self.matrix.shape u, s, vt = numpy.linalg.svd(self.matrix) s_new = s for i in range(len(s)): if i <= len(s) * 4 / 5: s_new[i] = s[i] else: s_new[i] = 0 s_mat = diagsvd(s_new, m, n) A = u.dot(s_mat).dot(vt) # ext_a = (numpy.min(A), numpy.max(A)) # A = numpy.round(A / (ext_a[1] - ext_a[0]), 3) * (ext_a[1] - ext_a[0]) B = self.matrix - A return A, B def __std_solve(self): new_matrix, new_vector, deleted_rows = self.__identify_empty_lines(self.re_matrix, self.re_vector) self.__inv_matrix = numpy.linalg.inv(new_matrix) sol = self.__inv_matrix.dot(new_vector) return self.__append_zeroes_if_needed(sol, deleted_rows) def __lstsq_solve(self): new_matrix, new_vector, deleted_rows = self.__identify_empty_lines(self.re_matrix, self.re_vector) sol = numpy.linalg.lstsq(new_matrix, new_vector) self.__ill_conditioned_matrix_warning = True return self.__append_zeroes_if_needed(sol[0], deleted_rows) @staticmethod def __svd_solve(matrix, vector): m, n = matrix.shape u, s, vt = numpy.linalg.svd(matrix) r = numpy.linalg.matrix_rank(matrix) s[:r] = 1 / s[:r] s_inv = diagsvd(s, m, n) return vt.T.dot(s_inv).dot(u.T).dot(vector) @staticmethod def __rearrange_matrix(matrix, vector): m, n = matrix.shape new_matrix = numpy.ones((m, n)) new_vector = numpy.ones(m) for i in range(m): row = matrix[i, :] ext_row = (numpy.min(row), numpy.max(row)) if not (ext_row[1] - ext_row[0]) == 0: new_matrix[i, :] = row / (ext_row[1] - ext_row[0]) new_vector[i] = vector[i] / (ext_row[1] - ext_row[0]) else: new_matrix[i, :] = matrix[i, :] new_vector[i] = vector[i] return new_matrix, new_vector @staticmethod def __identify_empty_lines(matrix, vector): m, n = matrix.shape deleted_rows = [] new_matrix = numpy.copy(matrix) new_vector = numpy.copy(vector) for i in range(m): row = matrix[i, :] ext_row = (numpy.min(row), numpy.max(row)) if (ext_row[1] - ext_row[0]) == 0 and ext_row[0] == 0: if vector[i] == 0: del_i = i - len(deleted_rows) new_matrix = numpy.delete(new_matrix, del_i, 0) new_matrix = numpy.delete(new_matrix, del_i, 1) new_vector = numpy.delete(new_vector, del_i) deleted_rows.append(i) else: raise return new_matrix, new_vector, deleted_rows def __append_zeroes_if_needed(self, sol, deleted_rows): for i in deleted_rows: sol = numpy.insert(sol, i, 0) if self.__inv_matrix is not None: m, n = self.__inv_matrix.shape new_row = numpy.zeros(m) new_col = numpy.zeros(n + 1) self.__inv_matrix = numpy.insert(self.__inv_matrix, i, [new_row], axis=0) self.__inv_matrix = numpy.insert(self.__inv_matrix, i, [new_col], axis=1) return sol @property def is_solvable(self): for element in [self.columns.empty_lines, self.columns.dependent_lines, self.rows.empty_lines, self.rows.dependent_lines]: if not len(element) == 0: return False return self.n_row == self.n_col @property def solution(self): sol_vector = numpy.zeros(len(self.vector)) for i in range(len(self.columns)): solution = self.columns[i].solution if solution is not None: sol_vector[i] = solution return sol_vector @property def is_ill_conditioned(self): if self.sub_matrix is None: return self.__ill_conditioned_matrix_warning else: return self.sub_matrix.is_ill_conditioned @property def inverse_matrix(self): return self.__inv_matrix class MatrixElement: def __init__(self, value: float, initial_position: list): self.value = value self.solution = None self.initial_position = initial_position self.row = None self.col = None @property def is_empty(self) -> bool: return self.value == 0 class MatrixLine: def __init__(self, vector, initial_position): self.vector = vector self.module = self.__vector_module() self.initial_position = initial_position self.is_row = None self.solution = None self.non_zero = self.__count_non_zero_elements() def __vector_module(self) -> float: module = 0 for element in self.vector: module += pow(element.value, 2) return pow(module, 0.5) def __count_non_zero_elements(self) -> int: counter = 0 for element in self.vector: if not element.is_empty: counter += 1 return counter def return_numpy_array(self, indices=None) -> numpy.ndarray: if indices is None: return_vector = numpy.zeros(len(self.vector)) for i in range(len(self.vector)): return_vector[i] = self.vector[i].value else: i = 0 return_vector = numpy.zeros(len(indices)) for index in indices: return_vector[i] = self.vector[index].value i += 1 return return_vector def get_from_list(self, initial_position): if self.is_row: i = 1 else: i = 0 for element in self.vector: if element.initial_position[i] == initial_position: return element return None @property def non_zero_element(self): return_list = list() for element in self.vector: if not element.is_empty: return_list.append(element) return return_list @property def is_empty(self): return self.module == 0 @property def dim(self): return len(self.vector) def __gt__(self, other): # enables comparison # self > other return self.module < other.module def __lt__(self, other): # enables comparison # self < other return self.module > other.module def __le__(self, other): return not self.__gt__(other) def __ge__(self, other): return not self.__lt__(other) def __eq__(self, other): if self.dim == other.dim and self.is_row == other.is_row: if self.non_zero == other.non_zero: for i in range(self.dim): if self.vector[i].value / self.module != other.vector[i].value / other.module: return False return True return False class MatrixColumn(MatrixLine): def __init__(self, vector, initial_position): super().__init__(vector, initial_position) self.is_row = False for elem in vector: elem.col = self def set_solution(self, solution): self.solution = solution for elem in self.vector: elem.solution = solution @property def is_solved(self): return self.solution is not None class MatrixRow(MatrixLine): def __init__(self, vector, initial_position): super().__init__(vector, initial_position) self.is_row = True for elem in vector: elem.row = self @property def is_assignment(self): return self.non_zero == 1 class MatrixLineList(list): def __init__(self, contains_rows): super().__init__() self.contains_rows = contains_rows self.empty_lines = list() self.dependent_lines = list() def get_from_list(self, initial_position): for element in self: if element.initial_position == initial_position: return element return None def add_to_list(self, vector, initial_position: int): new_element = self.get_from_list(initial_position) if new_element is None: if self.contains_rows: new_element = MatrixRow(vector, initial_position) else: new_element = MatrixColumn(vector, initial_position) self.append(new_element) return new_element def check(self): self.empty_lines = list() self.dependent_lines = list() for i in range(len(self)): if self[i].is_empty: self.empty_lines.append({i: self[i]}) else: for j in range(i + 1, len(self)): if self[i] == self[j]: self.dependent_lines.append({str(i) + "; " + str(j): [self[i], self[j]]}) @property def non_solved(self): return_list = list() for element in self: if not element.is_solved: return_list.append(element) return return_list @property def sorted_indices(self) -> list: sorted_indices = list() self.sort() for element in self: sorted_indices.append(element.initial_position) return sorted_indices
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/Other/matrix_analyzer.py
matrix_analyzer.py
from EEETools.Tools.Other.fernet_handler import FernetHandler from EEETools.Tools.Other.handler import Handler from abc import ABC, abstractmethod from PyQt5.QtWidgets import QWidget from EEETools import costants import os class AbstractCostCorrelation(ABC): def __init__(self): self.name = "" self.note = "" self.component_type = "" self.fernet_handler = FernetHandler() def import_from_file(self, file_path): """DON'T OVERRIDE THIS METHOD""" data = self.fernet_handler.read_file(file_path) self.import_xml_tree(data) def export_to_file(self, file_path = ""): """DON'T OVERRIDE THIS METHOD""" if file_path == "": correlation_handler = CostCorrelationHandler() file_path = correlation_handler.get_file_path(self) data = self.export_xml_tree() self.fernet_handler.save_file(file_path, data) @abstractmethod def import_xml_tree(self, data): raise NotImplementedError() @abstractmethod def export_xml_tree(self): raise NotImplementedError() @abstractmethod def get_cost(self): raise NotImplementedError() @property def currentCEPCI(self): return self.__current_cepci @currentCEPCI.setter def currentCEPCI(self, input_cepci): self.__current_cepci = input_cepci @property @abstractmethod def parameter_dict(self) -> dict: raise NotImplementedError() @abstractmethod def set_parameters(self, input_dict): raise NotImplementedError() @property @abstractmethod def coefficient_dict(self): raise NotImplementedError() @property @abstractmethod def coefficients(self): raise NotImplementedError() @coefficients.setter @abstractmethod def coefficients(self, input_dict: dict): raise NotImplementedError() @property @abstractmethod def description(self): pass @property @abstractmethod def edit_correlation_widget(self) -> QWidget: raise NotImplementedError() @property @abstractmethod def parameter_settings_widget(self): raise NotImplementedError() class CostCorrelationHandler(Handler): def __init__(self): super().__init__() self.data_folder = os.path.join(costants.ROOT_DIR, "3ETool_res", "Cost Correlation Data") self.subclass_directory_path = "EEETools.Tools.CostCorrelations.CorrelationClasses" from EEETools.Tools.modules_handler import ModulesHandler modules_handler = ModulesHandler() self.name_list = modules_handler.name_list def check_data_folder(self): if not os.path.isdir(self.data_folder): try: os.mkdir(self.data_folder) except: pass for name in self.name_list: folder_name = self.get_module_name(name) name_folder_path = os.path.join(self.data_folder, folder_name) if not os.path.isdir(name_folder_path): try: os.mkdir(name_folder_path) except: pass def open_file(self, file_path): fernet_handler = FernetHandler() data = fernet_handler.read_file(file_path) __header = data.find("header") __correlation_name = __header.get("correlation_class") __subclass = self.import_correct_sub_class(__correlation_name) return __subclass(data) def save_file(self, correlation_class, file_path = ""): if file_path == "": file_path = self.get_file_path(correlation_class) correlation_class.export_to_file(file_path) def get_file_path(self, correlation_class): file_folder = os.path.join(self.data_folder, self.get_module_name(correlation_class.component_type)) if os.path.isdir(file_folder): return os.path.join(file_folder, self.get_module_name(correlation_class.name) + ".dat") else: raise FileNotFoundError @staticmethod def rename_file(new_name, file_path): fernet_handler = FernetHandler() data = fernet_handler.read_file(file_path) header = data.find("header") header.attrib["name"] = new_name fernet_handler.save_file(file_path, data) # <-----------------------------------------> # <------------ SUPPORT CLASSES ------------> # <-----------------------------------------> class Parameter: def __init__(self, input_name): self.name = input_name self.note = "" self.measure_unit = "" self.value = 0. self.__range = Range() @property def range(self): return self.__range @range.setter def range(self, input_range): self.__range.initialize(input_range) class Range: def __init__(self): self.low = 0. self.high = 0. def __str__(self): if self.low == self.high: if self.low == 0: return "" else: return str(self.low) else: return str(self.low) + " - " + str(self.high) def initialize(self, input_range): if type(input_range) is str: input_range = input_range.strip() if input_range == "": self.low = 0. self.high = 0. elif "-" not in input_range: self.low = float(input_range) self.high = float(input_range) else: elements = input_range.split("-") self.low = float(elements[0]) self.high = float(elements[1]) elif type(input_range) is list: self.low = input_range[0] self.high = input_range[1] elif type(input_range) is Range: self.low = input_range.low self.high = input_range.high
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/CostCorrelations/cost_correlation_classes.py
cost_correlation_classes.py
from EEETools.Tools.CostCorrelations.cost_correlation_classes import CostCorrelationHandler from EEETools.Tools.CostCorrelations.cost_correlation_classes import AbstractCostCorrelation from EEETools.Tools.CostCorrelations.cost_correlation_classes import Parameter from EEETools.Tools.GUIElements.gui_base_classes import * from PyQt5.QtGui import QKeySequence, QFont, QDoubleValidator from shutil import copy2 as copy_file from PyQt5.QtWidgets import * from PyQt5.QtCore import Qt import os class CostCorrelationFilesManager(AbstractFilesManager): def __init__(self, flags=None, *args, **kwargs): super().__init__(flags, *args, **kwargs) self.title = "Cost Correlation Manager" self.modules_handler = CostCorrelationHandler() def on_button_add_pressed(self): if not os.path.isdir(self.selected_element_path): self.dir_name = os.path.dirname(self.selected_element_path) else: self.dir_name = self.selected_element_path warning_text = "Select a correlation format" self.add_new_dialog = WarningDialog(self) self.add_new_dialog.set_label_text(warning_text) self.add_new_dialog.set_buttons_on_click(self.on_add_new_dialog_clicked) self.add_combo_box = QComboBox() self.add_combo_box.addItems(self.modules_handler.list_modules()) combo_box_layout = QHBoxLayout() combo_box_layout.addWidget(self.add_combo_box) self.add_new_dialog.set_layout(combo_box_layout) self.add_new_dialog.set_button_text("Add", set_button_yes=True) self.add_new_dialog.set_button_text("Cancel", set_button_yes=False) self.add_new_dialog.show() def on_add_new_dialog_clicked(self): sender = self.sender() if sender.is_yes_button: __sub_class_name = self.add_combo_box.currentText() __sub_class = self.modules_handler.import_correct_sub_class(__sub_class_name)() component_type = self.__get_component_type() __sub_class.component_type = component_type modify_widget = __sub_class.edit_correlation_widget modify_widget.show() self.add_new_dialog.close() def on_button_modify_pressed(self): __sub_class = self.modules_handler.open_file(self.selected_element_path) modify_widget = __sub_class.edit_correlation_widget modify_widget.show() def on_button_delete_pressed(self): dir_name = os.path.dirname(self.selected_element_path) dir_name = os.path.basename(dir_name) filename = os.path.basename(self.selected_element_path) warning_text = "Do you really want to delete file " warning_text += os.path.join(dir_name, filename) warning_text += "?" self.delete_warning_dialog = WarningDialog(self) self.delete_warning_dialog.set_label_text(warning_text) self.delete_warning_dialog.set_buttons_on_click(self.on_delete_warning_clicked) self.delete_warning_dialog.set_button_text("Yes", set_button_yes=True) self.delete_warning_dialog.set_button_text("No", set_button_yes=False) self.delete_warning_dialog.show() def on_delete_warning_clicked(self): sender = self.sender() if sender.is_yes_button: if os.path.exists(self.selected_element_path): os.remove(self.selected_element_path) self.__enable_buttons() self.delete_warning_dialog.close() def on_button_rename_pressed(self): dir_name = os.path.dirname(self.selected_element_path) dir_name = os.path.basename(dir_name) filename = os.path.basename(self.selected_element_path) label_text = "insert new name for file " label_text += os.path.join(dir_name, filename) self.rename_line_edit = QLineEdit() hint_label = QLabel("new name:") hLayout = QHBoxLayout() hLayout.addWidget(hint_label) hLayout.addWidget(self.rename_line_edit) self.rename_warning_dialog = WarningDialog(self) self.rename_warning_dialog.set_layout(hLayout) self.rename_warning_dialog.set_label_text(label_text) self.rename_warning_dialog.set_buttons_on_click(self.on_rename_warning_clicked) self.rename_warning_dialog.set_button_text("Rename", set_button_yes=True) self.rename_warning_dialog.set_button_text("Cancel", set_button_yes=False) self.rename_warning_dialog.show() def on_rename_warning_clicked(self): sender = self.sender() if sender.is_yes_button: new_name = self.rename_line_edit.text() self.__rename_file(new_name, self.selected_element_path) self.__enable_buttons() self.rename_warning_dialog.close() def on_button_duplicate_pressed(self): dir_name = os.path.dirname(self.selected_element_path) dir_name = os.path.basename(dir_name) filename = os.path.basename(self.selected_element_path) warning_text = "Do you really want to duplicate file " warning_text += os.path.join(dir_name, filename) warning_text += "?" self.duplicate_warning_dialog = WarningDialog(self) self.duplicate_warning_dialog.set_label_text(warning_text) self.duplicate_warning_dialog.set_button_text("Yes", set_button_yes=True) self.duplicate_warning_dialog.set_button_text("No", set_button_yes=False) self.duplicate_warning_dialog.set_buttons_on_click(self.on_duplicate_warning_pressed) self.duplicate_warning_dialog.show() def on_duplicate_warning_pressed(self): sender = self.sender() if sender.is_yes_button: if os.path.exists(self.selected_element_path): dir_name = os.path.dirname(self.selected_element_path) filename = os.path.basename(self.selected_element_path) if ".dat" in filename: filename = filename.split(".dat")[0] file_extension = ".dat" elif ".xml" in filename: filename = filename.split(".xml")[0] file_extension = ".xml" else: file_extension = "" i = 1 new_path = os.path.join(dir_name, filename + "(1)" + file_extension) while os.path.exists(new_path): i += 1 new_path = os.path.join(dir_name, filename + "(" + str(i) + ")" + file_extension) copy_file(self.selected_element_path, new_path) self.duplicate_warning_dialog.close() def __rename_file(self, new_name, file_path): self.modules_handler.rename_file(new_name, file_path) super(CostCorrelationFilesManager, self).__rename_file(new_name, file_path) def __get_component_type(self): if not os.path.isdir(self.selected_element_path): dir_name = os.path.dirname(self.selected_element_path) else: dir_name = self.selected_element_path return os.path.basename(dir_name) class BaseEditCorrelationWidget(QDialog): def __init__(self, cost_correlation_class: AbstractCostCorrelation): super().__init__() self.title = "" self.cost_correlation = cost_correlation_class self.tab_widget = BaseEditCorrelationTabWidget() self.buttons_layout = QHBoxLayout() self.button_save = QPushButton() self.button_new = QPushButton() self.layout_is_set = False def show(self): if not self.layout_is_set: self.__init_main_layout() super(BaseEditCorrelationWidget, self).show() def enable_buttons(self): self.button_save.setEnabled(self.is_ready_for_saving) def __init_main_layout(self): self.setWindowTitle(self.title) self.__init_button_layout() __button_widget = QWidget() __button_widget.setLayout(self.buttons_layout) main_layout = QVBoxLayout() main_layout.addWidget(self.tab_widget) main_layout.addWidget(__button_widget) self.setLayout(main_layout) self.layout_is_set = True def __init_tab_layout(self): self.coefficient_widget = CoefficientWidget(self.cost_correlation.coefficient_dict, self) def __init_button_layout(self): self.button_save.setText("Save (CTRL-S)") self.button_save.clicked.connect(self.on_button_pressed) self.button_new.setText("New (CTRL-N)") self.button_new.clicked.connect(self.on_button_pressed) self.__set_buttons_shortcut() self.buttons_layout = QHBoxLayout() self.buttons_layout.addWidget(self.button_save) self.buttons_layout.addWidget(self.button_new) self.enable_buttons() def __set_buttons_shortcut(self): sequence_save = QKeySequence(Qt.CTRL + Qt.Key_S) self.button_save.setShortcut(sequence_save) sequence_new = QKeySequence(Qt.CTRL + Qt.Key_N) self.button_new.setShortcut(sequence_new) @property def is_ready_for_saving(self): """method to be overloaded""" return False # <-------------------------------------------------> # <------------ BUTTON ON CLICK METHODS ------------> # <-------------------------------------------------> def on_button_pressed(self): sender = self.sender() if "Save" in sender.text(): warning_text = "Do you want to save the file? Data will be overwritten" self.on_click_function = self.__save else: warning_text = "By clicking \"Continue\" all your progress will be lost" self.on_click_function = self.__reset_dialog self.warning_dialog = WarningDialog(self) self.warning_dialog.set_label_text(warning_text) self.warning_dialog.set_buttons_on_click(self.on_warning_clicked) self.warning_dialog.set_button_text("Continue", set_button_yes=True) self.warning_dialog.set_button_text("Cancel", set_button_yes=False) self.warning_dialog.show() def on_warning_clicked(self): sender = self.sender() if sender.is_yes_button: self.on_click_function() self.warning_dialog.close() def __save(self): self.__update() self.cost_correlation.export_to_file() def __reset_dialog(self): raise NotImplementedError def __update(self): raise NotImplementedError # <-------------------------------------------------> # <------------ WIDGETS GETTER AND SETTER -----------> # <-------------------------------------------------> @property def header_widget(self): return self.tab_widget.tab_main @header_widget.setter def header_widget(self, input_widget): self.tab_widget.add_widget(input_widget, "Main") @property def parameter_widget(self): return self.tab_widget.tab_parameters @parameter_widget.setter def parameter_widget(self, input_widget): self.tab_widget.add_widget(input_widget, "Parameters") @property def coefficient_widget(self): return self.tab_widget.tab_coefficient @coefficient_widget.setter def coefficient_widget(self, input_widget): self.tab_widget.add_widget(input_widget, "Coefficients") class BaseEditCorrelationTabWidget(QTabWidget): def __init__(self): super().__init__() self.tab_main = None self.tab_parameters = None self.tab_coefficient = None def add_widget(self, widget: QWidget, widget_type): found = True if widget_type == "Main" and self.tab_main is None: self.tab_main = widget elif widget_type == "Parameters" and self.tab_parameters is None: self.tab_parameters = widget elif widget_type == "Coefficients" and self.tab_coefficient is None: self.tab_coefficient = widget else: found = False if found: self.addTab(widget, widget_type) class ParametersWidget(QWidget): def __init__(self, parameter_dict: dict, parent_class: BaseEditCorrelationWidget): super().__init__() self.splitter = QSplitter() self.parameter_dict = parameter_dict self.list_view = None self.parameters_widgets = dict() def init_layout(self): self.list_view = QListView() self.list_view.clicked.connect(self.__on_list_view_clicked) row = 0 for key in self.parameter_dict.keys(): self.list_view.insertItem(row, key) row += 1 # # def __on_list_view_clicked(self): # # # # def __show_currect_widget(self, item_key: str): # # @property def is_ready_for_saving(self): for edit_text in [self.unit_edit, self.note_edit, self.range_low_edit, self.range_high_edit]: if edit_text.text() == "": return False return True class SingleParameterWidget(QWidget): def __init__(self, parameter_class: Parameter, parent_class: BaseEditCorrelationWidget): super().__init__() self.set_edit_layout = False self.parameter = parameter_class self.parent_class = parent_class self.main_layout = QVBoxLayout() self.grid_layout = QGridLayout() def init_layout(self): if self.set_edit_layout: self.__init_edit_objects() self.__init_edit_layout() else: self.__init_set_objects() self.__init_set_layout() self.setLayout(self.main_layout) def __init_edit_objects(self): self.unit_edit = QLineEdit() self.note_edit = QTextEdit() self.range_low_edit = QLineEdit() self.range_high_edit = QLineEdit() self.range_low_edit.setValidator(QDoubleValidator()) self.range_high_edit.setValidator(QDoubleValidator()) self.unit_edit.setText(self.parameter.measure_unit) self.note_edit.setText(self.parameter.note) self.range_low_edit.setText(str(self.parameter.range.low)) self.range_high_edit.setText(str(self.parameter.range.high)) self.unit_edit.setObjectName("unit_edit") self.note_edit.setObjectName("note_edit") self.range_low_edit.setObjectName("range_low_edit") self.range_high_edit.setObjectName("range_high_edit") self.unit_edit.textChanged.connect(self.on_text_edit_change) self.note_edit.textChanged.connect(self.on_text_edit_change) self.range_low_edit.textChanged.connect(self.on_text_edit_change) self.range_high_edit.textChanged.connect(self.on_text_edit_change) def __init_set_objects(self): self.value_edit = QLineEdit() self.unit_edit = QLabel() self.note_edit = QLabel() self.range_low_edit = QLabel() self.range_high_edit = QLabel() self.note_edit.setWordWrap(True) self.value_edit.setObjectName("value_edit") self.value_edit.textChanged.connect(self.on_text_edit_change) self.value_edit.setValidator(QDoubleValidator()) self.value_edit.setText(str(self.parameter.value)) self.unit_edit.setText(self.parameter.measure_unit) self.note_edit.setText(self.parameter.note) self.range_low_edit.setText(str(self.parameter.range.low)) self.range_high_edit.setText(str(self.parameter.range.high)) def __init_edit_layout(self): # <----------- FIRST ROW -----------> title_label_input = QLabel() title_label_input.setText(self.parameter.name) title_label_input.setFont(QFont('Helvetica 30 bold')) self.grid_layout.addWidget(title_label_input, 0, 0) # <----------- SECOND ROW -----------> measure_unit_label = QLabel() measure_unit_label.setText("Measurement Unit") self.grid_layout.addWidget(measure_unit_label, 1, 0) self.grid_layout.addWidget(self.unit_edit, 1, 1) # <----------- THIRD ROW -----------> range_label = QLabel() range_label.setText("Range") range_layout = QHBoxLayout() range_layout.addWidget(self.range_low_edit) range_layout.addWidget(QLabel("->")) range_layout.addWidget(self.range_high_edit) range_widget = QWidget() range_widget.setLayout(range_layout) self.grid_layout.addWidget(range_label, 2, 0) self.grid_layout.addWidget(range_widget, 2, 1) # <----------- FINAL ROW -----------> grid_layout_widget = QWidget() grid_layout_widget.setLayout(self.grid_layout) self.main_layout.addWidget(grid_layout_widget) self.main_layout.addWidget(self.note_edit) def __init_set_layout(self): # <----------- FIRST ROW -----------> title_label_input = QLabel() title_label_input.setText(self.parameter.name) title_label_input.setFont(QFont('Helvetica 30 bold')) self.grid_layout.addWidget(title_label_input, 0, 0) # <----------- SECOND ROW -----------> measure_unit_label = QLabel() measure_unit_label.setText("Measurement Unit") self.grid_layout.addWidget(measure_unit_label, 1, 0) self.grid_layout.addWidget(self.unit_edit, 1, 1) # <----------- THIRD ROW -----------> range_label = QLabel() range_label.setText("Range") range_layout = QHBoxLayout() range_layout.addWidget(self.range_low_edit) range_layout.addWidget(QLabel("->")) range_layout.addWidget(self.range_high_edit) range_widget = QWidget() range_widget.setLayout(range_layout) self.grid_layout.addWidget(range_label, 2, 0) self.grid_layout.addWidget(range_widget, 2, 1) # <----------- FINAL ROW -----------> grid_layout_widget = QWidget() grid_layout_widget.setLayout(self.grid_layout) self.main_layout.addWidget(grid_layout_widget) self.main_layout.addWidget(self.note_edit) def on_text_edit_change(self): name = self.sender().objectName() if name == "value_edit": try: self.parameter.value = float(self.value_edit.text()) except: self.parameter.value = 0.0 elif name == "unit_edit": self.parameter.measure_unit = self.unit_edit.text() elif name == "note_edit": self.parameter.note = self.note_edit.toPlainText() elif name == "range_low_edit" or name == "range_high_edit": try: low = float(self.range_low_edit.text()) except: low = 0.0 try: high = float(self.range_high_edit.text()) except: high = 0.0 self.parameter.range.initialize([low, high]) self.parent_class.enable_buttons() @property def is_ready_for_saving(self): for edit_text in [self.unit_edit, self.note_edit, self.range_low_edit, self.range_high_edit]: if edit_text.text() == "": return False return True class CoefficientWidget(QWidget): def __init__(self, coefficient_dict: dict, parent_class: BaseEditCorrelationWidget): super().__init__() self.coefficient_dict = coefficient_dict self.parent_class = parent_class self.main_layout = QGridLayout() self.widget_dict = dict() self.__init_layout() def __init_layout(self): row = 0 for key in self.coefficient_dict.keys(): self.__extend_grid_layout(key, row) row += 1 self.setLayout(self.main_layout) def __extend_grid_layout(self, key, row): col = 1 coefficient = self.coefficient_dict[key] title_label_input = QLabel() title_label_input.setText("<b>"+ key + ":<b>") title_label_input.setAlignment(Qt.AlignRight) self.grid_layout.addWidget(title_label_input, row, col) i = 0 col += 1 first_col = col edit_test_list = list() while i < coefficient["array size"]: col = first_col + i edit_text = QLineEdit() edit_text.setValidator(QDoubleValidator()) edit_text.textChanged.connect(self.on_text_edit_change) edit_test_list.append(edit_text) self.grid_layout.addWidget(edit_text, row, col) i += 1 self.widget_dict.update({key: edit_test_list}) def on_text_edit_change(self): self.parent_class.enable_buttons() @property def coefficient_values(self): return_dict = dict() for key in self.widget_dict.keys(): return_list = list() for edit_text in self.widget_dict[key]: try: return_list.append(float(edit_text.text())) except: return_list.append(0.0) return_dict.update({key: return_list}) return return_dict @property def is_ready_for_saving(self): for key in self.widget_dict.keys(): for edit_text in self.widget_dict[key]: if edit_text.text() == "": return False return True
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/CostCorrelations/cost_correlation_gui.py
cost_correlation_gui.py
from .turton_correlation import TurtonCorrelation
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/CostCorrelations/CorrelationClasses/__init__.py
__init__.py
from EEETools.Tools.CostCorrelations.cost_correlation_classes import AbstractCostCorrelation from EEETools.Tools.CostCorrelations.cost_correlation_classes import Parameter from EEETools.Tools.CostCorrelations.cost_correlation_gui import BaseEditCorrelationWidget from EEETools.Tools.CostCorrelations.cost_correlation_gui import CoefficientWidget from EEETools.Tools.CostCorrelations.cost_correlation_gui import ParametersWidget from PyQt5.QtGui import QFont, QDoubleValidator import xml.etree.ElementTree as ETree from PyQt5.QtWidgets import * import math class TurtonCorrelation(AbstractCostCorrelation): def __init__(self, correlation_data=None): super().__init__() self.name = "" self.note = "" self.material = "Carbon Steel" self.component_type = "" self.__A = Parameter("A") self.__P = Parameter("P") self.__K = list() self.__C = list() self.__B = list() self.__F_m = 0. self.__current_cepci = 0 self.__correlation_cepci = None self.is_imported_from_file = False if correlation_data is not None: self.import_xml_tree(correlation_data) def get_cost(self): # This correlation format is extracted from: Turton, R, Bailie, R C, & Whiting, W B. "Analysis, synthesis and # design of chemical processes" Appendix A - pg.924. # # Once calculated, the cost value value is actualized using the CEPCI value relation CP_0 = self.__K[0] CP_0 += self.__K[1] * math.log10(self.__A.value) CP_0 += self.__K[2] * math.pow(math.log10(self.__A.value), 2) CP_0 = math.pow(10, CP_0) F_p = self.__get_F_p_coefficient() F_m = self.__F_m C_BM = CP_0 * (self.__B[0] + self.__B[1] * F_p * F_m) return C_BM * self.__current_cepci / self.__correlation_cepci def __get_F_p_coefficient(self): # If the material IS NOT carbon steel other parameters are required: # # - C[0], C[1] and C[2] are interpolation parameters and could be retrieved in Turton book # - __P.value is pressure value as defined in the correlation description # - F_p is the pressure factor defined according to the equipment type F_p = self.__C[0] F_p += self.__C[1] * math.log10(self.__P.value) F_p += self.__C[2] * math.pow(math.log10(self.__P.value), 2) return math.pow(10, F_p) @property def parameter_dict(self): param_dict = {"A": self.__A, "P": self.__P} return param_dict def set_parameters(self, input_dict: dict): if "A" in input_dict.keys(): self.__A.value = input_dict["A"] if "P" in input_dict.keys(): self.__P.value = input_dict["P"] @property def coefficient_dict(self): coefficients = {"corr_CEPCI": {"array size": 1, "is optional": False}, "F_m": {"array size": 1, "is optional": False}, "K": {"array size": 3, "is optional": False}, "C": {"array size": 3, "is optional": False}, "B": {"array size": 2, "is optional": True}} return coefficients @property def coefficients(self): return {"curr_CEPCI": [self.__correlation_cepci], "F_m": [self.__F_m], "K": self.__K, "C": self.__C, "B": self.__B} @coefficients.setter def coefficients(self, input_dict: dict): if "corr_CEPCI" in input_dict.keys(): self.__correlation_cepci = input_dict["corr_CEPCI"][0] if "F_m" in input_dict.keys(): self.__F_m = input_dict["F_m"][0] if "K" in input_dict.keys(): self.__K = input_dict["K"] if "C" in input_dict.keys(): self.__C = input_dict["C"] if "B" in input_dict.keys(): self.__B = input_dict["B"] @property def description(self): return "" @property def edit_correlation_widget(self) -> QWidget: return TurtonEditCorrelationWidget(self) @property def parameter_settings_widget(self): return None def import_xml_tree(self, data: ETree.Element): header = data.find("header") self.name = header.get("name") self.component_type = header.get("component_type") self.note = header.get("note") parametersList = data.findall("parameter") for parameter in parametersList: __tmp_parameter = Parameter() __tmp_parameter.measure_unit = parameter.get("measure_unit") __tmp_parameter.range = parameter.get("range") __tmp_parameter.note = parameter.get("note") param_dict = {parameter.get("name"): __tmp_parameter} self.set_parameters(param_dict) coefficientsList = data.findall("coefficient") for coefficient in coefficientsList: __tmp_list = list() for element in coefficient.findall("element"): __tmp_list.append(float(element.get("value"))) coeff_dict = {coefficient.get("name"): __tmp_list} self.coefficients = coeff_dict @property def export_xml_tree(self): # This class save the correlation data to a .dat file containing an encrypted xml tree. Encryption is useful in # order to prevent the user from modifying the file manually without going through the editor. # # The method generate the xml tree and pass it to the "export_to_file" method that is in charge of the actual # encryption and file saving processes. # # here is an example of turton correlation xml file: # # <data> # # <header # # correlation_class = "Turton Correlation" # name = "standard" # component_type = "Heat Exchanger" # note = "Plate Heat Exchanger" # # ></header> # # <parameters> # # <parameter # # name = "A" # measure_unit = "m^2" # range = "30-60" # note = "Heat Exchanger Area" # # ></parameter> # # <parameter # # name = "P" # measure_unit = "kPa" # range = "300-1000" # note = "Mean Pressure" # # ></parameter> # # </parameters> # # <coefficients> # # <coefficient name = "corr_CEPCI"> # # <element value = 357> # # </coefficient> # # <coefficient name = "K"> # # <element value = 1.2039> # <element value = 5.6434> # <element value = 0.0353> # # </coefficient> # # <coefficient name = "C"> # # <element value = 3.4510"> # <element value = 0.7601"> # <element value = 0.0032"> # # </coefficient> # # <coefficient name = "B"> # # <element value = 0.0012"> # <element value = 3.4550"> # # </coefficient> # # </coefficients> # # </data> data = ETree.Element("data") # <--------- HEADER DEFINITION ---------> header = ETree.SubElement(data, "header") correlation_name = self.name correlation_note = self.note component_type = self.component_type header.set("correlation_class", "Turton Correlation") header.set("name", correlation_name) header.set("component_type", component_type) header.set("note", correlation_note) # <--------- PARAMETERS DEFINITION ---------> parameters = ETree.SubElement(data, "parameters") for key in self.parameter_dict.keys(): parameter = ETree.SubElement(parameters, "parameter") parameter.set("name", key) parameter.set("measure_unit", self.parameter_dict[key].measure_unit) parameter.set("range", str(self.parameter_dict[key].range)) parameter.set("note", str(self.parameter_dict[key].note)) # <--------- COEFFICIENTS DEFINITION ---------> coefficients = ETree.SubElement(data, "coefficients") for key in self.coefficients.keys(): coefficient = ETree.SubElement(coefficients, "coefficient") coefficient.set("name", key) for element_value in self.coefficients[key]: element = ETree.SubElement(coefficient, "element") element.set("value", str(element_value)) return data class TurtonEditCorrelationWidget(BaseEditCorrelationWidget): def __init__(self, cost_correlation_class: AbstractCostCorrelation): super().__init__(cost_correlation_class) self.title = "Turton Cost Correlation" self.header_widget = None self.parameter_widget_dict = dict() self.__set_header_layout() self.__set_parameter_layout() def __update(self): coeff_dict = dict() for key in self.coefficient_widget_dict.keys(): coeff_dict.update(self.coefficient_widget_dict[key].coefficient_dict) self.cost_correlation.coefficients = coeff_dict def __reset_dialog(self): self.header_widget.component_type_combo.setEnabled(True) @property def is_ready_for_saving(self): for sel_dict in [self.parameter_widget_dict]: for key in sel_dict.keys(): if not sel_dict[key].is_ready_for_saving: return False return self.header_widget.is_ready_for_saving def __set_header_layout(self): widget = TurtonHeaderWidget(self) widget.set_edit_layout = True widget.init_layout() self.header_widget = widget def __set_parameter_layout(self): parameter_dict = self.cost_correlation.parameter_dict parameter_layout = QHBoxLayout() for key in parameter_dict.keys(): widget = ParametersWidget(parameter_dict[key], self) widget.set_edit_layout = True widget.init_layout() self.parameter_widget_dict.update({key: widget}) parameter_layout.addWidget(widget) parameter_widget = QWidget() parameter_widget.setLayout(parameter_layout) self.parameter_widget = parameter_widget class TurtonHeaderWidget(QWidget): def __init__(self, parent_class: TurtonEditCorrelationWidget): super().__init__(None) self.correlation = parent_class.cost_correlation self.set_edit_layout = False self.parent_class = parent_class self.main_layout = QVBoxLayout() self.grid_layout = QGridLayout() def init_layout(self): if self.set_edit_layout: self.__init_edit_objects() self.__init_edit_layout() else: self.__init_set_objects() self.__init_set_layout() self.setLayout(self.main_layout) def __init_edit_objects(self): self.name_edit = QLineEdit() self.note_edit = QTextEdit() self.component_type_combo = QComboBox() self.name_edit.setText(self.correlation.name) self.note_edit.setText(self.correlation.note) from EEETools.Tools.modules_handler import ModulesHandler modules_handler = ModulesHandler() self.component_type_combo.addItems(modules_handler.name_list) self.component_type_combo.setEnabled(False) if not self.correlation.component_type == "": component_type = self.correlation.component_type self.component_type_combo.setCurrentIndex(modules_handler.get_name_index(component_type)) else: self.component_type_combo.setCurrentIndex(0) self.name_edit.setObjectName("name_edit") self.note_edit.setObjectName("note_edit") self.component_type_combo.setObjectName("component_type_combo") self.name_edit.textChanged.connect(self.on_text_edit_change) self.note_edit.textChanged.connect(self.on_text_edit_change) self.component_type_combo.currentTextChanged.connect(self.on_text_edit_change) def __init_set_objects(self): self.curr_cepci_edit = QLineEdit() self.name_edit = QLabel() self.note_edit = QLabel() self.component_type_combo = QLabel() self.note_edit.setWordWrap(True) self.curr_cepci_edit.setValidator(QDoubleValidator()) self.curr_cepci_edit.setObjectName("curr_cepci_edit") self.curr_cepci_edit.textChanged.connect(self.on_text_edit_change) self.note_edit.setText(self.correlation.name) self.note_edit.setText(self.correlation.note) self.note_edit.setText(self.correlation.component_type) def __init_edit_layout(self): # <----------- FIRST ROW -----------> name_label = QLabel() name_label.setText("Correlation Name:") self.grid_layout.addWidget(name_label, 0, 0) self.grid_layout.addWidget(self.name_edit, 0, 1) # <---------- SECOND ROW -----------> component_type_label = QLabel() component_type_label.setText("Component Type:") self.grid_layout.addWidget(component_type_label, 1, 0) self.grid_layout.addWidget(self.component_type_combo, 1, 1) # <----------- FINAL ROW -----------> grid_layout_widget = QWidget() grid_layout_widget.setLayout(self.grid_layout) self.main_layout.addWidget(grid_layout_widget) self.main_layout.addWidget(self.note_edit) def __init_set_layout(self): # <----------- FIRST ROW -----------> name_label = QLabel() name_label.setText("Correlation Name:") self.grid_layout.addWidget(name_label, 0, 0) self.grid_layout.addWidget(self.name_edit, 0, 1) # <---------- SECOND ROW -----------> component_type_label = QLabel() component_type_label.setText("Component Type:") self.grid_layout.addWidget(component_type_label, 1, 0) self.grid_layout.addWidget(self.component_type_combo, 1, 1) # <---------- THIRD ROW -----------> curr_cepci_label = QLabel() curr_cepci_label.setText("Current CEPCI:") self.grid_layout.addWidget(curr_cepci_label, 2, 0) self.grid_layout.addWidget(self.curr_cepci_edit, 2, 1) # <----------- FINAL ROW -----------> grid_layout_widget = QWidget() grid_layout_widget.setLayout(self.grid_layout) self.main_layout.addWidget(grid_layout_widget) self.main_layout.addWidget(self.note_edit) def on_text_edit_change(self): name = self.sender().objectName() if name == "curr_cepci_edit": self.correlation.currentCEPCI = float(self.curr_cepci_edit.text()) elif name == "name_edit": self.correlation.name = self.note_edit.text() elif name == "note_edit": self.correlation.note = self.note_edit.toPlainText() elif name == "component_type_combo": self.correlation.component_type = self.component_type_combo.currentText() self.parent_class.enable_buttons() @property def is_ready_for_saving(self): for edit_text in [self.name_edit, self.note_edit]: if edit_text.text() == "": return False return True
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/CostCorrelations/CorrelationClasses/turton_correlation.py
turton_correlation.py
from EEETools.MainModules.main_module import ArrayHandler from pyvis.network import Network def display_network(array_handler: ArrayHandler): network = Network(height='750px', width='100%', bgcolor='#222222', font_color='white') network.barnes_hut() for block in array_handler.block_list: if not block.is_support_block: network.add_node(block.ID, label="{} - {}".format(block.ID, block.name)) for conn in array_handler.connection_list: if not conn.is_system_input and not conn.is_system_output and not conn.is_internal_stream: from_block_ID = conn.from_block.get_main_ID to_block_ID = conn.to_block.get_main_ID network.add_edge(from_block_ID, to_block_ID) network.show('topology.html')
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/GUIElements/net_plot_modules.py
net_plot_modules.py
from EEETools.MainModules.main_module import ArrayHandler from EEETools.Tools.GUIElements.gui_base_classes import * from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import * from PyQt5.QtGui import QFont from PyQt5.QtCore import Qt import sys class CheckConnectionWidget(QDialog): # noinspection PyArgumentList def __init__(self, array_hander: ArrayHandler): super().__init__() self.array_hander = array_hander self.setWindowTitle("Topology Inspection Window") self.main_layout = QVBoxLayout(self) self.__init_tab_widget() self.setLayout(self.main_layout) self.__update_tab("Blocks") self.__update_tab("Connections") def __init_tab_widget(self): self.tab_widget = QTabWidget() self.__init_tab_block() self.__init_tab_connection() self.main_layout.addWidget(self.tab_widget) def __init_tab_block(self): self.tab_block = QWidget() self.tab_block_layout = QVBoxLayout() self.__init_block_h_layout(0) self.__init_block_h_layout(1) self.__init_block_h_layout(2) self.__init_block_h_layout(3) self.tab_block.setLayout(self.tab_block_layout) self.tab_widget.addTab(self.tab_block, "Blocks") def __init_block_h_layout(self, layout_layer): h_layout_new = QHBoxLayout() if layout_layer == 0: name_label = QLabel("Block ID") name_label.setFont(QFont("Helvetica 20")) name_label.setMinimumWidth(100) name_label.setMaximumWidth(100) self.block_ID_combobox = QComboBox() for ID in self.array_hander.standard_block_IDs: self.block_ID_combobox.addItem(str(ID)) self.block_ID_combobox.currentIndexChanged.connect(self.on_combo_box_changed) self.block_ID_combobox.setFont(QFont("Helvetica 20 Bold")) h_layout_new.addWidget(name_label) h_layout_new.addWidget(self.block_ID_combobox) elif layout_layer == 1: name_label = QLabel("Block Name:") name_label.setFont(QFont("Helvetica 20")) name_label.setMinimumWidth(100) name_label.setMaximumWidth(100) self.name_label = QLabel("Block Name") self.name_label.setFont(QFont("Helvetica 20 Bold")) h_layout_new.addWidget(name_label) h_layout_new.addWidget(self.name_label) elif layout_layer == 2: name_label = QLabel("Block Type:") name_label.setFont(QFont("Helvetica 20")) name_label.setMinimumWidth(100) name_label.setMaximumWidth(100) self.type_label = QLabel("Block Type") self.type_label.setFont(QFont("Helvetica 20 Bold")) h_layout_new.addWidget(name_label) h_layout_new.addWidget(self.type_label) else: h_layout_new.addLayout(self.__init_connections_tablesview()) self.tab_block_layout.addLayout(h_layout_new) def __init_connections_tablesview(self): self.tables = dict() v_layout_right = QVBoxLayout() v_splitter = QSplitter(Qt.Vertical) v_splitter = self.init_table_view(v_splitter, "Input Connections") v_splitter = self.init_table_view(v_splitter, "Output Connections") v_layout_right.addWidget(v_splitter) return v_layout_right def init_table_view(self, layout, title_str): widget = QWidget() v_layout = QVBoxLayout() title_label_input = QLabel(title_str) title_label_input.setFont(QFont('Helvetica 30 bold')) new_table = CheckerAbstractTable(self, title_str) header = new_table.horizontalHeader() header.setSectionResizeMode(0, QHeaderView.Stretch) header.setSectionResizeMode(1, QHeaderView.ResizeToContents) v_layout.addWidget(title_label_input) v_layout.addWidget(new_table) widget.setLayout(v_layout) layout.addWidget(widget) self.tables.update({title_str: new_table}) return layout def __init_tab_connection(self): self.tab_connection = QWidget() self.tab_conn_layout = QVBoxLayout() self.__init_conn_h_layout(0) self.__init_conn_h_layout(1) self.__init_conn_h_layout(2) self.__init_conn_h_layout(3) self.tab_connection.setLayout(self.tab_conn_layout) self.tab_widget.addTab(self.tab_connection, "Connections") def __init_conn_h_layout(self, layout_layer): h_layout_new = QHBoxLayout() if layout_layer == 0: name_label = QLabel("Conn ID") name_label.setFont(QFont("Helvetica 20")) name_label.setMinimumWidth(100) name_label.setMaximumWidth(100) self.conn_ID_combobox = QComboBox() for ID in self.array_hander.standard_conn_IDs: self.conn_ID_combobox.addItem(str(ID)) self.conn_ID_combobox.currentIndexChanged.connect(self.on_combo_box_changed) self.conn_ID_combobox.setFont(QFont("Helvetica 20 Bold")) h_layout_new.addWidget(name_label) h_layout_new.addWidget(self.conn_ID_combobox) elif layout_layer == 1: name_label = QLabel("Conn Name:") name_label.setFont(QFont("Helvetica 20")) name_label.setMinimumWidth(100) name_label.setMaximumWidth(100) self.conn_name_label = QLabel("Conn Name") self.conn_name_label.setFont(QFont("Helvetica 20 Bold")) h_layout_new.addWidget(name_label) h_layout_new.addWidget(self.conn_name_label) elif layout_layer == 2: name_label = QLabel("From Block:") name_label.setFont(QFont("Helvetica 20")) name_label.setMinimumWidth(100) name_label.setMaximumWidth(100) self.from_block_label = QLabel("From Block:") self.from_block_label.setFont(QFont("Helvetica 20 Bold")) h_layout_new.addWidget(name_label) h_layout_new.addWidget(self.from_block_label) else: name_label = QLabel("To Block:") name_label.setFont(QFont("Helvetica 20")) name_label.setMinimumWidth(100) name_label.setMaximumWidth(100) self.to_block_label = QLabel("To Block:") self.to_block_label.setFont(QFont("Helvetica 20 Bold")) h_layout_new.addWidget(name_label) h_layout_new.addWidget(self.to_block_label) self.tab_conn_layout.addLayout(h_layout_new) def on_combo_box_changed(self): sender = self.sender() if sender == self.block_ID_combobox: self.__update_tab("Blocks") else: self.__update_tab("Connections") def __update_tab(self, tab_to_update): if tab_to_update == "Blocks": try: new_index = int(self.block_ID_combobox.currentText()) new_block = self.array_hander.find_block_by_ID(new_index) except: new_block = None if new_block is not None: self.name_label.setText(new_block.name) self.type_label.setText(new_block.type) else: self.name_label.setText("") self.type_label.setText("") for key in self.tables.keys(): new_model = CheckerIndexSetterTableModel(self, key) self.tables[key].setModel(new_model) else: try: new_index = int(self.conn_ID_combobox.currentText()) new_conn = self.array_hander.find_connection_by_ID(new_index) except: new_conn = None if new_conn is not None: self.conn_name_label.setText(new_conn.name) block_labels = self.get_connection_string(new_conn) self.from_block_label.setText(block_labels["from"]) self.to_block_label.setText(block_labels["to"]) else: self.name_label.setText("") self.type_label.setText("") @staticmethod def get_connection_string(connection): reutrn_dict = dict() if connection.is_system_input: reutrn_dict.update({"from": "System Input - cost: {}€/kJ".format(connection.rel_cost)}) else: other_block = connection.from_block reutrn_dict.update({"from": "{} - {}".format(other_block.get_main_ID, other_block.get_main_name)}) if connection.is_system_output: if connection.is_loss: reutrn_dict.update({"to": "System Loss"}) else: reutrn_dict.update({"to": "System Useful Effect"}) else: other_block = connection.to_block reutrn_dict.update({"to": "{} - {}".format(other_block.get_main_ID, other_block.get_main_name)}) return reutrn_dict @classmethod def launch(cls, array_handler): app = QApplication(sys.argv) new_self = cls(array_handler) new_self.show() app.exec_() class CheckerAbstractTable(QTableView): def __init__(self, main_window, title): super().__init__() new_model = self.table_model(main_window, title) self.setModel(new_model) self.currentRow = 0 self.currentCol = 0 self.__set_actions() def contextMenuEvent(self, event: QContextMenuEvent): menu = QMenu(self) menu.addAction(self.show_action) menu.exec(event.globalPos()) def __set_actions(self): self.show_action = QAction(self) self.show_action.setText("&Show") self.show_action.triggered.connect(self.onShowPressed) def onShowPressed(self): try: item = self.selectedIndexes()[0] self.model().onShowPressed(item.row(), item.column()) except: pass @property def table_model(self): return CheckerIndexSetterTableModel class CheckerIndexSetterTableModel(QAbstractTableModel): def __init__(self, main_window: CheckConnectionWidget, type): super().__init__() self.type = type self.main_window = main_window self.row_count = 0 self.column_count = 3 self.data_dict = dict() self.additional_info_list = list() self.names_list = list() self.index_list = list() self.change_data_type() def change_data_type(self): __current_block_ID = str(self.main_window.block_ID_combobox.currentText()) __block = self.main_window.array_hander.find_block_by_ID(__current_block_ID) if __block is None: connection = [] elif self.type == "Input Connections": connection = __block.external_input_connections else: connection = __block.external_output_connections self.load_connections(connection) def load_connections(self, connection_list): self.names_list = list() self.index_list = list() self.additional_info_list = list() self.connection_list = connection_list if len(connection_list) > 0: for connection in connection_list: self.names_list.append(str(connection.name)) self.index_list.append(str(connection.index)) self.additional_info_list.append(self.__get_connection_string(connection)) else: self.names_list.append("") self.index_list.append("") self.additional_info_list.append("") self.row_count = len(self.names_list) def rowCount(self, parent=QModelIndex()): return self.row_count def columnCount(self, parent=QModelIndex()): return self.column_count # noinspection PyMethodOverriding def headerData(self, section, orientation, role): if role == Qt.DisplayRole: if orientation == Qt.Horizontal: if self.type == "Input Connections": name_tuple = ("Conn Name", "Conn Index", "from Block") else: name_tuple = ("Conn Name", "Conn Index", "to Block") return name_tuple[section] else: return "{}".format(section) else: return None def data(self, index, role=Qt.DisplayRole): column = index.column() row = index.row() if role == Qt.DisplayRole: if column == 0: return self.names_list[row] elif column == 1: return self.index_list[row] elif column == 2: return str(self.additional_info_list[row]) elif role == Qt.BackgroundRole: return QColor(Qt.white) elif role == Qt.TextAlignmentRole: if column == 0: return Qt.AlignLeft | Qt.AlignVCenter elif column == 1: return Qt.AlignCenter else: return Qt.AlignCenter return None def flags(self, index): return Qt.ItemIsEnabled | Qt.ItemIsSelectable def onShowPressed(self, row, col): if col == 2: value = str(self.additional_info_list[row]) block_ID = int(value.split(" - ")[0]) index = self.main_window.block_ID_combobox.findData(block_ID) if not index == -1: self.main_window.block_ID_combobox.setCurrentIndex(index) self.main_window.on_combo_box_changed() else: connection = self.connection_list[row] index = self.main_window.conn_ID_combobox.findData(connection.ID) if not index == -1: self.main_window.conn_ID_combobox.setCurrentIndex(index) self.main_window.tab_widget.setCurrentIndex(1) self.main_window.on_combo_box_changed() def __get_connection_string(self, connection): if self.type == "Input Connections": return self.main_window.get_connection_string(connection)["from"] else: return self.main_window.get_connection_string(connection)["to"]
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/GUIElements/connection_and_block_check.py
connection_and_block_check.py
from PyQt5.QtCore import QAbstractTableModel, QModelIndex, Qt from PyQt5.QtGui import QColor, QContextMenuEvent, QIcon from PyQt5.QtWidgets import * import os class AbstractFilesManager(QDialog): def __init__(self, flags=None, *args, **kwargs): super().__init__(flags, *args, **kwargs) self.file_edit = None self.title = "" self.modules_handler = None self.selected_element_path = "" def __init_file_tree(self, dir_path): layout = QVBoxLayout() layout.addWidget(self.__get_tree_widget(dir_path)) layout.addWidget(self.__get_buttons_widget()) self.setLayout(layout) def __get_tree_widget(self, dir_path) -> QWidget: self.model = QFileSystemModel() self.model.setRootPath(dir_path) self.tree = QTreeView() self.tree.setModel(self.model) self.tree.setRootIndex(self.model.index(dir_path)) self.tree.clicked.connect(self.on_selection_changed) self.tree.setColumnWidth(0, 250) return self.tree def __get_buttons_widget(self) -> QWidget: buttons_widget = QWidget() v_layout = QHBoxLayout() self.add_button = QPushButton() self.add_button.setText("Add") self.add_button.setEnabled(False) self.add_button.clicked.connect(self.on_button_add_pressed) self.rename_button = QPushButton() self.rename_button.setText("Rename") self.rename_button.clicked.connect(self.on_button_rename_pressed) self.rename_button.setEnabled(False) self.modify_button = QPushButton() self.modify_button.setText("Modify") self.modify_button.clicked.connect(self.on_button_modify_pressed) self.modify_button.setEnabled(False) self.delete_button = QPushButton() self.delete_button.setText("Delete") self.delete_button.clicked.connect(self.on_button_delete_pressed) self.delete_button.setEnabled(False) self.duplicate_button = QPushButton() self.duplicate_button.setText("Duplicate") self.duplicate_button.clicked.connect(self.on_button_duplicate_pressed) self.duplicate_button.setEnabled(False) v_layout.addWidget(self.add_button) v_layout.addWidget(self.rename_button) v_layout.addWidget(self.modify_button) v_layout.addWidget(self.delete_button) v_layout.addWidget(self.duplicate_button) buttons_widget.setLayout(v_layout) return buttons_widget def __enable_buttons(self): if not os.path.exists(self.selected_element_path): self.add_button.setEnabled(False) self.delete_button.setEnabled(False) self.rename_button.setEnabled(False) self.modify_button.setEnabled(False) self.duplicate_button.setEnabled(False) if os.path.isdir(self.selected_element_path): self.add_button.setEnabled(True) self.delete_button.setEnabled(False) self.rename_button.setEnabled(False) self.modify_button.setEnabled(False) self.duplicate_button.setEnabled(False) elif os.path.isfile(self.selected_element_path): self.add_button.setEnabled(False) self.delete_button.setEnabled(True) self.rename_button.setEnabled(True) self.modify_button.setEnabled(True) self.duplicate_button.setEnabled(True) else: self.add_button.setEnabled(False) self.delete_button.setEnabled(False) self.rename_button.setEnabled(False) self.modify_button.setEnabled(False) self.duplicate_button.setEnabled(False) def __rename_file(self, new_name, file_path): dir_path = os.path.dirname(file_path) new_path = os.path.join(dir_path, new_name + ".dat") self.selected_element_path = new_path os.rename(file_path, new_path) def on_selection_changed(self, signal): self.selected_element_path = self.model.filePath(signal) self.__enable_buttons() def on_button_add_pressed(self): raise NotImplementedError def on_button_rename_pressed(self): raise NotImplementedError def on_button_modify_pressed(self): raise NotImplementedError def on_button_delete_pressed(self): raise NotImplementedError def on_button_duplicate_pressed(self): raise NotImplementedError def show(self): self.setWindowTitle(self.title) self.setGeometry(300, 300, 650, 300) self.modules_handler.check_data_folder() self.selected_element_path = self.modules_handler.data_folder self.__init_file_tree(self.modules_handler.data_folder) super(AbstractFilesManager, self).show() class WarningDialog(QDialog): # noinspection PyArgumentList def __init__(self, flags=None, *args, **kwargs): super().__init__(flags, *args, **kwargs) self.setWindowTitle("Warning") self.show_only_one_button = False self.button_on_click = None self.layout_is_set = False self.label = QLabel() self.yes_button = WarningButton() self.no_button = WarningButton() self.__init_layout() def __init_layout(self): self.button_on_click = self.__default_button_on_click self.yes_button.set_state(is_yes=True) self.no_button.set_state(is_yes=False) def set_label_text(self, text: str): self.label.setText(text) def set_layout(self, input_layout: QLayout = None): v_layout = QVBoxLayout() v_layout.addWidget(self.label) if not input_layout is None: __tmp_widget = QWidget() __tmp_widget.setLayout(input_layout) v_layout.addWidget(__tmp_widget) button_layout = QHBoxLayout() button_layout.addWidget(self.yes_button) if not self.show_only_one_button: button_layout.addWidget(self.no_button) __tmp_widget = QWidget() __tmp_widget.setLayout(button_layout) v_layout.addWidget(__tmp_widget) self.setLayout(v_layout) self.layout_is_set = True def set_button_text(self, text: str, set_button_yes=True): if set_button_yes: self.yes_button.setText(text) else: self.no_button.setText(text) def set_buttons_on_click(self, function): self.button_on_click = function def show(self): if not self.layout_is_set: self.set_layout() self.yes_button.clicked.connect(self.button_on_click) self.no_button.clicked.connect(self.button_on_click) super(WarningDialog, self).show() def __default_button_on_click(self): self.close() class WarningButton(QPushButton): def __init__(self, flags=None, *args, **kwargs): super().__init__(flags, *args, **kwargs) self.is_yes_button = False def set_state(self, is_yes): self.is_yes_button = is_yes class AbstractTable(QTableView): def __init__(self, main_window, title): super().__init__() new_model = self.table_model(main_window, title) self.setModel(new_model) self.currentRow = 0 self.__set_actions() def contextMenuEvent(self, event: QContextMenuEvent): menu = QMenu(self) # Populating the menu with actions menu.addAction(self.add_action) menu.addAction(self.delete_action) menu.addAction(self.modify_action) self.currentRow = self.rowAt(event.pos().y()) self.__enable_actions() # Launching the menu menu.exec(event.globalPos()) def __set_actions(self): self.modify_action = QAction(self) self.modify_action.setText("&Modify") self.modify_action.setIcon(QIcon(":icon-modify")) self.modify_action.triggered.connect(self.onModifyPressed) self.delete_action = QAction(self) self.delete_action.setText("&Delete") self.delete_action.setIcon(QIcon(":icon-delete")) self.delete_action.triggered.connect(self.onDeletePressed) self.add_action = QAction(self) self.add_action.setText("&Add") self.add_action.setIcon(QIcon(":icon-add")) self.add_action.triggered.connect(self.onAddPressed) def __enable_actions(self): model = self.model() self.modify_action.setEnabled(model.context_action_activation(self.currentRow, "modify")) self.delete_action.setEnabled(model.context_action_activation(self.currentRow, "delete")) self.add_action.setEnabled(model.context_action_activation(self.currentRow, "add")) def onAddPressed(self): self.model().onAddClicked(self.currentRow) def onDeletePressed(self): self.model().onDeleteClicked(self.currentRow) def onModifyPressed(self): self.model().onModifyClicked(self.currentRow) @property def table_model(self): return IndexSetterTableModel class IndexSetterTableModel(QAbstractTableModel): def __init__(self, main_window, type): super().__init__() self.type = type self.main_window = main_window self.row_count = 0 if self.type in ["Input Indices", "Parameters Indices"]: self.column_count = 3 else: self.column_count = 2 self.data_dict = dict() self.additional_info_list = list() self.names_list = list() self.index_list = list() self.change_data_type() def change_data_type(self): if self.type == "Input Indices": __current_type_name = str(self.main_window.type_combobox.currentText()) __current_type_class = self.main_window.modules_handler.import_correct_sub_class(__current_type_name) data: dict = __current_type_class.return_EES_needed_index() elif self.type == "Parameters Indices": data = dict() else: __current_type_name = str(self.main_window.block_ID_combobox.currentText()) __current_type_class = self.main_window.modules_handler.import_correct_sub_class(__current_type_name) data: dict = __current_type_class.return_EES_base_equations() self.load_data(data) def load_data(self, data): self.names_list = list() self.index_list = list() self.additional_info_list = list() self.data_dict = data for key in data.keys(): self.names_list.append(str(key)) if self.type in ["Input Indices", "Parameters Indices"]: self.index_list.append(data[key][0]) self.additional_info_list.append(data[key][1]) else: self.index_list.append(len(data[key]["variables"])) self.row_count = len(self.names_list) def rowCount(self, parent=QModelIndex()): return self.row_count def columnCount(self, parent=QModelIndex()): return self.column_count # noinspection PyMethodOverriding def headerData(self, section, orientation, role): if role == Qt.DisplayRole: if orientation == Qt.Horizontal: if self.type == "Input Indices": name_tuple = ("Index Name", "Index Reference", "Multiple Input") elif self.type == "Parameters Indices": name_tuple = ("Index Name", "Index Reference", "Related Option") else: name_tuple = ("Name", "n° Connections", "") return name_tuple[section] else: return "{}".format(section) else: return None def data(self, index, role=Qt.DisplayRole): column = index.column() row = index.row() if role == Qt.DisplayRole: if column == 0: return self.names_list[row] elif column == 1: return self.index_list[row] elif column == 2: return str(self.additional_info_list[row]) elif role == Qt.BackgroundRole: return QColor(Qt.white) elif role == Qt.TextAlignmentRole: if column == 0: return Qt.AlignLeft | Qt.AlignVCenter elif column == 1: return Qt.AlignCenter else: if self.type == "Input Indices": return Qt.AlignCenter elif self.type == "Parameters Indices": return Qt.AlignLeft | Qt.AlignVCenter else: return Qt.AlignCenter elif role == Qt.CheckStateRole: if index.column() == 2 and self.type == "Input Indices": if self.additional_info_list[row]: return Qt.Checked else: return Qt.Unchecked return None def flags(self, index): return Qt.ItemIsEnabled | Qt.ItemIsSelectable def context_action_activation(self, row, action): if self.type in ["Input Indices", "Parameters Indices"]: return False else: return True # <------------ MENU ON CLICK METHODS ------------> def onAddClicked(self, row): if self.type in ["Input Indices", "Parameters Indices"]: pass else: pass def onModifyClicked(self, row): if self.type in ["Input Indices", "Parameters Indices"]: pass else: pass def onDeleteClicked(self, row): if self.type in ["Input Indices", "Parameters Indices"]: pass else: pass
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/Tools/GUIElements/gui_base_classes.py
gui_base_classes.py
import copy import warnings import xml.etree.ElementTree as ETree from abc import ABC, abstractmethod import numpy as np from EEETools import costants from EEETools.Tools.Other.matrix_analyzer import MatrixAnalyzer from EEETools.Tools.modules_handler import ModulesHandler class Block(ABC): # ------------------------------------- # ------ Initialization Methods ------ # ------------------------------------- def __init__(self, inputID, main_class, is_support_block=False): self.__ID = inputID self.index = inputID self.name = " " self.type = "generic" self.coefficients = dict() self.exergy_analysis = dict() self.comp_cost_corr = None self.comp_cost = 0. self.output_cost = 0. self.difference_cost = 0. self.dissipative_output_cost = 0. self.output_cost_decomposition = dict() self.input_connections = list() self.output_connections = list() self.n_input = 0 self.n_output = 0 self.is_support_block = is_support_block self.has_modification = False self.has_support_block = False self.move_skipped_block_at_the_end = False self.error_value = 0 self.main_class = main_class self.support_block = list() self.main_block = None self.connection_with_main = None def modify_ID(self, newID): # When the ID of the block is modified, for exemple in ordering the BlockArray List, the ID has to be modified # also in the connection related to the block self.__ID = newID @property def ID(self): return self.__ID @property def get_main_ID(self): if self.is_support_block: return self.main_block.get_main_ID else: return self.ID @property def get_main_name(self): if self.is_support_block: return self.main_block.get_main_name else: return self.name # ------------------------------------- # -------- Calculation Methods -------- # ------------------------------------- # - Matrix Row generation - def get_matrix_row(self, n_elements): self.calculate_exergy_analysis() if self.is_dissipative: return self.__get_dissipative_matrix_row(n_elements) else: return self.__get_standard_matrix_row(n_elements) def __get_standard_matrix_row(self, n_blocks): # This method return the row of the Cost Matrix corresponding to the current block in a block-oriented # computation scheme # The Cost Matrix is a squared matrix of size NXN where N is the number of blocks. Another column, # representing the known variables vector has been added at the end of the matrix, hence its actual # dimensions are NX(N+1). In the Cost Matrix the elements on the diagonal correspond to the Exergetic value # of the flows exiting from the block while the off-diagonal elements match with the input flows into the # blocks. Off-diagonal terms must be negative. For example at column "m" you will find the exergy flux coming # into the component from block with ID "m". # The last column represent known variable and should be filled with the known costs # For further details please refer to the paper (to be quoted) # line initialization with an array of zeroes (dimension N+1) row = np.zeros(n_blocks + 1) element_cost = self.comp_cost exergy_sum = 0 # This part of the code scrolls the input connections, for each of them it checks if the connection # came form another block (it's an internal connection) or if it's a system input. # In the latter case its absolute cost must be known so it will be considered as a known variable # ant the result is written in the last column for conn in self.input_connections: if not (conn.is_system_input or conn.exergy_value == 0): row[conn.fromID] -= conn.exergy_value else: element_cost += conn.exergy_value * conn.rel_cost row[-1] = element_cost # Output connections are scrolled, if they are not exergy losses their exergy values is summed up # result is written in the column related to the current block for conn in self.output_connections: if not conn.is_loss or (not self.main_class.options.loss_cost_is_zero): exergy_sum += conn.exergy_value row[self.ID] = exergy_sum return row def __get_dissipative_matrix_row(self, n_blocks): # This method return the rows of the Cost Matrix corresponding to a dissipative block # The Cost Matrix is a squared matrix of size NXN where N is the number of blocks. Another column, # representing the known variables vector has been added at the end of the matrix, hence its actual # dimensions are NX(N+1). # # In the Cost Matrix the elements on the diagonal for dissipative blocks is equal to 1 as the i-th column in # the matrix represent the cost difference variable. While the off-diagonal elements match with the input # flows into the blocks. Off-diagonal terms must be negative. For example at column "m" you will find the # exergy flux coming into the component from block with ID "m". # The last column represent known variable and should be filled with the known costs # For further details please refer to the paper (to be quoted) # line initialization with an array of zeroes (dimension N+1) row = np.zeros(n_blocks + 1) element_cost = self.comp_cost # This part of the code scrolls the input connections, for each of them it checks if che connection # came form another block (it's an internal connection) or if it's a system input. # In the latter case its absolute cost must be known so it will be considered as a known variable # result is written in the last column for conn in self.input_connections: if not (conn.is_system_input or conn.exergy_value == 0): row[conn.fromID] -= conn.exergy_value else: element_cost += conn.exergy_value * conn.rel_cost row[-1] = element_cost # diagonal element is set to overall_exergy_input row[self.ID] = self.exergy_input return row # - Loss Redistribution Handling - @property def redistribution_index(self): if self.is_dissipative: redistribution_index = 0 else: redistribution_method = self.main_class.options.redistribution_method if redistribution_method == CalculationOptions.EXERGY_DESTRUCTION: redistribution_index = abs(self.exergy_balance) elif redistribution_method == CalculationOptions.EXERGY_PRODUCT: redistribution_index = abs(self.productive_exergy_output) else: redistribution_index = abs(self.comp_cost) return redistribution_index @property def redistribution_block_list(self): # TODO it can be overloaded in sub classes if self.is_dissipative: return self.main_class.non_dissipative_blocks else: return list() @property def redistribution_sum(self): redistribution_sum = 0 for block in self.redistribution_block_list: redistribution_sum += block.redistribution_index return redistribution_sum # - Exergo-Economic Analysis Coefficient Evaluation - def calculate_exergy_analysis(self): fuel_exergy = 0. lost_exergy = 0. product_exergy = 0. for conn in self.input_connections: fuel_exergy += conn.exergy_value for conn in self.output_connections: if conn.is_loss: lost_exergy += conn.exergy_value else: product_exergy += conn.exergy_value destruction_exergy = fuel_exergy - product_exergy - lost_exergy self.exergy_analysis.update({"fuel": fuel_exergy, "product": product_exergy, "losses": lost_exergy, "distruction": destruction_exergy}) def calculate_coefficients(self, total_destruction): r = 0 f = 0 y = 0 eta = 0 c_fuel = 0 c_dest = 0 self.calculate_exergy_analysis() fuel_exergy = self.exergy_analysis["fuel"] dest_exergy = self.exergy_analysis["distruction"] dest_loss_exergy = self.exergy_analysis["distruction"] + self.exergy_analysis["losses"] fuel_cost = 0. if self.can_be_removed_in_pf_definition and self.main_class.options.calculate_on_pf_diagram: self.output_cost = self.output_connections[0].rel_cost if self.is_dissipative: c_prod = self.dissipative_output_cost else: c_prod = self.output_cost for conn in self.input_connections: fuel_cost += conn.exergy_value * conn.rel_cost if not fuel_exergy == 0: eta = self.productive_exergy_output / abs(fuel_exergy) if eta > 1: eta = 1/eta c_fuel = fuel_cost / abs(fuel_exergy) c_dest = c_fuel if not c_fuel == 0: r = (c_prod - c_fuel) / c_fuel if not (self.comp_cost + c_dest * abs(dest_loss_exergy)) == 0: f = self.comp_cost / (self.comp_cost + c_dest * abs(dest_exergy)) if not total_destruction == 0: y = dest_exergy / total_destruction self.coefficients.update({ "r": r, "f": f, "y": y, "eta": eta, "c_fuel": c_fuel, "c_dest": c_dest }) # - Support Methods - def prepare_for_calculation(self): # This method is used in block's subclasses to execute the calculations needed before the launch of the main # calculation, it has to be overloaded if needed pass def append_output_cost(self, defined_steam_cost): # The stream cost is calculated in the overall calculation, # this method is meant to be used in order to assign the # right cost to the output streams # Cost of the exergy losses will be considered as 0 if self.is_dissipative: block_ex_dl = self.exergy_dl self.difference_cost = defined_steam_cost * block_ex_dl self.dissipative_output_cost = defined_steam_cost self.output_cost = 0. else: self.output_cost = defined_steam_cost for outConn in self.output_connections: if outConn.is_loss and self.main_class.options.loss_cost_is_zero: outConn.set_cost(0.) else: outConn.set_cost(self.output_cost) def generate_output_cost_decomposition(self, inverse_matrix_row): overall_sum = self.__sum_decomposition_values(inverse_matrix_row) for block in self.main_class.block_list: if not block.comp_cost == 0.: decomposition_value = inverse_matrix_row[block.ID] * block.comp_cost self.__append_decomposition_value(block.name, decomposition_value, overall_sum) for input_conn in self.main_class.system_inputs: if not input_conn.rel_cost == 0.: decomposition_value = inverse_matrix_row[input_conn.to_block.ID] * input_conn.abs_cost self.__append_decomposition_value(input_conn.name, decomposition_value, overall_sum) def __sum_decomposition_values(self, inverse_matrix_row): sum = 0 for block in self.main_class.block_list: if not block.comp_cost == 0.: sum += inverse_matrix_row[block.ID] * block.comp_cost for input_conn in self.main_class.system_inputs: if not input_conn.rel_cost == 0.: sum += inverse_matrix_row[input_conn.to_block.ID] * input_conn.abs_cost return sum def __append_decomposition_value(self, input_name, absolute_decomposition_value, overall_sum): if overall_sum == 0.: decomposition_value = 0. else: decomposition_value = absolute_decomposition_value / overall_sum self.output_cost_decomposition.update({input_name: decomposition_value}) @property def productive_exergy_output(self): productive_exergy_output = 0 for conn in self.non_loss_output: productive_exergy_output += abs(conn.exergy_value) return productive_exergy_output @property def exergy_input(self): overall_exergy_input = 0 for conn in self.input_connections: overall_exergy_input += abs(conn.exergy_value) return overall_exergy_input @property def exergy_dl(self): overall_exergy_dl = self.exergy_balance for conn in self.output_connections: if conn.is_loss: overall_exergy_dl += abs(conn.exergy_value) return overall_exergy_dl @property def exergy_balance(self): exergy_balance = 0 for conn in self.input_connections: exergy_balance += conn.exergy_value for conn in self.output_connections: exergy_balance -= conn.exergy_value return exergy_balance @property def cost_balance(self): cost_balance = self.comp_cost for conn in self.input_connections: cost_balance += conn.exergy_value * conn.rel_cost if self.is_dissipative: cost_balance -= self.difference_cost else: for conn in self.output_connections: cost_balance -= conn.exergy_value * conn.rel_cost return cost_balance # ------------------------------------- # ---- Connection Handling Methods ---- # ------------------------------------- def add_connection(self, new_connection, is_input, append_to_support_block=None): if append_to_support_block is None: if is_input: new_connection.set_block(self, is_from_block=False) self.input_connections.append(new_connection) self.n_input += 1 else: new_connection.set_block(self, is_from_block=True) self.output_connections.append(new_connection) self.n_output += 1 else: if issubclass(type(append_to_support_block), Block) or type(append_to_support_block) is Block: sel_block = append_to_support_block else: try: sel_block = self.support_block[int(append_to_support_block)] except: warningString = "" warningString += str(append_to_support_block) + " is not a suitable index" warningString += " connection not updated" warnings.warn(warningString) return sel_block.add_connection(new_connection, is_input) def remove_connection(self, deleted_conn): # This method tries to remove the connection from the input_connections List (it can do that because # connection class has __eq__ method implemented) if the elimination does not succeed (i.e. there is not such # connection in the List) it rises a warning and exit # The method search the connection to be deleted in the input_connection list and in the output_connection # list. If none of this search succeed the method repeat the search in the support blocks try: self.input_connections.remove(deleted_conn) except: try: self.output_connections.remove(deleted_conn) except: found = False if self.has_support_block: warnings.filterwarnings("error") for block in self.support_block: try: block.remove_connection(deleted_conn) except: pass else: found = True warnings.filterwarnings("default") if not found: warningString = "" warningString += "You're trying to delete " warningString += str(deleted_conn) + " from " + str(self) + " but " warningString += "the connection is not related with the selected block" warnings.warn(warningString) else: # if the connection is found in the outputs its toBlockID is replaced with -1 # (default for disconnected streams, it means that its an exergy input with cost 0) deleted_conn.set_block(None, is_from_block=True) else: # if the connection is found in the inputs its toBlockID is replaced with -1 # (default for disconnected streams, it means that its an exergy loss) deleted_conn.set_block(None, is_from_block=False) self.calculate_exergy_analysis() def disconnect_block(self): # this method will remove every connection from the block, it is usefull if the block has to be deleted _tmpConnectionArray = copy.deepcopy(self.input_connections) _tmpConnectionArray.extend(copy.deepcopy(self.output_connections)) for conn in _tmpConnectionArray: self.remove_connection(conn) def connection_is_in_connections_list(self, connection): return connection in self.input_connections or connection in self.output_connections def get_fluid_stream_connections(self): connection_list = list() for connection in self.input_connections: if connection.is_fluid_stream: connection_list.append(connection) for connection in self.output_connections: if connection.is_fluid_stream: connection_list.append(connection) return connection_list @property def external_input_connections(self): input_connections = list() for connection in self.input_connections: if not connection.is_internal_stream: input_connections.append(connection) if self.has_support_block: for block in self.support_block: input_connections.extend(block.external_input_connections) return input_connections @property def external_output_connections(self): output_connections = list() for connection in self.output_connections: if not connection.is_internal_stream: output_connections.append(connection) if self.has_support_block: for block in self.support_block: output_connections.extend(block.external_output_connections) return output_connections # ------------------------------------- # --------- Save/Load Methods --------- # ------------------------------------- @abstractmethod def initialize_connection_list(self, input_list): raise (NotImplementedError, "block.initialize_connection_list() must be overloaded in subclasses") @property def xml(self) -> ETree.Element: block_child = ETree.Element("block") block_child.set("index", str(self.index)) block_child.set("name", str(self.name)) block_child.set("type", str(self.type)) block_child.set("comp_cost", str(self.comp_cost)) block_child.set("comp_cost_corr", str(self.comp_cost_corr)) block_child.append(self.__export_xml_other_parameters()) block_child.append(self.export_xml_connection_list()) return block_child @xml.setter def xml(self, xml_input: ETree.Element): self.index = float(xml_input.get("index")) self.name = xml_input.get("name") self.type = xml_input.get("type") self.comp_cost = float(xml_input.get("comp_cost")) self.comp_cost_corr = xml_input.get("comp_cost_corr") self.append_xml_other_parameters(xml_input.find("Other")) self.append_xml_connection_list(xml_input.find("Connections")) def __export_xml_other_parameters(self) -> ETree.Element: other_tree = ETree.Element("Other") tree_to_append = self.export_xml_other_parameters() if tree_to_append is not None: other_tree.append(tree_to_append) return other_tree def export_xml_other_parameters(self) -> ETree.Element: pass def append_xml_other_parameters(self, input_list: ETree.Element): pass @abstractmethod def export_xml_connection_list(self) -> ETree.Element: raise (NotImplementedError, "block.__export_xml_connection_list() must be overloaded in subclasses") @abstractmethod def append_xml_connection_list(self, input_list: ETree.Element): raise (NotImplementedError, "block.__append_xml_connection_list() must be overloaded in subclasses") # ------------------------------------- # ---------- Support Methods ---------- # ------------------------------------- @property @abstractmethod def is_ready_for_calculation(self): # This method is used to check if the block has every input it needs to perform a calculation. # WARING: IT HAS TO BE OVERLOADED BY SUBCLASSES!! if type(self) is Block: return True else: raise (NotImplementedError, "block.is_ready_for_calculation() must be overloaded in subclasses") @property def is_dissipative(self): # this method returns true if all the outputs are exergy losses or have an exergy value equal to 0 # hence the corresponding column in the solution matrix will be and empty vector resulting in a singular matrix # To avoid this issue the program automatically skips such block in the solution matrix and set its stream # cost to 0 for outConn in self.output_connections: if (not outConn.is_loss) and (not outConn.exergy_value == 0): return False return True @property def can_be_removed_in_pf_definition(self): if not self.exergy_input == 0: relative_exergy_balance = round(self.exergy_balance/self.exergy_input, 6) else: relative_exergy_balance = self.exergy_balance if relative_exergy_balance == 0 and self.n_input == 1 and self.comp_cost == 0. and not self.is_dissipative: return True return False @property def non_loss_output(self): # This method returns a list of non-loss output, hence it scrolls the output connection and append the # connections that are not losses output_list = list() for outConn in self.output_connections: if (not outConn.is_loss) and (not outConn.exergy_value == 0): output_list.append(outConn) return output_list @property def n_non_loss_output(self): # This method the number of non-loss output, hence it scrolls the output connection and count the number of # them which are not losses return len(self.non_loss_output) @property def n_non_empty_output(self): # This method the number of non-empty output, hence it scrolls the output connection and count the number of # them which are not empty counter = 0 for outConn in self.output_connections: if not outConn.has_to_be_skipped: counter += 1 return counter @property def first_non_support_block(self): if not self.is_support_block: return self if self.is_support_block: return self.main_block.first_non_support_block # ------------------------------------- # ------ EES Generation Methods ----- # ------ (to be eliminated) ----- # ------------------------------------- @classmethod @abstractmethod def return_EES_needed_index(cls): # WARNING: This methods must be overloaded in subclasses!! # This methods returns a dictionary that contain a list of streams that have to be present in the EES text # definition. # # The first element of the list must be an index and means that the EES script must contains indices [$0], # [$1] and [$2] (the actual value can be updated in the editor). # # If the second element is True it means that multiple inputs can be connected to that port (for example a # mixer can have different input streams). This enables the usage of specific keywords ($sum, $multiply and # $repeat). If none of the key_words has been imposed the system automatically subsitute the index with the # first one in list ignoring the others. The the mixer example below should clarify this passage: # EXPANDER EXAMPLE # # dict: # # { "output power index" : [0, True] } # { "input flow index" : [1, False] } # { "output flow index" : [2, False] } # # EES text: # # "TURBINE [$block_index]" # # turb_DeltaP[$block_index] = $input[0] # turb_eff[$block_index] = $input[1] # # s_iso[$2] = s[$1] # h_iso[$2] = enthalpy($fluid, P = P[$2], s = s_iso[$2]) # # p[$2] = p[$1] - turb_DeltaP[$block_index] # h[$2] = h[$1] - (h[$1] - h_iso[$2])*turb_eff[$block_index] # T[$2] = temperature($fluid, P = P[$2], h = h[$2]) # s[$2] = entropy($fluid, P = P[$2], h = h[$2]) # m_dot[$2] = m_dot[$1] # # $sum{W[$0]} = m_dot[$2]*(h[$1] - h[$2]) # MIXER EXAMPLE # # dict: # # { "input flow index" : [0, True] } # { "output flow index" : [1, False] } # # EES text: # # "Mixer [$block_index]" # # "mass balance" # m_dot[$1] = $sum{m_dot[$0]} # # "energy balance" # m_dot[$1]*h[$1] = $sum{m_dot[$0]*h[$0]} # # "set pressure" # p[$1] = p[$0] # if type(cls) is Block: return dict() else: raise (NotImplementedError, "block.is_ready_for_calculation() must be overloaded in subclasses") @classmethod @abstractmethod def return_EES_base_equations(cls): # WARNING: This methods must be overloaded in subclasses!! # This methods returns a dictionary that contain a list of streams that have to be present in the EES text # definition. if type(cls) is Block: return dict() else: raise (NotImplementedError, "block.is_ready_for_calculation() must be overloaded in subclasses") @abstractmethod def return_other_zone_connections(self, zone_type, input_connection): # WARNING: This methods must be overloaded in subclasses!! # # This method is needed in order to generate zones (that is to say a list of connections that shares some # thermodynamic parameter (e.g. "flow rate" zone is a list of connections that has the same flow rate) # # This method must return a list of connections connected to the block that belongs to the same zone as # "input_connection". # # For example: as in a Turbine the flow rate is conserved between input and output, if this method is invoked # with flow_input as "input_connection" and with "flow rate" as zone_type it must return a list containing # flow_output if type(self) is Block: return list() else: raise (NotImplementedError, "block.is_ready_for_calculation() must be overloaded in subclasses") # ------------------------------------- # -------- Sequencing Methods -------- # ------------------------------------- def this_has_higher_skipping_order(self, other): if self.is_dissipative == other.is_dissipative: return None else: return self.is_dissipative def this_has_higher_support_block_order(self, this, other): if this.is_support_block == other.is_support_block: if this.is_support_block: return self.this_has_higher_support_block_order(this.main_block, other.main_block) else: return None else: return this.is_support_block def __gt__(self, other): # enables comparison # self > other skipping_order = self.this_has_higher_skipping_order(other) if skipping_order is not None and self.move_skipped_block_at_the_end: return skipping_order else: self_has_higher_support_block_order = self.this_has_higher_support_block_order(self, other) if self_has_higher_support_block_order is None: # if both are (or not are) support blocks the program check the IDs # (hence self > other if self.ID > other.ID) return self.ID > other.ID else: # if only one of the two is a support blocks the program return the support block as the greatest of the # couple (hence self > other if other.is_support_block = False AND self.is_support_block = True) return self_has_higher_support_block_order def __lt__(self, other): # enables comparison # self < other skipping_order = self.this_has_higher_skipping_order(other) if skipping_order is not None and self.move_skipped_block_at_the_end: return not skipping_order else: self_has_higher_support_block_order = self.this_has_higher_support_block_order(self, other) if self_has_higher_support_block_order is None: # if both are (or not are) support blocks the program check the IDs # (hence self < other if self.ID < other.ID) return self.ID < other.ID else: # if only one of the two is a support blocks the program return the support block as the greatest of the # couple (hence self < other if other.is_support_block = True AND self.is_support_block = False) return not self_has_higher_support_block_order def __le__(self, other): return not self.__gt__(other) def __ge__(self, other): return not self.__lt__(other) def __str__(self): # enables printing and str() method # e.g. str(Block1) -> "Block (ID: 2, name: Expander 1)" string2Print = "Block " string2Print += "(ID: " + str(self.ID) string2Print += ", name: " + str(self.name) string2Print += ", type: " + str(self.type) + ")" return string2Print def __repr__(self): # enables simple representation # e.g. Block1 -> "Block (ID: 2, name: Expander 1)" return str(self) class Connection: # Construction Methods def __init__(self, inputID, from_block_input: Block = None, to_block_input: Block = None, exergy_value: float = 0, is_fluid_stream=True): self.__ID = inputID self.index = inputID self.name = " " self.from_block = from_block_input self.to_block = to_block_input self.__rel_cost = 0. self.exergy_value = exergy_value self.is_useful_effect = False self.automatically_generated_connection = False self.is_fluid_stream = is_fluid_stream self.zones = {costants.ZONE_TYPE_FLUID: None, costants.ZONE_TYPE_FLOW_RATE: None, costants.ZONE_TYPE_PRESSURE: None, costants.ZONE_TYPE_ENERGY: None} self.sort_by_index = True self.base_connection = None def set_block(self, block, is_from_block): if is_from_block: self.from_block = block else: self.to_block = block # EES Checker Methods def add_zone(self, zone): self.zones[zone.type] = zone def return_other_zone_connections(self, zone): __tmp_zone_connections = list() if self.to_block is not None: __tmp_zone_connections.extend(self.to_block.return_other_zone_connections(zone.type, self)) if self.from_block is not None: __tmp_zone_connections.extend(self.from_block.return_other_zone_connections(zone.type, self)) return __tmp_zone_connections # Property setter and getter @property def ID(self): return self.__ID def modify_ID(self, inputID): self.__ID = inputID @property def fromID(self): if self.from_block is not None: return self.from_block.ID else: return -1 @property def toID(self): if self.to_block is not None: return self.to_block.ID else: return -1 def set_cost(self, cost): self.rel_cost = cost # Boolean Methods @property def is_system_input(self): return self.fromID == -1 @property def is_system_output(self): return self.toID == -1 @property def is_block_input(self): return not self.toID == -1 @property def is_loss(self): return (self.toID == -1 and not self.is_useful_effect) @property def is_internal_stream(self): if not (self.to_block is None or self.from_block is None): if self.to_block.get_main_ID == self.from_block.get_main_ID: return True return False @property def has_to_be_skipped(self): # This method returns true the stream exergy value equal to 0 hence the corresponding column in the solution # matrix will be and empty vector resulting in a singular matrix # To avoid this issue the program automatically skips such block in the solution matrix and set its stream # cost to 0 return (self.exergy_value == 0) or self.is_system_input or self.is_loss @property def xml(self) -> ETree: connection_child = ETree.Element("connection") connection_child.set("index", str(self.index)) connection_child.set("name", str(self.name)) connection_child.set("rel_cost", str(self.rel_cost)) connection_child.set("exergy_value", str(self.exergy_value)) connection_child.set("is_fluid_stream", str(self.is_fluid_stream)) connection_child.set("is_useful_effect", str(self.is_useful_effect)) return connection_child @xml.setter def xml(self, input_xml: ETree): self.index = float(input_xml.get("index")) self.name = input_xml.get("name") self.rel_cost = float(input_xml.get("rel_cost")) self.exergy_value = float(input_xml.get("exergy_value")) self.is_fluid_stream = input_xml.get("is_fluid_stream") == "True" self.is_useful_effect = input_xml.get("is_useful_effect") == "True" @property def abs_cost(self) -> float: return self.__rel_cost * self.exergy_value @property def rel_cost(self) -> float: return self.__rel_cost @rel_cost.setter def rel_cost(self, rel_cost_input): self.__rel_cost = rel_cost_input # Overloaded Methods def __this_has_higher_skipping_order(self, other): if self.has_to_be_skipped == other.is_dissipative: return None else: return self.has_to_be_skipped def __gt__(self, other): # enables comparison # self > other if self.sort_by_index: return self.index > other.index else: skipping_order = self.__this_has_higher_skipping_order(other) if skipping_order is not None: return skipping_order else: # if both are (or not are) to be skipped the program check the IDs # (hence self > other if self.ID > other.ID) return self.ID > other.ID def __lt__(self, other): # enables comparison # self < other if self.sort_by_index: return self.index < other.index else: skipping_order = self.__this_has_higher_skipping_order(other) if skipping_order is not None: return not skipping_order else: # if both are (or not are) to be skipped the program check the IDs # (hence self < other if self.ID < other.ID) return self.ID < other.ID def __le__(self, other): return not self.__gt__(other) def __ge__(self, other): return not self.__lt__(other) def __eq__(self, other): # enables comparison # Connection1 == Connection2 -> True if ID1 = ID2 # If type(self) == type(other) = ProductConnection the program compare the base_connections IDs # It types are different (one is Connection and the other one in ProductConnection) the comparison will fail if type(self) == type(other): if type(self) is Connection: return self.ID == other.ID else: return self.base_connection == other.base_connection return False def __str__(self): # enables printing and str() method # e.g. str(Block1) -> "Connection (ID: 2, name: Expander 1, from: 5, to:3)" if not self.from_block is None: from_ID = self.from_block.get_main_ID else: from_ID = self.fromID if not self.to_block is None: to_ID = self.to_block.get_main_ID else: to_ID = self.toID string2Print = "Connection " string2Print += "(ID: " + str(self.ID) string2Print += ", name: " + str(self.name) string2Print += ", from: " + str(from_ID) string2Print += ", to: " + str(to_ID) + ")" return string2Print def __repr__(self): # enables simple representation # e.g. Block1 -> "Block (ID: 2, name: Expander 1)" return str(self) class ArrayHandler: def __init__(self): self.block_list = list() self.n_block = 0 self.connection_list = list() self.n_connection = 0 self.n_conn_matrix = 0 self.matrix = np.zeros(0) self.vector = np.zeros(0) self.modules_handler = ModulesHandler() self.matrix_analyzer = None self.pf_diagram = None self.options = CalculationOptions() # ------------------------------------- # ----- Main Calculations Methods ----- # ------------------------------------- def calculate(self): # These methods generate the cost matrix combining the lines returned by each block and then solve it. Before # doing so, it invokes the method "__prepare_system" that prepares the system to be solved asking the # blocks to generate their own support blocks (if needed) and appending them to the block list. # If the user requires to perform the calculation on the product-fuels diagram rather than on the physical # system the program generates and solve it automatically if not self.is_ready_for_calculation: warning_string = "The system is not ready - calculation not started" warnings.warn(warning_string) else: self.prepare_system() if self.options.calculate_on_pf_diagram and "PFArrayHandler" not in str(type(self)): from EEETools.MainModules.pf_diagram_generation_module import PFArrayHandler self.pf_diagram = PFArrayHandler(self) self.pf_diagram.calculate() self.calculate_coefficients() else: i = 0 n_elements = self.n_block self.matrix = np.zeros((n_elements, n_elements)) self.vector = np.zeros(n_elements) for block in self.block_list: row = block.get_matrix_row(n_elements) self.vector[i] += row[-1] self.matrix[i, :] += row[0:-1] if block.is_dissipative: red_sum = block.redistribution_sum exergy_dissipated = block.exergy_input for non_dissipative_blocks in block.redistribution_block_list: red_perc = non_dissipative_blocks.redistribution_index / red_sum self.matrix[non_dissipative_blocks.ID, i] -= exergy_dissipated * red_perc i += 1 self.matrix_analyzer = MatrixAnalyzer(self.matrix, self.vector) self.matrix_analyzer.solve() sol = self.matrix_analyzer.solution self.append_solution(sol) self.calculate_coefficients() self.decompose_component_output_cost() def append_solution(self, sol): i = 0 for block in self.block_list: block.append_output_cost(sol[i]) i += 1 self.__reset_IDs(reset_block=True) self.__reset_IDs(reset_block=False) def calculate_coefficients(self): total_destruction = self.total_destruction for block in self.block_list: block.calculate_coefficients(total_destruction) def calculate_exergy_analysis(self): for block in self.block_list: block.calculate_exergy_analysis() def decompose_component_output_cost(self): if self.options.calculate_component_decomposition: try: __inverse_matrix = np.linalg.inv(self.matrix) for block in self.block_list: block.generate_output_cost_decomposition(__inverse_matrix[block.ID, ]) except: try: __inverse_matrix = self.matrix_analyzer.inverse_matrix for block in self.block_list: block.generate_output_cost_decomposition(__inverse_matrix[block.ID, ]) except: self.options.calculate_component_decomposition = False def prepare_system(self): # this method has to be called just before the calculation, it asks the blocks to prepare themselves for the # calculation self.calculate_exergy_analysis() self.__update_block_list() for block in self.block_list: block.prepare_for_calculation() if self.there_are_dissipative_blocks: self.__move_skipped_element_at_the_end() # ------------------------------------ # -------- Overall Properties -------- # ------------------------------------ @property def overall_investment_cost(self): overall_investment_cost = 0 for block in self.block_list: overall_investment_cost += block.comp_cost return overall_investment_cost @property def overall_external_balance(self): balance = self.overall_investment_cost for conn in self.system_inputs: balance += conn.exergy_value * conn.rel_cost for conn in self.system_outputs: balance -= conn.exergy_value * conn.rel_cost return balance @property def overall_efficiency(self): input_exergy = 0 for connection in self.system_inputs: input_exergy += connection.exergy_value output_exergy = 0 for connection in self.system_outputs: output_exergy += connection.exergy_value return output_exergy / input_exergy @property def total_destruction(self): total_destruction = 0 for conn in self.system_inputs: total_destruction += conn.exergy_value for conn in self.useful_effect_connections: total_destruction -= conn.exergy_value return total_destruction # ------------------------------------- # ----- Elements Handling Methods ----- # ------------------------------------- def append_block(self, input_element="Generic"): # this method accepts three types of inputs: # # - a Block or one of its subclasses: # in this case the object is directly appended to the list # # - a str or something that can be converted to a string containing the name of the block subclass that had # to be added: # in this case the method automatically import the correct block sub-class and append it to the blockArray # list if there is any problem with the import process the program will automatically import the "generic" # subclass # # - a List: # in this case append_block method is invoked for each component of the list if type(input_element) is list: new_blocks = list() for elem in input_element: new_block = self.append_block(elem) new_blocks.append(new_block) self.__reset_IDs(reset_block=True) return new_blocks else: if issubclass(type(input_element), Block) or type(input_element) is Block: new_block = input_element else: try: block_class = self.import_correct_sub_class(str(input_element)) except: block_class = self.import_correct_sub_class("Generic") new_block = block_class(self.n_block, self) self.n_block += 1 self.block_list.append(new_block) self.__reset_IDs(reset_block=True) return new_block def append_connection(self, new_conn=None, from_block=None, to_block=None) -> Connection: if new_conn is None: new_conn = Connection(self.__get_empty_index()) self.__try_append_connection(new_conn, from_block, is_input=False) self.__try_append_connection(new_conn, to_block, is_input=True) if not new_conn in self.connection_list: self.connection_list.append(new_conn) self.__reset_IDs(reset_block=False) return new_conn def remove_block(self, block, disconnect_block=True): if block in self.block_list: if disconnect_block: block.disconnect_block() self.block_list.remove(block) else: warningString = "" warningString += "You're trying to delete " warningString += str(block) + " from block list but " warningString += "that block isn't in the list" warnings.warn(warningString) self.__reset_IDs(reset_block=True) def remove_connection(self, connection): if connection in self.connection_list: if not connection.is_system_input: self.block_list[connection.fromID].remove_connection(connection) if connection.is_block_input: self.block_list[connection.toID].remove_connection(connection) self.connection_list.remove(connection) else: warningString = "" warningString += "You're trying to delete " warningString += str(connection) + " from connection list but " warningString += "that connection isn't in the list" warnings.warn(warningString) self.__reset_IDs(reset_block=False) def __try_append_connection(self, new_conn, block_input, is_input): if not block_input is None: if issubclass(type(block_input), Block) or type(block_input) is Block: block_input.add_connection(new_conn, is_input=is_input) else: try: self.block_list[int(block_input)].add_connection(new_conn, is_input=is_input) except: warningString = "" warningString += str(block_input) + " is not an accepted input" warnings.warn(warningString) # ------------------------------------- # -- Elements Identification Methods -- # ------------------------------------- def find_connection_by_index(self, index): for conn in self.connection_list: try: if conn.index == index: return conn except: pass return None def find_block_by_ID(self, ID): ID = int(ID) for block in self.block_list: try: if block.ID == ID: return block except: pass return None def find_connection_by_ID(self, ID): ID = int(ID) for conn in self.connection_list: try: if conn.ID == ID: return conn except: pass return None @property def standard_block_IDs(self): IDs = list() for block in self.block_list: if not block.is_support_block: IDs.append(block.ID) return IDs @property def standard_conn_IDs(self): IDs = list() for conn in self.connection_list: if not conn.is_internal_stream: IDs.append(conn.ID) return IDs @property def useful_effect_connections(self): return_list = list() for conn in self.connection_list: if conn.is_useful_effect: return_list.append(conn) return return_list @property def system_inputs(self): return_list = list() for conn in self.connection_list: if conn.is_system_input: return_list.append(conn) return return_list @property def system_outputs(self): return_list = list() for conn in self.connection_list: if conn.is_useful_effect or conn.is_loss: return_list.append(conn) return return_list @property def non_dissipative_blocks(self): return_list = list() for block in self.block_list: if not block.is_dissipative: return_list.append(block) return return_list # ------------------------------------- # ------- Input/Output Methods -------- # ------------------------------------- def append_excel_costs_and_useful_output(self, input_list, add_useful_output, input_cost): for elem in input_list: new_conn = self.find_connection_by_index(elem) if not new_conn is None: if add_useful_output: new_conn.is_useful_effect = True else: new_conn.rel_cost = input_cost # Overloaded Methods @property def xml(self) -> ETree.Element: data = ETree.Element("data") data.append(self.options.xml) # <--------- CONNECTIONS DEFINITION ---------> connections = ETree.SubElement(data, "connections") for connection in self.connection_list: if not (connection.is_internal_stream or connection.automatically_generated_connection): connections.append(connection.xml) # <--------- BLOCKS DEFINITION ---------> blocks = ETree.SubElement(data, "blocks") for block in self.block_list: if not block.is_support_block: blocks.append(block.xml) return data @xml.setter def xml(self, xml_input: ETree.Element): self.options.xml = xml_input.find("options") conn_list = xml_input.find("connections") block_list = xml_input.find("blocks") for conn in conn_list.findall("connection"): new_conn = self.append_connection() new_conn.xml = conn for block in block_list.findall("block"): new_block = self.append_block(block.get("type")) new_block.xml = block # ------------------------------------- # ---------- Support Methods ---------- # ------------------------------------- def import_correct_sub_class(self, subclass_name): return self.modules_handler.import_correct_sub_class(subclass_name) def get_pf_diagram(self): if self.has_pf_diagram: return self.pf_diagram else: from EEETools.MainModules.pf_diagram_generation_module import PFArrayHandler self.prepare_system() self.pf_diagram = PFArrayHandler(self) return self.pf_diagram @property def is_ready_for_calculation(self): for block in self.block_list: if not block.is_ready_for_calculation: return False return True @property def there_are_dissipative_blocks(self): for block in self.block_list: if block.is_dissipative: return True return False @property def has_pf_diagram(self): return self.pf_diagram is not None # ------------------------------------- # ---- Elements Sequencing Methods ---- # ------------------------------------- def __reset_IDs(self, reset_block=True): if reset_block: elem_list = self.block_list else: elem_list = self.connection_list i = 0 elem_list.sort() for elem in elem_list: elem.modify_ID(i) i += 1 self.n_block = len(self.block_list) self.n_connection = len(self.connection_list) def __update_block_list(self): # this method asks the blocks to generate their own support blocks (if needed) and appends them to the # block list. Finally, it orders the lists and reset the IDs. for block in self.block_list: if block.has_support_block: block_list = block.support_block self.append_block(block_list) self.__reset_IDs(reset_block=True) def __move_skipped_element_at_the_end(self): for block in self.block_list: block.move_skipped_block_at_the_end = True self.__reset_IDs(reset_block=True) for block in self.block_list: block.move_skipped_block_at_the_end = False def __get_empty_index(self): i = 0 j = 0 while np.power(10, i) < self.n_connection: i += 1 while self.find_connection_by_index(int(np.power(10, i)) + j) is not None: j += 1 return int(np.power(10, i)) + j @property def blocks_by_index(self): new_block_list = list() for block in self.block_list: inserted = False for i in range(len(new_block_list)): if new_block_list[i].index > block.index: new_block_list.insert(i, block) inserted = True break if not inserted: new_block_list.append(block) return new_block_list def __str__(self): # enables printing and str() method # e.g. str(ArrayHandler1) will result in: # # "Array Handler with 2 blocks and 5 connections # # blocks: # Block (ID: 0, name: Expander 1) # Block (ID: 1, name: Compressor 1)" # # connections: # Connection (ID: 0, name: a, from: -1, to: 0) # Connection (ID: 1, name: b, from: -1, to: 1) # Connection (ID: 2, name: c, from: 1, to: 0) # Connection (ID: 3, name: d, from: 0, to: -1) # Connection (ID: 4, name: e, from: 0, to: -1)" string2_print = "Array Handler with " if self.n_block == 0: string2_print += "No Blocks" elif self.n_block == 1: string2_print += "1 Block" else: string2_print += str(self.n_block) + " Blocks" string2_print += " and " if self.n_connection == 0: string2_print += "No Connections" elif self.n_connection == 1: string2_print += "1 Connection" else: string2_print += str(self.n_connection) + " Connections" if self.n_block > 0: string2_print += "\n\nBlocks:" for block in self.block_list: if not block.is_support_block: string2_print += "\n" + "\t" + "\t" + str(block) if self.n_connection > 0: string2_print += "\n\nConnections:" for conn in self.connection_list: if not conn.is_internal_stream: string2_print += "\n" + "\t" + "\t" + str(conn) string2_print += "\n" + "\n" return string2_print def __repr__(self): # enables simple representation # e.g. BlockList1 will result in: # # "Array Handler with 2 blocks and 5 connections # # blocks: # Block (ID: 0, name: Expander 1) # Block (ID: 1, name: Compressor 1)" # # connections: # Connection (ID: 0, name: a, from: -1, to: 0) # Connection (ID: 1, name: b, from: -1, to: 1) # Connection (ID: 2, name: c, from: 1, to: 0) # Connection (ID: 3, name: d, from: 0, to: -1) # Connection (ID: 4, name: e, from: 0, to: -1)" return str(self) class CalculationOptions: # DISSIPATIVE COMPONENTS REDISTRIBUTION METHODS EXERGY_DESTRUCTION = 0 EXERGY_PRODUCT = 1 RELATIVE_COST = 2 def __init__(self): self.calculate_on_pf_diagram = True self.loss_cost_is_zero = True self.valve_is_dissipative = True self.condenser_is_dissipative = True self.redistribution_method = CalculationOptions.RELATIVE_COST self.calculate_component_decomposition = True @property def xml(self) -> ETree.Element: option_child = ETree.Element("options") option_child.set("calculate_on_pf_diagram", str(self.calculate_on_pf_diagram)) option_child.set("loss_cost_is_zero", str(self.loss_cost_is_zero)) option_child.set("valve_is_dissipative", str(self.valve_is_dissipative)) option_child.set("condenser_is_dissipative", str(self.condenser_is_dissipative)) option_child.set("redistribution_method", str(self.redistribution_method)) option_child.set("calculate_component_decomposition", str(self.calculate_component_decomposition)) return option_child @xml.setter def xml(self, xml_input: ETree.Element): self.calculate_on_pf_diagram = xml_input.get("calculate_on_pf_diagram") == "True" self.loss_cost_is_zero = xml_input.get("loss_cost_is_zero") == "True" self.valve_is_dissipative = xml_input.get("valve_is_dissipative") == "True" self.condenser_is_dissipative = xml_input.get("condenser_is_dissipative") == "True" self.redistribution_method = int(xml_input.get("redistribution_method")) self.calculate_component_decomposition = xml_input.get("calculate_component_decomposition") == "True"
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/MainModules/main_module.py
main_module.py
from EEETools.MainModules.main_module import Connection, ArrayHandler, Block from EEETools.BlockSubClasses.generic import Generic class ProductBlock(Generic): def __init__(self, inputID, main_class, base_block: Block): super().__init__(inputID, main_class) self.base_block = base_block self.name = base_block.name self.contained_blocks = [base_block] self.contained_connection = list() def add_connection(self, new_connection, is_input, append_to_support_block=None): super(ProductBlock, self).add_connection( new_connection, is_input, append_to_support_block=append_to_support_block ) if not is_input: self.contained_connection.append(new_connection) def append_output_cost(self, defined_steam_cost): super().append_output_cost(defined_steam_cost) self.base_block.append_output_cost(defined_steam_cost) for outConn in self.contained_connection: if outConn.is_loss and self.main_class.options.loss_cost_is_zero: outConn.set_cost(0.) else: outConn.set_cost(self.output_cost) def generate_output_cost_decomposition(self, inverse_matrix_row): super(ProductBlock, self).generate_output_cost_decomposition(inverse_matrix_row) for block in self.contained_blocks: block.output_cost_decomposition = self.output_cost_decomposition def find_product_connections(self): for conn in self.base_block.output_connections: self.__check_connection(conn) self.__set_comp_cost() def contains(self, element): if "Connection" in str(type(element)) or issubclass(type(element), Connection): return element in self.contained_connection else: return element in self.contained_blocks def calculate_coefficients(self, total_destruction): super(ProductBlock, self).calculate_coefficients(total_destruction) self.base_block.coefficients = self.coefficients def __check_connection(self, conn): if conn.is_system_output: self.main_class.generate_product_connection(conn, from_product_block=self) else: new_block = conn.to_block if not self.main_class.contains(new_block): if new_block.can_be_removed_in_pf_definition: self.contained_connection.append(conn) self.contained_blocks.append(new_block) for conn in new_block.output_connections: self.__check_connection(conn) else: self.main_class.generate_product_block(new_block, input_connection=conn, from_block=self) else: self.main_class.generate_product_connection(conn, from_product_block=self, to_product_block=self.main_class.find_element(new_block)) def __set_comp_cost(self): self.comp_cost = 0 for block in self.contained_blocks: self.comp_cost += block.comp_cost def this_has_higher_skipping_order(self, other): return None def this_has_higher_support_block_order(self, this, other): return None class ProductConnection(Connection): def __init__(self, base_connection: Connection): super().__init__(base_connection.ID) self.base_connection = base_connection self.name = self.base_connection.name self.exergy_value = base_connection.exergy_value self.rel_cost = base_connection.rel_cost self.is_useful_effect = base_connection.is_useful_effect self.is_fluid_stream = base_connection.is_fluid_stream @property def abs_cost(self) -> float: return self.rel_cost * self.exergy_value @property def rel_cost(self) -> float: return self.base_connection.rel_cost @rel_cost.setter def rel_cost(self, rel_cost_input): self.__rel_cost = rel_cost_input self.base_connection.rel_cost = rel_cost_input class PFArrayHandler(ArrayHandler): # ------------------------------------- # ------ Initialization Methods ------ # ------------------------------------- def __init__(self, base_array_handler: ArrayHandler): super().__init__() self.base_array_handler = base_array_handler self.__generate_lists() self.__identify_support_blocks() def __generate_lists(self): for connection in self.base_array_handler.system_inputs: new_block = connection.to_block self.generate_product_block(new_block, input_connection=connection) def __identify_support_blocks(self): for prod_block in self.block_list: if prod_block.base_block.is_support_block: prod_block.is_support_block = True prod_block.main_block = self.find_element(prod_block.base_block.first_non_support_block) def generate_product_connection(self, input_connection: Connection, from_product_block=None, to_product_block=None): new_conn = ProductConnection(input_connection) self.append_connection(new_conn, from_block=from_product_block, to_block=to_product_block) def generate_product_block(self, input_block: Block, input_connection=None, from_block=None): new_block = self.find_element(input_block) if new_block is None: new_block = self.__append_new_product_block(input_block, input_connection, from_block) new_block.find_product_connections() elif input_connection is not None: self.generate_product_connection( input_connection, to_product_block=new_block, from_product_block=from_block ) def __append_new_product_block(self, input_block: Block, input_connection, from_block) -> ProductBlock: new_block = ProductBlock(self.n_block, self, input_block) self.append_block(new_block) if input_connection is not None: self.generate_product_connection( input_connection, to_product_block=new_block, from_product_block=from_block ) return new_block # ------------------------------------- # ---------- Support Methods ---------- # ------------------------------------- def find_element(self, element): for prod_block in self.block_list: if prod_block.contains(element): return prod_block return None def contains(self, element): return self.find_element(element) is not None def get_pf_diagram(self): return self
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/MainModules/pf_diagram_generation_module.py
pf_diagram_generation_module.py
from xml.etree import ElementTree as ETree from EEETools.MainModules import Block, ArrayHandler class Drawer(Block): # This class is a simple block subclass that will be used for the definition of support blocks. See the component # documentation for further explanations. # # For the initialization both the input_ID and the main block to which the drawer is connected as a support block # are required. Another optional argument has to be passed if the drawer is intended to be added to handle the # outputs of the main block def __init__(self, main_class: ArrayHandler, main_block: Block, is_input=True, allow_multiple_input=True): super().__init__(-100, main_class, is_support_block=True) self.index = float(main_block.ID) + (float(len(main_block.support_block)) + 1.) / 100. self.type = "drawer" self.name = "Support block of: " + str(main_block.name) self.main_block = main_block self.is_input = is_input self.connection_with_main = None self.input_mixer = None self.output_separator = None self.allow_multiple_input = allow_multiple_input def add_connection(self, new_connection, is_input, append_to_support_block=None): # The "add_connection" method has been overloaded because we want the drawer to have only 3 connection (1 input, # 1 output and the "connection_with_main") if the "allow_multiple_input" option is not on. This is needed # because of some issue with the EES code generation. # # The overloaded method calls the super method if the maximum number of connection has not been reached or if # the "allow_multiple_input" option is on. Otherwise it will add the connection to a support_block (it choose # the right ones between the "input_mixer" or "output_separator" blocks depending on whether the connection # to be added is an input or an output) and initialize the support block itself if needed, by calling # "__append_support_block". if is_input: n_connection = self.n_input if self.connection_with_main is not None and not self.is_input: n_connection -= 1 support_block = self.input_mixer else: n_connection = self.n_output if self.connection_with_main is not None and self.is_input: n_connection -= 1 support_block = self.output_separator if self.allow_multiple_input or n_connection < 1: super(Drawer, self).add_connection(new_connection, is_input, append_to_support_block) else: if support_block is None: support_block = self.__append_support_block(is_input) support_block.add_connection(new_connection, is_input) def remove_connection(self, deleted_conn): # The "remove_connection" method has been overloaded because we want the drawer to have only 3 connection (1 # input, 1 output and the "connection_with_main") if the "allow_multiple_input" option is not on. This is # needed because of some issue with the EES code generation. # # This method calls the super method to remove the connection. Then it checks if the support block (if # present) is still needed and remove it otherwise super(Drawer, self).remove_connection(deleted_conn) self.__check_support_blocks() def is_ready_for_calculation(self): return_value = self.n_input >= 1 and self.n_output >= 1 if self.has_support_block: for block in self.support_block: return_value = return_value and block.is_ready_for_calculation() return return_value def prepare_for_calculation(self): if self.has_support_block: for block in self.support_block: block.prepare_for_calculation() self.update_main_connection() def initialize_connection_list(self, input_list): for elem in input_list: new_conn = self.main_class.find_connection_by_index(abs(elem)) if not new_conn is None: is_input = (elem > 0) self.add_connection(new_conn, is_input) def connection_is_in_connections_list(self, connection): for connection_list in [self.input_connections, self.output_connections]: if connection in connection_list: return True if self.has_support_block: for block in self.support_block: if block.connection_is_in_connections_list(connection): return True return False def get_fluid_stream_connections(self): connection_list = super(Drawer, self).get_fluid_stream_connections() if self.has_support_block: for block in self.support_block: connection_list.extend(block.get_fluid_stream_connections()) return connection_list def return_other_zone_connections(self, zone_type, input_connection): return self.main_block.return_other_zone_connections(zone_type, input_connection) def initialize_main_connection(self): # connect support block with main class if self.is_input: self.__add_connection_manually(self, self.main_block, is_connection_with_main=True) else: self.__add_connection_manually(self.main_block, self, is_connection_with_main=True) def update_main_connection(self): if self.connection_with_main is None: self.initialize_main_connection() self.connection_with_main.is_fluid_stream = False if self.is_input: self.connection_with_main.exergy_value += self.exergy_balance else: self.connection_with_main.exergy_value -= self.exergy_balance def __add_connection_manually(self, from_block, to_block, is_connection_with_main=False): new_connection = self.main_class.append_connection() new_connection.set_block(from_block, is_from_block=True) from_block.output_connections.append(new_connection) from_block.n_output += 1 new_connection.set_block(to_block, is_from_block=False) to_block.input_connections.append(new_connection) to_block.n_input += 1 if is_connection_with_main: self.connection_with_main = new_connection def __append_support_block(self, is_input=True): # This class append an input mixer or an output separator if needed. In fact, drawer class is designed to # accept only 3 connections: 1 input, 1 output and the "connection_with_main" because of some issues # regarding the EES code definition. # # In order to deal with such limitation the derawer class is designed so that it will automatically append an # input mixer or an output separator so that it can replicate a multiple connection behaviour. # # This method initializes the support block (it choose between "input_mixer" and "output_separator" according # to the "is_input" parameter). It then moves all the input (or output) connections except for the # "connection_with_main" to the new block and generate the connection between the new support block and the # drawer class. self.has_support_block = True modules_handler = self.main_class.modules_handler if is_input: block_subclass = get_drawer_sub_class("mixer", modules_handler) self.input_mixer = block_subclass(self.main_class, self, True) self.support_block.append(self.input_mixer) for connection in self.input_connections: if connection is not self.connection_with_main: self.input_mixer.add_connection(connection, is_input=True) self.input_connections = list() self.n_input = 0 self.input_mixer.initialize_main_connection() return self.input_mixer else: block_subclass = get_drawer_sub_class("separator", modules_handler) self.output_separator = block_subclass(self.main_class, self, False) self.support_block.append(self.output_separator) for connection in self.output_connections: if connection is not self.connection_with_main: self.output_separator.add_connection(connection, is_input=False) self.output_connections = list() self.n_output = 0 self.output_separator.initialize_main_connection() return self.output_separator def __check_support_blocks(self): has_support_block = False if self.input_mixer is not None: if not self.input_mixer.is_needed: self.input_mixer.disconnect() self.support_block.remove(self.input_mixer) self.input_mixer = None else: has_support_block = True if self.output_separator is not None: if not self.output_separator.is_needed: self.output_separator.disconnect() self.support_block.remove(self.output_separator) self.output_separator = None else: has_support_block = True self.has_support_block = has_support_block @property def is_connected(self): return not self.connection_with_main is None def __str__(self): self.name = "Support block of: " + str(self.main_block.name) return super(Drawer, self).__str__() def export_xml_connection_list(self) -> ETree.Element: pass def append_xml_connection_list(self, input_list: ETree.Element): pass @classmethod def return_EES_needed_index(cls): pass @classmethod def return_EES_base_equations(cls): pass def get_drawer_sub_class(block_subclass_name, modules_handler): block_subclass = modules_handler.import_correct_sub_class(block_subclass_name) class SupportSeparator(block_subclass): def __init__(self, main_class: ArrayHandler, main_block: Block, is_input=None): super().__init__(-100, main_class) self.is_support_block = True self.main_block = main_block self.__define_is_input(is_input) self.type += "-support block" self.name = "Support block of: " + str(main_block.name) self.connection_with_main = None def initialize_main_connection(self): if self.is_input: self.connection_with_main = self.main_class.append_connection(from_block=self, to_block=self.main_block) else: self.connection_with_main = self.main_class.append_connection(from_block=self.main_block, to_block=self) def update_main_connection(self): if self.connection_with_main is None: self.initialize_main_connection() if self.is_input: self.connection_with_main.exergy_value += self.__return_exergy_balance() else: self.connection_with_main.exergy_value -= self.__return_exergy_balance() def disconnect(self): if self.is_input: connection_list = self.input_connections else: connection_list = self.output_connections if self.connection_with_main is not None: self.main_class.remove_connection(self.connection_with_main) for conn in connection_list: self.main_block.add_connection(conn, is_input=self.is_input) def prepare_for_calculation(self): self.update_main_connection() def is_ready_for_calculation(self): return self.n_input >= 1 and self.n_output >= 1 def __return_exergy_balance(self): exergy_balance = 0 for conn in self.input_connections: exergy_balance += conn.exergy_value for conn in self.output_connections: exergy_balance -= conn.exergy_value return exergy_balance def __define_is_input(self, is_input): if is_input is None: if self.type == "mixer": self.is_input = True elif self.type == "separator": self.is_input = False else: self.is_input = False else: self.is_input = is_input @property def is_needed(self): if self.is_input: return self.n_input > 1 else: return self.n_output > 1 @property def is_connected(self): return not self.connection_with_main is None return SupportSeparator def get_support_block_sub_class(block_subclass_name, modules_handler): block_subclass = modules_handler.import_correct_sub_class(block_subclass_name) class SupportSeparator(block_subclass): def __init__(self, main_class: ArrayHandler, main_block: Block, is_input=None): super().__init__(-100, main_class) self.is_support_block = True self.main_block = main_block self.__define_is_input(is_input) self.type += "-support block" self.name = "Support block of: " + str(main_block.name) self.connection_with_main = None def initialize_main_connection(self): if self.is_input: self.connection_with_main = self.main_class.append_connection(from_block=self, to_block=self.main_block) else: self.connection_with_main = self.main_class.append_connection(from_block=self.main_block, to_block=self) def update_main_connection(self): if self.connection_with_main is None: self.initialize_main_connection() if self.is_input: self.connection_with_main.exergy_value += self.__return_exergy_balance() else: self.connection_with_main.exergy_value -= self.__return_exergy_balance() def disconnect(self): if self.is_input: connection_list = self.input_connections else: connection_list = self.output_connections if self.connection_with_main is not None: self.main_class.remove_connection(self.connection_with_main) for conn in connection_list: self.main_block.add_connection(conn, is_input=self.is_input) def prepare_for_calculation(self): self.update_main_connection() def is_ready_for_calculation(self): return self.n_input >= 1 and self.n_output >= 1 def __return_exergy_balance(self): exergy_balance = 0 for conn in self.input_connections: exergy_balance += conn.exergy_value for conn in self.output_connections: exergy_balance -= conn.exergy_value return exergy_balance def __define_is_input(self, is_input): if is_input is None: if self.type == "mixer": self.is_input = True elif self.type == "separator": self.is_input = False else: self.is_input = False else: self.is_input = is_input @property def is_needed(self): if self.is_input: return self.n_input > 1 else: return self.n_output > 1 @property def is_connected(self): return not self.connection_with_main is None return SupportSeparator
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/MainModules/support_blocks.py
support_blocks.py
from .main_module import Block, Connection, ArrayHandler
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/MainModules/__init__.py
__init__.py
from EEETools.MainModules.support_blocks import Drawer from EEETools.MainModules.main_module import Block import xml.etree.ElementTree as ETree from EEETools import costants class Cooler(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) self.type = "cooler" self.has_support_block = True self.support_block.append(Drawer(main_class, self, is_input=True)) def is_ready_for_calculation(self): return len(self.input_connections) >= 1 and len(self.output_connections) >= 1 def prepare_for_calculation(self): self.support_block[0].prepare_for_calculation() def initialize_connection_list(self, input_list): new_power_conn = self.main_class.find_connection_by_index(input_list[0]) new_input_conn = self.main_class.find_connection_by_index(input_list[1]) new_output_conn = self.main_class.find_connection_by_index(input_list[2]) self.add_connection(new_power_conn, is_input=False) self.add_connection(new_input_conn, is_input=True, append_to_support_block=0) self.add_connection(new_output_conn, is_input=False, append_to_support_block=0) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fluid_connections = ETree.SubElement(xml_connection_list, "FluidConnections") for input_connection in self.support_block[0].external_input_connections: input_xml = ETree.SubElement(fluid_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in self.support_block[0].external_output_connections: output_xml = ETree.SubElement(fluid_connections, "output") output_xml.set("index", str(output_connection.index)) power_connections = ETree.SubElement(xml_connection_list, "PowerConnections") for output_connection in self.external_output_connections: output_xml = ETree.SubElement(power_connections, "output") output_xml.set("index", str(output_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fluid_connections = input_list.find("FluidConnections") PowerConnections = input_list.find("PowerConnections") self.__add_connection_by_index(fluid_connections, "input", append_to_support_block=0) self.__add_connection_by_index(fluid_connections, "output", append_to_support_block=0) self.__add_connection_by_index(PowerConnections, "output") def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) @classmethod def return_EES_needed_index(cls): return_dict = {"flow input": [1, False], "flow output": [2, False]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable": "flow input", "type": costants.ZONE_TYPE_FLOW_RATE}, {"variable": "flow output", "type": costants.ZONE_TYPE_FLOW_RATE}] return_element.update({"mass_continuity": {"variables": variables_list, "related_option": "none"}}) variables_list = [{"variable": "flow input", "type": costants.ZONE_TYPE_PRESSURE}, {"variable": "flow output", "type": costants.ZONE_TYPE_PRESSURE}] return_element.update({"pressure_continuity": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In the cooler flow rate is preserved, hence if "input_connection" stream is connected to the condenser # block the methods must returns each fluid stream connected to that block if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In the condenser fluid type is preserved, hence if "input_connection" stream is connected to the condenser # block the methods must returns each fluid stream connected to that block if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In the condenser pressure is preserved, hence if "input_connection" stream is connected to the condenser # block the methods must returns each fluid stream connected to that block if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/cooler.py
cooler.py
from EEETools.MainModules import Block from EEETools.MainModules.support_blocks import Drawer import xml.etree.ElementTree as ETree class Alternator(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) self.type = "alternator" self.has_support_block = True self.support_block.append(Drawer(main_class, self)) self.efficiency = 1. def add_connection_to_support_block(self, new_connection, is_input): self.support_block[0].add_connection(new_connection, is_input, ) def is_ready_for_calculation(self): return len(self.support_block[0].input_connections) >= 1 def prepare_for_calculation(self): self.support_block[0].prepare_for_calculation() new_conn = self.main_class.append_connection(from_block=self) new_conn.name = "Electrical Power Output" new_conn.is_useful_effect = True new_conn.automatically_generated_connection = True new_conn.exergy_value = self.exergy_balance def initialize_connection_list(self, input_list): self.efficiency = float(input_list[0]) for elem in input_list[1:]: new_conn = self.main_class.find_connection_by_index(abs(elem)) if not new_conn is None: is_input = (elem > 0) new_conn.is_fluid_stream = False if is_input: self.add_connection(new_conn, is_input, append_to_support_block=0) else: self.add_connection(new_conn, is_input) def export_xml_other_parameters(self) -> ETree.Element: other_tree = ETree.Element("efficiency") other_tree.set("value", str(self.efficiency)) return other_tree def append_xml_other_parameters(self, input_list: ETree.Element): efficiency_tree = input_list.find("efficiency") self.efficiency = float(efficiency_tree.get("value")) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") mechanical_connections = ETree.SubElement(xml_connection_list, "MechanicalConnections") for input_connection in self.support_block[0].external_input_connections: if not input_connection.automatically_generated_connection: input_xml = ETree.SubElement(mechanical_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in self.support_block[0].external_output_connections: if not output_connection.automatically_generated_connection: output_xml = ETree.SubElement(mechanical_connections, "output") output_xml.set("index", str(output_connection.index)) electrical_connections = ETree.SubElement(xml_connection_list, "ElectricalConnections") for input_connection in self.external_input_connections: if not input_connection.automatically_generated_connection: input_xml = ETree.SubElement(electrical_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in self.external_output_connections: if not output_connection.automatically_generated_connection: output_xml = ETree.SubElement(electrical_connections, "output") output_xml.set("index", str(output_connection.index)) a = ETree.tostring(xml_connection_list) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): mechanical_connections = input_list.find("MechanicalConnections") electrical_connections = input_list.find("ElectricalConnections") self.__add_connection_by_index(mechanical_connections, "input", append_to_support_block=0) self.__add_connection_by_index(mechanical_connections, "output", append_to_support_block=0) self.__add_connection_by_index(electrical_connections, "input") self.__add_connection_by_index(electrical_connections, "output") def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) @classmethod def return_EES_needed_index(cls): # Alternator has multiple input and outputs for exergy flux: return_dict = {"global output": [0, False], "mechanical input": [1, True], "mechanical output": [2, True], "electrical input": [3, True], "electrical output": [4, True]} return return_dict @classmethod def return_EES_base_equations(cls): # WARNING: This methods must be overloaded in subclasses!! # This methods returns a dictionary that contain a list of streams that have to be present in the EES text # definition. return dict() @property def exergy_balance(self): exergy_balance = 0 for conn in self.input_connections: if conn == self.support_block[0].connection_with_main: exergy_balance += conn.exergy_value * self.efficiency else: exergy_balance += conn.exergy_value for conn in self.output_connections: exergy_balance -= conn.exergy_value return exergy_balance @property def can_be_removed_in_pf_definition(self): return False def return_other_zone_connections(self, zone_type, input_connection): # Alternator is connected only to energy streams, hence it is not interested in the zones generation process return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/alternator.py
alternator.py
from EEETools.MainModules.support_blocks import Drawer from EEETools.MainModules import Block import xml.etree.ElementTree as ETree from EEETools import costants class Valve(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) self.type = "valve" if self.main_class.options.valve_is_dissipative: self.has_support_block = True self.support_block.append(Drawer(main_class, self, is_input=True)) else: self.has_support_block = False def is_ready_for_calculation(self): return len(self.input_connections) >= 1 and len(self.output_connections) >= 1 def prepare_for_calculation(self): if self.main_class.options.valve_is_dissipative: self.support_block[0].prepare_for_calculation() def initialize_connection_list(self, input_list): new_input_conn = self.main_class.find_connection_by_index(input_list[0]) new_output_conn = self.main_class.find_connection_by_index(input_list[1]) if self.main_class.options.valve_is_dissipative: self.add_connection(new_input_conn, is_input=True, append_to_support_block=0) self.add_connection(new_output_conn, is_input=False, append_to_support_block=0) else: self.add_connection(new_input_conn, is_input=True) self.add_connection(new_output_conn, is_input=False) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fluid_connections = ETree.SubElement(xml_connection_list, "FluidConnections") if self.main_class.options.valve_is_dissipative: input_connections = self.support_block[0].external_input_connections output_connections = self.support_block[0].external_output_connections else: input_connections = self.external_input_connections output_connections = self.external_output_connections for input_connection in input_connections: if not input_connection.automatically_generated_connection: input_xml = ETree.SubElement(fluid_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in output_connections: if not output_connection.automatically_generated_connection: output_xml = ETree.SubElement(fluid_connections, "output") output_xml.set("index", str(output_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fluid_connections = input_list.find("FluidConnections") if self.main_class.options.valve_is_dissipative: self.__add_connection_by_index(fluid_connections, "input", append_to_support_block=0) self.__add_connection_by_index(fluid_connections, "output", append_to_support_block=0) else: self.__add_connection_by_index(fluid_connections, "input") self.__add_connection_by_index(fluid_connections, "output") def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) @classmethod def return_EES_needed_index(cls): return_dict = {"flow input" : [1, False], "flow output": [2, False]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable": "flow input", "type": costants.ZONE_TYPE_FLOW_RATE}, {"variable": "flow output", "type": costants.ZONE_TYPE_FLOW_RATE}] return_element.update({"mass_continuity": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In a valve the flow rate is preserved, hence if "input_connection" stream is connected to the # block the methods returns each fluid stream connected to it if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In a valve the fluid type is preserved, hence if "input_connection" stream is connected to the # block the methods returns each fluid stream connected to it if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In a valve the pressure is not preserved, hence an empty list is returned return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/valve.py
valve.py
from EEETools.MainModules import Block from EEETools.MainModules.support_blocks import Drawer import xml.etree.ElementTree as ETree from EEETools import costants class Boiler(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) self.type = "boiler" self.has_support_block = True self.support_block.append(Drawer(main_class, self, is_input=False, allow_multiple_input=False)) def add_connection_to_support_block(self, new_connection, is_input): self.support_block[0].add_connection(new_connection, is_input, ) def is_ready_for_calculation(self): return len(self.input_connections) >= 1 and len(self.support_block[0].output_connections) >= 1 and len( self.support_block[0].input_connections) >= 1 def initialize_connection_list(self, input_list): new_conn_fuel_in = self.main_class.find_connection_by_index(abs(input_list[0])) new_conn_input_flow = self.main_class.find_connection_by_index(abs(input_list[1])) new_conn_output_flow = self.main_class.find_connection_by_index(abs(input_list[2])) new_conn_fuel_in.is_fluid_stream = False self.add_connection(new_conn_fuel_in, is_input=True) self.add_connection(new_conn_input_flow, is_input=True, append_to_support_block=0) self.add_connection(new_conn_output_flow, is_input=False, append_to_support_block=0) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fluid_connections = ETree.SubElement(xml_connection_list, "FluidConnections") for input_connection in self.support_block[0].external_input_connections: input_xml = ETree.SubElement(fluid_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in self.support_block[0].external_output_connections: output_xml = ETree.SubElement(fluid_connections, "output") output_xml.set("index", str(output_connection.index)) fuel_connections = ETree.SubElement(xml_connection_list, "FuelConnections") for input_connection in self.external_input_connections: input_xml = ETree.SubElement(fuel_connections, "input") input_xml.set("index", str(input_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fluid_connections = input_list.find("FluidConnections") fuel_connections = input_list.find("FuelConnections") self.__add_connection_by_index(fluid_connections, "input", append_to_support_block=0) self.__add_connection_by_index(fluid_connections, "output", append_to_support_block=0) self.__add_connection_by_index(fuel_connections, "input") def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) @classmethod def return_EES_needed_index(cls): return_dict = {"fuel input": [0, False], "flow input": [1, False], "flow output": [2, False]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable":"flow input", "type": costants.ZONE_TYPE_FLOW_RATE}, {"variable":"flow output","type": costants.ZONE_TYPE_FLOW_RATE}] return_element.update({"mass_continuity": {"variables": variables_list, "related_option": "none"}}) variables_list = [{"variable": "flow input", "type": costants.ZONE_TYPE_PRESSURE}, {"variable": "flow output", "type": costants.ZONE_TYPE_PRESSURE}] return_element.update({"pressure_continuity": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In the boiler flow rate is preserved, hence if "input_connection" stream is connected to the support # block (where the fluid streams are connected) the methods returns each fluid stream connected to the # support block if self.support_block[0].connection_is_in_connections_list(input_connection): return self.support_block[0].get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In the boiler fluid type is preserved, hence if "input_connection" stream is connected to the support # block (where the fluid streams are connected) the methods returns each fluid stream connected to the # support block if self.support_block[0].connection_is_in_connections_list(input_connection): return self.support_block[0].get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In the boiler pressure is preserved, hence if "input_connection" stream is connected to the support # block (where the fluid streams are connected) the methods returns each fluid stream connected to the # support block if self.support_block[0].connection_is_in_connections_list(input_connection): return self.support_block[0].get_fluid_stream_connections() else: return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/boiler.py
boiler.py
from EEETools.MainModules.support_blocks import Drawer from EEETools.MainModules.main_module import Block import xml.etree.ElementTree as ETree from EEETools import costants class Condenser(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) self.type = "condenser" if self.main_class.options.condenser_is_dissipative: self.has_support_block = True self.support_block.append(Drawer(main_class, self, is_input=True)) else: self.has_support_block = False def is_ready_for_calculation(self): return len(self.input_connections) >= 1 and len(self.output_connections) >= 1 def prepare_for_calculation(self): if self.main_class.options.condenser_is_dissipative: self.support_block[0].prepare_for_calculation() if self.main_class.options.loss_cost_is_zero: new_conn = self.main_class.append_connection(from_block=self) new_conn.name = "Condenser Exergy Loss" new_conn.automatically_generated_connection = True new_conn.exergy_value = self.exergy_balance new_conn.is_fluid_stream = False def initialize_connection_list(self, input_list): new_input_conn = self.main_class.find_connection_by_index(input_list[0]) new_output_conn = self.main_class.find_connection_by_index(input_list[1]) if self.main_class.options.condenser_is_dissipative: self.add_connection(new_input_conn, is_input=True, append_to_support_block=0) self.add_connection(new_output_conn, is_input=False, append_to_support_block=0) else: self.add_connection(new_input_conn, is_input=True) self.add_connection(new_output_conn, is_input=False) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fluid_connections = ETree.SubElement(xml_connection_list, "FluidConnections") if self.main_class.options.condenser_is_dissipative: input_connections = self.support_block[0].external_input_connections output_connections = self.support_block[0].external_output_connections else: input_connections = self.external_input_connections output_connections = self.external_output_connections for input_connection in input_connections: if not input_connection.automatically_generated_connection: input_xml = ETree.SubElement(fluid_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in output_connections: if not output_connection.automatically_generated_connection: output_xml = ETree.SubElement(fluid_connections, "output") output_xml.set("index", str(output_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fluid_connections = input_list.find("FluidConnections") if self.main_class.options.condenser_is_dissipative: self.__add_connection_by_index(fluid_connections, "input", append_to_support_block=0) self.__add_connection_by_index(fluid_connections, "output", append_to_support_block=0) else: self.__add_connection_by_index(fluid_connections, "input") self.__add_connection_by_index(fluid_connections, "output") def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) @classmethod def return_EES_needed_index(cls): return_dict = {"flow input": [1, False], "flow output": [2, False]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable": "flow input", "type": costants.ZONE_TYPE_FLOW_RATE}, {"variable": "flow output", "type": costants.ZONE_TYPE_FLOW_RATE}] return_element.update({"mass_continuity": {"variables": variables_list, "related_option": "none"}}) variables_list = [{"variable": "flow input", "type": costants.ZONE_TYPE_PRESSURE}, {"variable": "flow output", "type": costants.ZONE_TYPE_PRESSURE}] return_element.update({"pressure_continuity": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In the condenser flow rate is preserved, hence if "input_connection" stream is connected to the condenser # block the methods must returns each fluid stream connected to that block if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In the condenser fluid type is preserved, hence if "input_connection" stream is connected to the condenser # block the methods must returns each fluid stream connected to that block if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In the condenser pressure is preserved, hence if "input_connection" stream is connected to the condenser # block the methods must returns each fluid stream connected to that block if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/condenser.py
condenser.py
from EEETools.MainModules import Block from EEETools.MainModules.support_blocks import Drawer import xml.etree.ElementTree as ETree from EEETools import costants class CombustionChamber(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) self.type = "combustion chamber" self.has_support_block = True self.support_block.append(Drawer(main_class, self, is_input=False, allow_multiple_input=False)) def add_connection_to_support_block(self, new_connection, is_input): self.support_block[0].add_connection(new_connection, is_input) def is_ready_for_calculation(self): return len(self.input_connections) >= 1 and len(self.support_block[0].output_connections) >= 1 and len( self.support_block[0].input_connections) >= 1 def initialize_connection_list(self, input_list): new_conn_fuel_in = self.main_class.find_connection_by_index(abs(input_list[0])) new_conn_input_flow = self.main_class.find_connection_by_index(abs(input_list[1])) new_conn_output_flow = self.main_class.find_connection_by_index(abs(input_list[2])) self.add_connection(new_conn_fuel_in, is_input=True) self.add_connection(new_conn_input_flow, is_input=True, append_to_support_block=0) self.add_connection(new_conn_output_flow, is_input=False, append_to_support_block=0) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fluid_connections = ETree.SubElement(xml_connection_list, "FluidConnections") for input_connection in self.support_block[0].external_input_connections: input_xml = ETree.SubElement(fluid_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in self.support_block[0].external_output_connections: output_xml = ETree.SubElement(fluid_connections, "output") output_xml.set("index", str(output_connection.index)) fuel_connections = ETree.SubElement(xml_connection_list, "FuelConnections") for input_connection in self.external_input_connections: input_xml = ETree.SubElement(fuel_connections, "input") input_xml.set("index", str(input_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fluid_connections = input_list.find("FluidConnections") fuel_connections = input_list.find("FuelConnections") self.__add_connection_by_index(fluid_connections, "input", append_to_support_block=0) self.__add_connection_by_index(fluid_connections, "output", append_to_support_block=0) self.__add_connection_by_index(fuel_connections, "input") def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) @classmethod def return_EES_needed_index(cls): return_dict = {"fuel input": [0, False], "flow input": [1, False], "flow output": [2, False]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable": "fuel input", "type": costants.ZONE_TYPE_PRESSURE}, {"variable": "flow input", "type": costants.ZONE_TYPE_PRESSURE}, {"variable": "flow output", "type": costants.ZONE_TYPE_PRESSURE}, ] return_element.update({"pressure_continuity": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In the combustion chamber flow rate is not preserved (input and fuel flows are mixed), hence an empty # list is returned return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In the combustion chamber fluid type is preserved, hence if "input_connection" stream is connected to # the support block (where the fluid streams are connected) the methods returns each fluid stream # connected to the support block. # # (this is an approximation because we consider that the amount of fuel injected is not enough to modify # the main fuel properties, an optional check_box should be considered!!) if self.support_block[0].connection_is_in_connections_list(input_connection): return self.support_block[0].get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In the combustion chamber pressure is preserved, hence if "input_connection" stream is connected to the # support block (where the fluid streams are connected) or to the block itself (where the input is # connected) the methods returns each fluid stream connected to the support block. In addition, # as also the fluid input must have the same pressure, it is added as well! if self.support_block[0].connection_is_in_connections_list(input_connection) or self.connection_is_in_connections_list(input_connection): return_list = list() return_list.extend(self.support_block[0].get_fluid_stream_connections()) return_list.extend(self.get_fluid_stream_connections()) return return_list else: return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/combustion_chamber.py
combustion_chamber.py
from EEETools.MainModules import Block import xml.etree.ElementTree as ETree from EEETools import costants class Separator(Block): def __init__(self, inputID, main_class): Block.__init__(self, inputID, main_class) self.type = "separator" def is_ready_for_calculation(self): return len(self.input_connections) >= 1 and len(self.output_connections) >= 1 def initialize_connection_list(self, input_list): for elem in input_list: new_conn = self.main_class.find_connection_by_index(abs(elem)) if not new_conn is None: is_input = (elem > 0) self.add_connection(new_conn, is_input) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fluid_connections = ETree.SubElement(xml_connection_list, "FluidConnections") for input_connection in self.external_input_connections: input_xml = ETree.SubElement(fluid_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in self.external_output_connections: output_xml = ETree.SubElement(fluid_connections, "output") output_xml.set("index", str(output_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fluid_connections = input_list.find("FluidConnections") self.__add_connection_by_index(fluid_connections, "input") self.__add_connection_by_index(fluid_connections, "output") def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) @classmethod def return_EES_needed_index(cls): return_dict = {"flow input" : [1, False], "flow output": [2, True]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable": "flow input", "type": costants.ZONE_TYPE_PRESSURE}, {"variable": "flow output", "type": costants.ZONE_TYPE_PRESSURE}] return_element.update({"pressure_continuity": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In a separator flow rate is not preserved, hence an empty list is returned return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In a separator fluid type is preserved, hence if "input_connection" stream is connected to the # block the methods returns each fluid stream connected to it if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In a separator pressure is preserved, hence if "input_connection" stream is connected to the # block the methods returns each fluid stream connected to it if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/separator.py
separator.py
from EEETools.MainModules import Block from EEETools.MainModules.support_blocks import Drawer import xml.etree.ElementTree as ETree from EEETools import costants class Compressor(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) self.type = "compressor" self.has_support_block = True self.support_block.append(Drawer(main_class, self, is_input=False, allow_multiple_input=False)) def add_connection_to_support_block(self, new_connection, is_input): self.support_block[0].add_connection(new_connection, is_input) def is_ready_for_calculation(self): return len(self.output_connections) >= 1 and len(self.support_block[0].output_connections) >= 1 and len( self.support_block[0].input_connections) >= 1 def initialize_connection_list(self, input_list): new_conn_power = self.main_class.find_connection_by_index(abs(input_list[0])) new_conn_input_flow = self.main_class.find_connection_by_index(abs(input_list[1])) new_conn_output_flow = self.main_class.find_connection_by_index(abs(input_list[2])) new_conn_power.is_fluid_stream = False self.add_connection(new_conn_power, is_input=True) self.add_connection(new_conn_input_flow, is_input=True, append_to_support_block=0) self.add_connection(new_conn_output_flow, is_input=False, append_to_support_block=0) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fluid_connections = ETree.SubElement(xml_connection_list, "FluidConnections") for input_connection in self.support_block[0].external_input_connections: input_xml = ETree.SubElement(fluid_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in self.support_block[0].external_output_connections: output_xml = ETree.SubElement(fluid_connections, "output") output_xml.set("index", str(output_connection.index)) mechanical_connections = ETree.SubElement(xml_connection_list, "MechanicalConnections") for input_connection in self.external_input_connections: input_xml = ETree.SubElement(mechanical_connections, "input") input_xml.set("index", str(input_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fluid_connections = input_list.find("FluidConnections") mechanical_connections = input_list.find("MechanicalConnections") self.__add_connection_by_index(fluid_connections, "input", append_to_support_block=0) self.__add_connection_by_index(fluid_connections, "output", append_to_support_block=0) self.__add_connection_by_index(mechanical_connections, "input") def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) @classmethod def return_EES_needed_index(cls): return_dict = {"power input": [0, False], "flow input": [1, False], "flow output": [2, False]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable": "flow input", "type": costants.ZONE_TYPE_FLOW_RATE}, {"variable": "flow output", "type": costants.ZONE_TYPE_FLOW_RATE}] return_element.update({"mass_continuity": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In the compressor flow rate is preserved, hence if "input_connection" stream is connected to the support # block (where the fluid streams are connected) the methods returns each fluid stream connected to the # support block if self.support_block[0].connection_is_in_connections_list(input_connection): return self.support_block[0].get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In the compressor fluid type is preserved, hence if "input_connection" stream is connected to the support # block (where the fluid streams are connected) the methods returns each fluid stream connected to the # support block if self.support_block[0].connection_is_in_connections_list(input_connection): return self.support_block[0].get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In the compressor pressure is not preserved, hence an empty list is returned return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/compressor.py
compressor.py
from EEETools.MainModules import Block from EEETools.MainModules.support_blocks import Drawer import xml.etree.ElementTree as ETree from EEETools import costants class Pump(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) self.type = "pump" self.has_support_block = True self.support_block.append(Drawer(main_class, self, is_input=False, allow_multiple_input=False)) def add_connection_to_support_block(self, new_connection, is_input): self.support_block[0].add_connection(new_connection, is_input) def is_ready_for_calculation(self): return len(self.output_connections) >= 1 and len(self.support_block[0].output_connections) >= 1 and len(self.support_block[0].input_connections) >= 1 def initialize_connection_list(self, input_list): new_conn_power = self.main_class.find_connection_by_index(abs(input_list[0])) new_conn_input_flow = self.main_class.find_connection_by_index(abs(input_list[1])) new_conn_output_flow = self.main_class.find_connection_by_index(abs(input_list[2])) self.add_connection(new_conn_power, is_input=True) self.add_connection(new_conn_input_flow, is_input=True, append_to_support_block = 0) self.add_connection(new_conn_output_flow, is_input=False, append_to_support_block = 0) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fluid_connections = ETree.SubElement(xml_connection_list, "FluidConnections") for input_connection in self.support_block[0].external_input_connections: input_xml = ETree.SubElement(fluid_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in self.support_block[0].external_output_connections: output_xml = ETree.SubElement(fluid_connections, "output") output_xml.set("index", str(output_connection.index)) mechanical_connections = ETree.SubElement(xml_connection_list, "MechanicalConnections") for input_connection in self.external_input_connections: input_xml = ETree.SubElement(mechanical_connections, "input") input_xml.set("index", str(input_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fluid_connections = input_list.find("FluidConnections") mechanical_connections = input_list.find("MechanicalConnections") self.__add_connection_by_index(fluid_connections, "input", append_to_support_block=0) self.__add_connection_by_index(fluid_connections, "output", append_to_support_block=0) self.__add_connection_by_index(mechanical_connections, "input") def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) @classmethod def return_EES_needed_index(cls): return_dict = {"power input": [0, False], "flow input": [1, False], "flow output": [2, False]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable": "flow input", "type": costants.ZONE_TYPE_FLOW_RATE}, {"variable": "flow output", "type": costants.ZONE_TYPE_FLOW_RATE}] return_element.update({"mass_continuity": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In a pump the flow rate is preserved, hence if "input_connection" stream is connected to the support # block (where the fluid streams are connected) the methods returns each fluid stream connected to the # support block if self.support_block[0].connection_is_in_connections_list(input_connection): return self.support_block[0].get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In a pump the fluid type is preserved, hence if "input_connection" stream is connected to the support # block (where the fluid streams are connected) the methods returns each fluid stream connected to the # support block if self.support_block[0].connection_is_in_connections_list(input_connection): return self.support_block[0].get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In a pump the pressure is not preserved, hence an empty list is returned return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/pump.py
pump.py
from EEETools.MainModules import Block import xml.etree.ElementTree as ETree from EEETools import costants class Mixer(Block): def __init__(self, inputID, main_class): Block.__init__(self, inputID, main_class) self.type = "mixer" def is_ready_for_calculation(self): return len(self.input_connections) >= 1 and len(self.output_connections) >= 1 def initialize_connection_list(self, input_list): for elem in input_list: new_conn = self.main_class.find_connection_by_index(abs(elem)) if not new_conn is None: is_input = (elem > 0) self.add_connection(new_conn, is_input) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fluid_connections = ETree.SubElement(xml_connection_list, "FluidConnections") for input_connection in self.external_input_connections: input_xml = ETree.SubElement(fluid_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in self.external_output_connections: output_xml = ETree.SubElement(fluid_connections, "output") output_xml.set("index", str(output_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fluid_connections = input_list.find("FluidConnections") self.__add_connection_by_index(fluid_connections, "input") self.__add_connection_by_index(fluid_connections, "output") def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) @classmethod def return_EES_needed_index(cls): return_dict = {"flow input": [1, True], "flow output": [2, False]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable": "flow input", "type": costants.ZONE_TYPE_PRESSURE}, {"variable": "flow output", "type": costants.ZONE_TYPE_PRESSURE}] return_element.update({"pressure_continuity": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In a mixer the flow rate is not preserved, hence an empty list is returned return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In a mixer the fluid type is preserved, hence if "input_connection" stream is connected to the # block the methods returns each fluid stream connected to it if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In a mixer the pressure is preserved, hence if "input_connection" stream is connected to the # block the methods returns each fluid stream connected to it if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/mixer.py
mixer.py
from EEETools.MainModules import Block from EEETools.MainModules.support_blocks import Drawer import xml.etree.ElementTree as ETree from EEETools import costants # EXACTLY THE SAME AS HEAT_EXCHANGER (Maintained only to keep the analogy with Matlab application) class Evaporator(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) self.type = "evaporator" self.has_support_block = True self.support_block.append(Drawer(main_class, self, is_input=True, allow_multiple_input=False)) self.support_block.append(Drawer(main_class, self, is_input=False, allow_multiple_input=False)) def add_new_drawer(self, is_input): self.support_block.append(Drawer(self.main_class, self, is_input=is_input, allow_multiple_input=False)) def is_ready_for_calculation(self): for supp_block in self.support_block: if not supp_block.is_ready_for_calculation: return False return True def initialize_connection_list(self, input_list): new_conn_input_product = self.main_class.find_connection_by_index(abs(input_list[0])) new_conn_output_product = self.main_class.find_connection_by_index(abs(input_list[1])) self.add_connection(new_conn_input_product, is_input=True, append_to_support_block=1) self.add_connection(new_conn_output_product, is_input=False, append_to_support_block=1) for elem in input_list[2:]: new_conn = self.main_class.find_connection_by_index(abs(elem)) if new_conn is not None: is_input = (elem > 0) self.add_connection(new_conn, is_input=is_input, append_to_support_block=0) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fuels_connections = ETree.SubElement(xml_connection_list, "FuelsConnections") product_connections = ETree.SubElement(xml_connection_list, "ProductConnections") for support_block in self.support_block: if support_block.is_input: main_tree = ETree.SubElement(fuels_connections, "Block") else: main_tree = ETree.SubElement(product_connections, "Block") for input_connection in support_block.external_input_connections: input_xml = ETree.SubElement(main_tree, "input") input_xml.set("index", str(input_connection.index)) for output_connection in support_block.external_output_connections: output_xml = ETree.SubElement(main_tree, "output") output_xml.set("index", str(output_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fuels_connections = input_list.find("FuelsConnections") product_connections = input_list.find("ProductConnections") self.__add_support_blocks(len(fuels_connections.findall("Block")), True) self.__add_support_blocks(len(product_connections.findall("Block")), False) i = 0 support_block_array = self.input_support_block for connection in fuels_connections.findall("Block"): self.__add_connection_by_index(connection, "input", append_to_support_block=support_block_array[i]) self.__add_connection_by_index(connection, "output", append_to_support_block=support_block_array[i]) i = i + 1 i = 0 support_block_array = self.output_support_block for connection in product_connections.findall("Block"): self.__add_connection_by_index(connection, "input", append_to_support_block=support_block_array[i]) self.__add_connection_by_index(connection, "output", append_to_support_block=support_block_array[i]) i = i + 1 def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block = append_to_support_block) def __add_support_blocks(self, n_support_blocks, is_input): for i in range(1, n_support_blocks): self.add_new_drawer(is_input) @property def input_support_block(self) -> list: return_list = list() for support_block in self.support_block: if support_block.is_input: return_list.append(support_block) return return_list @property def output_support_block(self) -> list: return_list = list() for support_block in self.support_block: if not support_block.is_input: return_list.append(support_block) return return_list @classmethod def return_EES_needed_index(cls): return_dict = {"input_1": [1, False], "output_1": [1, False], "input_2": [1, False], "output_2": [1, False]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable": "input_1", "type": costants.ZONE_TYPE_FLOW_RATE}, {"variable": "output_1", "type": costants.ZONE_TYPE_FLOW_RATE}] return_element.update({"mass_continuity_1": {"variables": variables_list, "related_option": "none"}}) variables_list = [{"variable": "input_2", "type": costants.ZONE_TYPE_FLOW_RATE}, {"variable": "output_2", "type": costants.ZONE_TYPE_FLOW_RATE}] return_element.update({"mass_continuity_2": {"variables": variables_list, "related_option": "none"}}) variables_list = [{"variable": "input_1", "type": costants.ZONE_TYPE_PRESSURE}, {"variable": "output_1", "type": costants.ZONE_TYPE_PRESSURE}] return_element.update({"pressure_continuity_1": {"variables": variables_list, "related_option": "none"}}) variables_list = [{"variable": "input_2", "type": costants.ZONE_TYPE_PRESSURE}, {"variable": "output_2", "type": costants.ZONE_TYPE_PRESSURE}] return_element.update({"pressure_continuity_2": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): connected_drawer = None for drawer in self.support_block: if drawer.connection_is_in_connections_list(input_connection): connected_drawer = drawer break if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In the evaporator flow rate is preserved for each drawer, hence the program identify the drawer to which # "input_connection" stream is connected and returns each fluid stream connected to that block if connected_drawer is not None: return connected_drawer.get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In the evaporator fluid type is preserved for each drawer, hence the program identify the drawer to which # "input_connection" stream is connected and returns each fluid stream connected to that block if connected_drawer is not None: return connected_drawer.get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In the evaporator pressure is preserved for each drawer, hence the program identify the drawer to which # "input_connection" stream is connected and returns each fluid stream connected to that block if connected_drawer is not None: return connected_drawer.get_fluid_stream_connections() else: return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/evaporator.py
evaporator.py
from EEETools.MainModules import Block from EEETools.MainModules.support_blocks import Drawer import xml.etree.ElementTree as ETree from EEETools import costants class HeatExchanger(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) self.type = "heat exchanger" self.has_support_block = True self.support_block.append(Drawer(main_class, self, is_input=True, allow_multiple_input=False)) self.support_block.append(Drawer(main_class, self, is_input=False, allow_multiple_input=False)) def add_new_drawer(self, is_input): self.support_block.append(Drawer(self.main_class, self, is_input=is_input)) def is_ready_for_calculation(self): for supp_block in self.support_block: if not supp_block.is_ready_for_calculation: return False return True def initialize_connection_list(self, input_list): if str(input_list[0]) in ["Heat Exchanger", "Scambiatore"]: new_conn_input_product = self.main_class.find_connection_by_index(abs(input_list[1])) new_conn_output_product = self.main_class.find_connection_by_index(abs(input_list[2])) new_conn_input_fuel = self.main_class.find_connection_by_index(abs(input_list[3])) new_conn_output_fuel = self.main_class.find_connection_by_index(abs(input_list[4])) self.add_connection(new_conn_input_product, is_input=True, append_to_support_block=1) self.add_connection(new_conn_output_product, is_input=False, append_to_support_block=1) self.add_connection(new_conn_input_fuel, is_input=True, append_to_support_block=0) self.add_connection(new_conn_output_fuel, is_input=False, append_to_support_block=0) elif str(input_list[0]) in ["Heat Exchanger - Multi Fuel", "Scambiatore - Multi Fuel"]: new_conn_input_product = self.main_class.find_connection_by_index(abs(input_list[1])) new_conn_output_product = self.main_class.find_connection_by_index(abs(input_list[2])) self.add_connection(new_conn_input_product, is_input=True, append_to_support_block=1) self.add_connection(new_conn_output_product, is_input=False, append_to_support_block=1) for elem in input_list[3:]: new_conn = self.main_class.find_connection_by_index(abs(elem)) if not new_conn is None: is_input = (elem > 0) self.add_connection(new_conn, is_input=is_input, append_to_support_block=0) else: new_conn_input_fuel = self.main_class.find_connection_by_index(abs(input_list[1])) new_conn_output_fuel = self.main_class.find_connection_by_index(abs(input_list[2])) self.add_connection(new_conn_input_fuel, is_input=True, append_to_support_block=0) self.add_connection(new_conn_output_fuel, is_input=False, append_to_support_block=0) for elem in input_list[3:]: new_conn = self.main_class.find_connection_by_index(abs(elem)) if not new_conn is None: is_input = (elem > 0) self.add_connection(new_conn, is_input=is_input, append_to_support_block=1) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fuels_connections = ETree.SubElement(xml_connection_list, "FuelsConnections") product_connections = ETree.SubElement(xml_connection_list, "ProductConnections") for support_block in self.support_block: if support_block.is_input: main_tree = ETree.SubElement(fuels_connections, "Block") else: main_tree = ETree.SubElement(product_connections, "Block") for input_connection in support_block.external_input_connections: input_xml = ETree.SubElement(main_tree, "input") input_xml.set("index", str(input_connection.index)) for output_connection in support_block.external_output_connections: output_xml = ETree.SubElement(main_tree, "output") output_xml.set("index", str(output_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fuels_connections = input_list.find("FuelsConnections") product_connections = input_list.find("ProductConnections") self.__add_support_blocks(len(fuels_connections.findall("Block")), True) self.__add_support_blocks(len(product_connections.findall("Block")), False) i = 0 support_block_array = self.input_support_block for connection in fuels_connections.findall("Block"): self.__add_connection_by_index(connection, "input", append_to_support_block=support_block_array[i]) self.__add_connection_by_index(connection, "output", append_to_support_block=support_block_array[i]) i = i + 1 i = 0 support_block_array = self.output_support_block for connection in product_connections.findall("Block"): self.__add_connection_by_index(connection, "input", append_to_support_block=support_block_array[i]) self.__add_connection_by_index(connection, "output", append_to_support_block=support_block_array[i]) i = i + 1 def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) def __add_support_blocks(self, n_support_blocks, is_input): for i in range(1, n_support_blocks): self.add_new_drawer(is_input) @property def input_support_block(self) -> list: return_list = list() for support_block in self.support_block: if support_block.is_input: return_list.append(support_block) return return_list @property def output_support_block(self) -> list: return_list = list() for support_block in self.support_block: if not support_block.is_input: return_list.append(support_block) return return_list @classmethod def return_EES_needed_index(cls): return_dict = {"input_1": [1, False], "output_1": [1, False], "input_2": [1, False], "output_2": [1, False]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable": "input_1", "type": costants.ZONE_TYPE_FLOW_RATE}, {"variable": "output_1", "type": costants.ZONE_TYPE_FLOW_RATE}] return_element.update({"mass_continuity_1": {"variables": variables_list, "related_option": "none"}}) variables_list = [{"variable": "input_2", "type": costants.ZONE_TYPE_FLOW_RATE}, {"variable": "output_2", "type": costants.ZONE_TYPE_FLOW_RATE}] return_element.update({"mass_continuity_2": {"variables": variables_list, "related_option": "none"}}) variables_list = [{"variable": "input_1", "type": costants.ZONE_TYPE_PRESSURE}, {"variable": "output_1", "type": costants.ZONE_TYPE_PRESSURE}] return_element.update({"pressure_continuity_1": {"variables": variables_list, "related_option": "none"}}) variables_list = [{"variable": "input_2", "type": costants.ZONE_TYPE_PRESSURE}, {"variable": "output_2", "type": costants.ZONE_TYPE_PRESSURE}] return_element.update({"pressure_continuity_2": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): connected_drawer = None for drawer in self.support_block: if drawer.connection_is_in_connections_list(input_connection): connected_drawer = drawer break if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In an heat exchanger the flow rate is preserved for each drawer, hence the program identify the drawer # to which "input_connection" stream is connected and returns each fluid stream connected to that block if connected_drawer is not None: return connected_drawer.get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In an heat exchanger fluid type is preserved for each drawer, hence the program identify the drawer to # which "input_connection" stream is connected and returns each fluid stream connected to that block if connected_drawer is not None: return connected_drawer.get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In an heat exchanger pressure is preserved for each drawer, hence the program identify the drawer to which # "input_connection" stream is connected and returns each fluid stream connected to that block if connected_drawer is not None: return connected_drawer.get_fluid_stream_connections() else: return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/heat_exchanger.py
heat_exchanger.py
from EEETools.MainModules import Block from EEETools.MainModules.support_blocks import Drawer import xml.etree.ElementTree as ETree from EEETools import costants class Expander(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) self.type = "expander" self.has_support_block = True self.support_block.append(Drawer(main_class, self, allow_multiple_input=False)) def add_connection_to_support_block(self, new_connection, is_input): self.support_block[0].add_connection(new_connection, is_input) def is_ready_for_calculation(self): return len(self.output_connections) >= 1 and len(self.support_block[0].output_connections) >= 1 and len( self.support_block[0].input_connections) >= 1 def initialize_connection_list(self, input_list): new_conn_power = self.main_class.find_connection_by_index(abs(input_list[0])) new_conn_input_flow = self.main_class.find_connection_by_index(abs(input_list[1])) new_conn_output_flow = self.main_class.find_connection_by_index(abs(input_list[2])) new_conn_power.is_fluid_stream = False self.add_connection(new_conn_power, is_input=False) self.add_connection(new_conn_input_flow, is_input=True, append_to_support_block=0) self.add_connection(new_conn_output_flow, is_input=False, append_to_support_block=0) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fluid_connections = ETree.SubElement(xml_connection_list, "FluidConnections") for input_connection in self.support_block[0].external_input_connections: input_xml = ETree.SubElement(fluid_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in self.support_block[0].external_output_connections: output_xml = ETree.SubElement(fluid_connections, "output") output_xml.set("index", str(output_connection.index)) mechanical_connections = ETree.SubElement(xml_connection_list, "MechanicalConnections") for output_connection in self.external_output_connections: output_xml = ETree.SubElement(mechanical_connections, "output") output_xml.set("index", str(output_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fluid_connections = input_list.find("FluidConnections") mechanical_connections = input_list.find("MechanicalConnections") self.__add_connection_by_index(fluid_connections, "input", append_to_support_block=0) self.__add_connection_by_index(fluid_connections, "output", append_to_support_block=0) self.__add_connection_by_index(mechanical_connections, "output") def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) @classmethod def return_EES_needed_index(cls): return_dict = {"power input": [0, False], "flow input": [1, False], "flow output": [2, False]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable": "flow input", "type": costants.ZONE_TYPE_FLOW_RATE}, {"variable": "flow output", "type": costants.ZONE_TYPE_FLOW_RATE}] return_element.update({"mass_continuity": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In the expander flow rate is preserved, hence if "input_connection" stream is connected to the support # block (where the fluid streams are connected) the methods returns each fluid stream connected to the # support block if self.support_block[0].connection_is_in_connections_list(input_connection): return self.support_block[0].get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In the expander fluid type is preserved, hence if "input_connection" stream is connected to the support # block (where the fluid streams are connected) the methods returns each fluid stream connected to the # support block if self.support_block[0].connection_is_in_connections_list(input_connection): return self.support_block[0].get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In the expander pressure is not preserved, hence an empty list is returned return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/expander.py
expander.py
from EEETools.MainModules import Block import xml.etree.ElementTree as ETree from EEETools import costants class Generic(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) def is_ready_for_calculation(self): return len(self.input_connections) >= 1 and len(self.output_connections) >= 1 def initialize_connection_list(self, input_list): for elem in input_list: new_conn = self.main_class.find_connection_by_index(abs(elem)) if not new_conn is None: is_input = (elem > 0) self.add_connection(new_conn, is_input) def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fluid_connections = ETree.SubElement(xml_connection_list, "FluidConnections") for input_connection in self.external_input_connections: input_xml = ETree.SubElement(fluid_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in self.external_output_connections: output_xml = ETree.SubElement(fluid_connections, "output") output_xml.set("index", str(output_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fluid_connections = input_list.find("FluidConnections") self.__add_connection_by_index(fluid_connections, "input") self.__add_connection_by_index(fluid_connections, "output") def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) @classmethod def return_EES_needed_index(cls): return_dict = {"flow input": [1, True], "flow output": [2, True]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable": "flow input", "type": costants.ZONE_TYPE_PRESSURE}, {"variable": "flow output", "type": costants.ZONE_TYPE_PRESSURE}] return_element.update({"pressure_continuity": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In a generic block flow rate is not preserved, hence an empty list is returned return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In a generic block fluid type is preserved, hence if "input_connection" stream is connected to the # block the methods returns each fluid stream connected to it if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In a generic block pressure is preserved, hence if "input_connection" stream is connected to the # block the methods returns each fluid stream connected to it if self.connection_is_in_connections_list(input_connection): return self.get_fluid_stream_connections() else: return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/generic.py
generic.py
from .alternator import Alternator from .boiler import Boiler from .combustion_chamber import CombustionChamber from .compressor import Compressor from .condenser import Condenser from .evaporator import Evaporator from .expander import Expander from .generic import Generic from .heat_exchanger import HeatExchanger from .mixer import Mixer from .pump import Pump from .separator import Separator from .valve import Valve
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/__init__.py
__init__.py
from EEETools.MainModules.support_blocks import Drawer, get_drawer_sub_class from EEETools.MainModules import Block import xml.etree.ElementTree as ETree from EEETools import costants class EjectorSimplified(Block): def __init__(self, inputID, main_class): super().__init__(inputID, main_class) self.type = "Ejector Simplified" self.has_support_block = True self.mass_ratio = 0. SupportMixer = get_drawer_sub_class("mixer", main_class) self.support_block.append(Drawer(main_class, self)) self.support_block.append(Drawer(main_class, self, is_input=False)) self.support_block.append(SupportMixer(main_class, self)) def add_connection_to_support_block(self, support_block, new_connection, is_input): if support_block == "expander": self.support_block[0].add_connection(new_connection, is_input) elif support_block == "compressor": self.support_block[0].add_connection(new_connection, is_input) elif support_block == "mixer": self.support_block[0].add_connection(new_connection, is_input) def is_ready_for_calculation(self): return len(self.output_connections) >= 1 and len(self.support_block[0].output_connections) >= 1 and len( self.support_block[0].input_connections) >= 1 def initialize_connection_list(self, input_list): self.mass_ratio = float(input_list[0]) conn_output = self.main_class.find_connection_by_index(abs(input_list[1])) conn_input_driving = self.main_class.find_connection_by_index(abs(input_list[2])) conn_input_driven = self.main_class.find_connection_by_index(abs(input_list[3])) self.add_connection(conn_output, is_input=False, append_to_support_block=2) self.support_block[0].add_connection(conn_input_driving, is_input=True, append_to_support_block=0) self.support_block[1].add_connection(conn_input_driven, is_input=False, append_to_support_block=0) new_conn = self.main_class.append_connection(from_block=self) def prepare_for_calculation(self): self.support_block[0].prepare_for_calculation() new_conn = self.main_class.append_connection(from_block=self) new_conn.name = "Electrical Power Output" new_conn.is_useful_effect = True new_conn.automatically_generated_connection = True new_conn.exergy_value = self.exergy_balance def export_xml_connection_list(self) -> ETree.Element: xml_connection_list = ETree.Element("Connections") fluid_connections = ETree.SubElement(xml_connection_list, "FluidConnections") for input_connection in self.support_block[0].external_input_connections: input_xml = ETree.SubElement(fluid_connections, "input") input_xml.set("index", str(input_connection.index)) for output_connection in self.support_block[0].external_output_connections: output_xml = ETree.SubElement(fluid_connections, "output") output_xml.set("index", str(output_connection.index)) mechanical_connections = ETree.SubElement(xml_connection_list, "MechanicalConnections") for output_connection in self.external_output_connections: output_xml = ETree.SubElement(mechanical_connections, "output") output_xml.set("index", str(output_connection.index)) return xml_connection_list def append_xml_connection_list(self, input_list: ETree.Element): fluid_connections = input_list.find("FluidConnections") mechanical_connections = input_list.find("MechanicalConnections") self.__add_connection_by_index(fluid_connections, "input", append_to_support_block=0) self.__add_connection_by_index(fluid_connections, "output", append_to_support_block=0) self.__add_connection_by_index(mechanical_connections, "output") def __add_connection_by_index(self, input_list: ETree.Element, connection_name, append_to_support_block=None): if connection_name == "input": is_input = True else: is_input = False for connection in input_list.findall(connection_name): new_conn = self.main_class.find_connection_by_index(float(connection.get("index"))) if new_conn is not None: self.add_connection(new_conn, is_input, append_to_support_block=append_to_support_block) @classmethod def return_EES_needed_index(cls): return_dict = {"power input": [0, False], "flow input": [1, False], "flow output": [2, False]} return return_dict @classmethod def return_EES_base_equations(cls): return_element = dict() variables_list = [{"variable": "flow input", "type": costants.ZONE_TYPE_FLOW_RATE}, {"variable": "flow output", "type": costants.ZONE_TYPE_FLOW_RATE}] return_element.update({"mass_continuity": {"variables": variables_list, "related_option": "none"}}) return return_element def return_other_zone_connections(self, zone_type, input_connection): if zone_type == costants.ZONE_TYPE_FLOW_RATE: # In the expander flow rate is preserved, hence if "input_connection" stream is connected to the support # block (where the fluid streams are connected) the methods returns each fluid stream connected to the # support block if self.support_block[0].connection_is_in_connections_list(input_connection): return self.support_block[0].get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_FLUID: # In the expander fluid type is preserved, hence if "input_connection" stream is connected to the support # block (where the fluid streams are connected) the methods returns each fluid stream connected to the # support block if self.support_block[0].connection_is_in_connections_list(input_connection): return self.support_block[0].get_fluid_stream_connections() else: return list() elif zone_type == costants.ZONE_TYPE_PRESSURE: # In the expander pressure is not preserved, hence an empty list is returned return list() else: return list()
3ETool
/3ETool-0.8.3.tar.gz/3ETool-0.8.3/EEETools/BlockSubClasses/ejector_simplified.py
ejector_simplified.py
# Data Scientist Nanodegree (Term 2) Content for Udacity's Data Science Nanodegree curriculum, which includes project and lesson content. <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-nd/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/">Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License</a>. Please refer to [Udacity Terms of Service](https://www.udacity.com/legal) for further information.
3a-python-package-ligia
/3a_python_package_ligia-0.1.tar.gz/3a_python_package_ligia-0.1/README.md
README.md
from setuptools import setup setup(name='3a_python_package_ligia', version='0.1', description='Gaussian distributions', packages=['distributions'], zip_safe=False)
3a-python-package-ligia
/3a_python_package_ligia-0.1.tar.gz/3a_python_package_ligia-0.1/setup.py
setup.py
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution class Gaussian(Distribution): """ Gaussian distribution class for calculating and visualizing a Gaussian distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats extracted from the data file """ def __init__(self, mu=0, sigma=1): Distribution.__init__(self, mu, sigma) def calculate_mean(self): """Function to calculate the mean of the data set. Args: None Returns: float: mean of the data set """ avg = 1.0 * sum(self.data) / len(self.data) self.mean = avg return self.mean def calculate_stdev(self, sample=True): """Function to calculate the standard deviation of the data set. Args: sample (bool): whether the data represents a sample or population Returns: float: standard deviation of the data set """ if sample: n = len(self.data) - 1 else: n = len(self.data) mean = self.calculate_mean() sigma = 0 for d in self.data: sigma += (d - mean) ** 2 sigma = math.sqrt(sigma / n) self.stdev = sigma return self.stdev def plot_histogram(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ plt.hist(self.data) plt.title('Histogram of Data') plt.xlabel('data') plt.ylabel('count') def pdf(self, x): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2) def plot_histogram_pdf(self, n_spaces = 50): """Function to plot the normalized histogram of the data and a plot of the probability density function along the same range Args: n_spaces (int): number of data points Returns: list: x values for the pdf plot list: y values for the pdf plot """ mu = self.mean sigma = self.stdev min_range = min(self.data) max_range = max(self.data) # calculates the interval between x values interval = 1.0 * (max_range - min_range) / n_spaces x = [] y = [] # calculate the x values to visualize for i in range(n_spaces): tmp = min_range + interval*i x.append(tmp) y.append(self.pdf(tmp)) # make the plots fig, axes = plt.subplots(2,sharex=True) fig.subplots_adjust(hspace=.5) axes[0].hist(self.data, density=True) axes[0].set_title('Normed Histogram of Data') axes[0].set_ylabel('Density') axes[1].plot(x, y) axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation') axes[0].set_ylabel('Density') plt.show() return x, y def __add__(self, other): """Function to add together two Gaussian distributions Args: other (Gaussian): Gaussian instance Returns: Gaussian: Gaussian distribution """ result = Gaussian() result.mean = self.mean + other.mean result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2) return result def __repr__(self): """Function to output the characteristics of the Gaussian instance Args: None Returns: string: characteristics of the Gaussian """ return "mean {}, standard deviation {}".format(self.mean, self.stdev)
3a-python-package-ligia
/3a_python_package_ligia-0.1.tar.gz/3a_python_package_ligia-0.1/distributions/Gaussiandistribution.py
Gaussiandistribution.py
class Distribution: def __init__(self, mu=0, sigma=1): """ Generic distribution class for calculating and visualizing a probability distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats extracted from the data file """ self.mean = mu self.stdev = sigma self.data = [] def read_data_file(self, file_name): """Function to read in data from a txt file. The txt file should have one number (float) per line. The numbers are stored in the data attribute. Args: file_name (string): name of a file to read from Returns: None """ with open(file_name) as file: data_list = [] line = file.readline() while line: data_list.append(int(line)) line = file.readline() file.close() self.data = data_list
3a-python-package-ligia
/3a_python_package_ligia-0.1.tar.gz/3a_python_package_ligia-0.1/distributions/Generaldistribution.py
Generaldistribution.py
# Best Buy Bullet Bot (3B Bot) Best Buy Bullet Bot, abbreviated to 3B Bot, is a stock checking bot with auto-checkout created to instantly purchase out-of-stock items on Best Buy once restocked. It was designed for speed with ultra-fast auto-checkout, as well as the ability to utilize all cores of your CPU with multiprocessing for optimal performance. * Headless item stock tracking * Multiprocessing and multithreading for best possible performance * One-time login on startup * Ultra-fast auto-checkout * Encrypted local credentials storage * Super easy setup and usage Bear in mind that 3B Bot is currently not equipped to handle a queue and/or email verification during the checkout process. If either of these is present, the bot will wait for you to take over and will take control again once you are back on the traditional checkout track. ![3B Bot](https://raw.githubusercontent.com/LeonShams/BestBuyBulletBot/main/docs/source/assets/demo.svg) <br> ## Prerequisites 1. **A Best Buy account with your location and payment information already set in advance.** The only information the bot will fill out during checkout is your login credentials (email and password) and the CVV of the card used when setting up your payment information on Best Buy (PayPal is currently not supported). All other information that may be required during checkout must be filled out beforehand. 2. **Python 3.6 or newer** 3B Bot is written in Python so if it is not already installed on your computer please install it from <https://www.python.org/downloads/>. **On Windows make sure to tick the “Add Python to PATH” checkbox during the installation process.** On MacOS this is done automatically. Once installed, checking your Python version can be done with the following. For MacOS: ```bash python3 --version ``` For Windows: ```bash python --version ``` If your version is less than 3.6 or you get the message `python is not recognized as an internal or external command` then install python from the link above. 3. **A supported browser** 3B Bot currently only supports [Chrome](https://www.google.com/chrome/) and [Firefox](https://www.mozilla.org/en-US/firefox/new/). We recommend using the Firefox browser for it's superior performance during tracking. ## Installation Installing 3B Bot is as simple as running the following in your shell (Command Prompt for Windows and Terminal for MacOS) For MacOS: ```bash python3 -m pip install --upgrade 3b-bot ``` For Windows: ```bash pip install --upgrade 3b-bot ``` ## Usage To start the bot just enter the following in your shell ```bash 3b-bot ``` **For more usage information check out our [documentation](https://bestbuybulletbot.readthedocs.io/en/latest/).** ## How does it work? This is what 3B Bot does step by step at a high level 1. Get currently set URLs to track or prompt if none are set. 2. Using the requests library validate all URLs and get item names. 3. Open up a Google Chrome browser with selenium and perform the following. a. Navigate to the login page. b. If we have logged in previously we can use the saved cookies from the previous session to skip the log-in process. If not automatically fill out the username and password fields to log in. c. Make a get request to the Best Buy API to confirm that there are no items in the cart. d. If this is the first time using the bot check that a mailing address and payment information has been set. e. Go to each URL and collect the page cookies. This is done so that during checkout we can just apply the cookies for that URL instead of going through the entire login process. 4. Assign each URL to a core on the CPU. 5. Each core will start a specified number of threads. 6. Each thread will repeatedly check whether the "add to cart button" is available for its item. 7. When a thread notices that an item has come back in stock it will unlock its parent core and lock all other threads on every core to conserve CPU resources and WIFI. 8. The unlocked parent will print to the terminal that the item has come back in stock, play a sound, and attempt to automatically checkout the item with the following steps. a. With the driver that was used to track the item, click the add-to-cart button. b. Open up another browser window (this one is visible) and navigate to the item URL to set some cookies to login. c. Redirect to the checkout page. d. Enter the CVV for the card. e. Click "place order". 9. Once finished the parent will update its funds, the item quantity, and unlock all threads to resume stock tracking. 10. Sound will stop playing when the item is no longer in stock. ## Performance tips The following are tips to achieve the best possible performance with 3B Bot. * Use the same amount of URLs as cores on your CPU. You can create a URL group with the same URL repeated multiple times to increase the number of URLs you have and `3b-bot count-cores` can be used to see how many cores your CPU has. * Use ethernet as opposed to WIFI for a stronger more stable connection. * Adequately cool your computer to prevent thermal throttling. * Tweak the number of threads per URL. This can be changed with the `3b-bot set-threads` command. * If you plan to complete the checkout process yourself, disable auto-checkout in the settings for a significant performance improvement. Overall, item stock tracking is a CPU and internet bound task, so at the end of the day the better your CPU and the stronger your internet the faster your tracking.
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/README.md
README.md
from pathlib import Path from setuptools import find_packages, setup # Get __version__ from best_buy_bullet_bot/version.py exec( compile( open("best_buy_bullet_bot/version.py").read(), "best_buy_bullet_bot/version.py", "exec", ) ) setup( name="3b-bot", version=__version__, author="Leon Shams-Schaal", description="Quickly purchase items from Best Buy the moment they restock.", long_description=Path("readme.md").read_text(encoding="utf-8"), long_description_content_type="text/markdown", url="https://github.com/LeonShams/BestBuyBulletBot", project_urls={ "Documentation": "https://github.com/LeonShams/BestBuyBulletBot/wiki", "Bug Tracker": "https://github.com/LeonShams/BestBuyBulletBot/issues", }, packages=find_packages(), python_requires=">=3.6", install_requires=Path("requirements.txt").read_text().splitlines(), entry_points={"console_scripts": ["3b-bot=best_buy_bullet_bot.__main__:main"]}, include_package_data=True, zip_safe=False, license="MIT", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: End Users/Desktop", "Operating System :: OS Independent", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Environment :: Console", ], keywords="bestbuy bot bestbuybot bestbuybulletbot 3bbot 3b-bot bestbuystock \ bestbuyrestock bestbuytracker stocktracker bestbuystocktracker \ autocheckout bestbuyautocheckout nvidiabot gpubot nvidiagpubot \ 3060bot 3060tibot 3070bot 3070tibot 3080bot 3080tibot 3090bot \ ps5bot nvidiatracker gputracker nvidiagputracker 3060tracker \ 3060titracker 3070tracker 3070titracker 3080tracker 3080titracker \ 3090tracker ps5tracker", )
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/setup.py
setup.py
import argparse import warnings from best_buy_bullet_bot.utils import count_cores from best_buy_bullet_bot.version import __version__ class NoAction(argparse.Action): """Makes argument do nothing. This is useful if we want an argument to show up in the help menu, but remain uncallable. """ def __init__(self, **kwargs): kwargs.setdefault("default", argparse.SUPPRESS) kwargs.setdefault("nargs", 0) super().__init__(**kwargs) def __call__(self, *args): pass class FuncKwargs(dict): """Only passes flags to a specified function.""" def __init__(self, args): self.args = args super().__init__() def add_flag(self, flag_name, cmd_name): flag = getattr(self.args, flag_name) flag and self.args.cmd == cmd_name and self.update({flag_name: flag}) class ImportWrapper: """Only imports the function that the user selects.""" def __init__(self, file): self.file = file def __getattribute__(self, name): if name == "file": return super().__getattribute__("file") def call_func(*args, **kwargs): imported_file = __import__(self.file, fromlist=[""]) return getattr(imported_file, name)(*args, **kwargs) return call_func # This is done to prevent unnecessary imports and more importantly # prevent a bunch of warnings from setting_utils when imported tracker = ImportWrapper("best_buy_bullet_bot.tracker") setting_utils = ImportWrapper("best_buy_bullet_bot.data.setting_utils") url_utils = ImportWrapper("best_buy_bullet_bot.data.url_utils") user_data = ImportWrapper("best_buy_bullet_bot.data.user_data") browser_login = ImportWrapper("best_buy_bullet_bot.data.browser_login") OPS = { "start": [tracker.start, "Start tracking the currently set URLs."], "view-urls": [url_utils.view_urls, "View list of tracked URLs."], "add-url": [url_utils.add_url, "Add URL to tracking list."], "add-url-group": [ url_utils.add_url_group, "Add multiple URLs and set a quantity for all of them as a whole instead of individually.", ], "remove-url": [ url_utils.remove_url, "Remove a URL from the list of tracked URLs.", ], "test-urls": [ url_utils.test_urls, "Tests to make sure all URLs can be tracked. This is also run on startup.", ], "clear-urls": [url_utils.clear_urls, "Remove all tracked URLs."], "view-settings": [setting_utils.view_settings, "View current settings."], "set-funds": [ setting_utils.set_funds, "Set how much money the bot is allowed to spend.", ], "set-tax": [setting_utils.set_tax, "Set the sales tax rate for your state."], "toggle-auto-checkout": [ setting_utils.toggle_auto_checkout, "Enable/disable auto checkout.", ], "change-browser": [ setting_utils.change_browser, "Pick the browser to be used during tracking and auto-checkout (only applies if auto-checkout is enabled). \ Firefox is the default and recommended browser.", ], "test-sound": [setting_utils.test_sound, "Play sound sample."], "set-sound-mode": [ setting_utils.set_sound_mode, "Choose whether you want sound to be completely disabled, play once on item restock, or play repeatedly on item restock.", ], "set-threads": [ setting_utils.set_threads, "Select the number of threads to allocate to tracking each URL.", ], "count-cores": [ count_cores, "Print how many CPU cores you have and how many threads each core has.", ], "reset-settings": [ setting_utils.reset_settings, "Reset setting to the defaults.", ], "view-creds": [ user_data.print_creds, "View your Best Buy login credentials (email, password, cvv).", ], "set-creds": [ user_data.set_creds, "Set your Best Buy login credentials (email, password, cvv).", ], "clear-creds": [ user_data.clear_creds, "Reset your Best Buy login credentials (email, password, cvv). Also offers the option to reset your access password.", ], } def run_command(): parser = argparse.ArgumentParser( prog="3b-bot", description="Setup and control your Best Buy bot.", epilog="Good luck :)", ) parser.add_argument( "-v", "--version", action="version", version="%(prog)s " + __version__, help="show 3B Bot version number", ) parser.add_argument( "cmd", default="start", const="start", nargs="?", choices=OPS.keys(), help="Performs a specified operation.", metavar="command", type=str.lower, ) group = parser.add_argument_group(title="Available commands") for name, [func, help_msg] in OPS.items(): group.add_argument(name, help=help_msg, action=NoAction) parser.add_argument( "-w", "--suppress-warnings", action="store_true", help="suppress warnings" ) """ EASTER EGG: Thank you for reading the source code! To run the bot with a higher priority level and achieve better performance complete the following. If using Firefox, complete the following before moving on to the next step: WINDOWS: Open a Command Prompt window with "Run as administrator" https://www.educative.io/edpresso/how-to-run-cmd-as-an-administrator MAC: Enter the command `su` in your terminal to gain root privileges. Beware your settings may be different in the root session, but you can always return to a normal session with the `exit` command. Then regardless of your browser: Run `3b-bot --fast` in your shell. """ parser.add_argument("--fast", action="store_true", help=argparse.SUPPRESS) parser.add_argument( "--headless", action="store_true", help="hide the browser during auto checkout" ) parser.add_argument( "--verify-account", action="store_true", help="confirm that the account is setup properly (automatically performed on first run)", ) parser.add_argument( "--skip-verification", action="store_true", help="skip checks on first run that make sure account is setup properly.", ) parser.add_argument( "--force-login", action="store_true", help="force browser to go through traditional login process as opposed to using cookies to skip steps", ) args = parser.parse_args() func_kwargs = FuncKwargs(args) func_kwargs.add_flag("fast", "start") func_kwargs.add_flag("headless", "start") func_kwargs.add_flag("verify_account", "start") func_kwargs.add_flag("skip_verification", "start") if args.suppress_warnings: warnings.filterwarnings("ignore") else: # Just ignore the depreciation warnings warnings.filterwarnings("ignore", category=DeprecationWarning) if args.force_login: browser_login.delete_cookies() # Run command OPS[args.cmd][0](**func_kwargs)
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/best_buy_bullet_bot/command_line.py
command_line.py
import sys from rich.traceback import install from best_buy_bullet_bot.command_line import run_command def main(): # Stylizes errors and shows more info install() try: run_command() except KeyboardInterrupt: # This way we don't get the keyboardinterrupt traceback error sys.exit(0) # Running things directly can be useful in development if __name__ == "__main__": main()
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/best_buy_bullet_bot/__main__.py
__main__.py
import logging import sys import clipboard import requests from selenium.common.exceptions import NoSuchWindowException, TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from best_buy_bullet_bot.data.browser_login import ( cookies_available, load_cookies, save_cookies, ) from best_buy_bullet_bot.data.setting_utils import ( DRIVER_NAMES, change_browser, get_settings, is_installed, update_setting, ) from best_buy_bullet_bot.utils import Colors, loading SETTINGS = get_settings() TAX = SETTINGS["tax"] BROWSER_NAME = SETTINGS["browser"] DRIVER_WRAPPER = DRIVER_NAMES[BROWSER_NAME] MAC = sys.platform == "darwin" USER_TAKEOVER = 20 * 60 # 20 min for user to takeover if the bot gets stuck logging.disable(logging.WARNING) try: DRIVER_PATH = DRIVER_WRAPPER.manager().install() except ValueError: if not is_installed(SETTINGS["browser"]): Colors.print( f"{SETTINGS['browser'].title()} is not installed on your computer.", properties=["fail"], ) change_browser() def _get_options(headless): options = DRIVER_WRAPPER.options() options.page_load_strategy = "none" options.add_argument("--proxy-server='direct://'") options.add_argument("--proxy-bypass-list=*") if headless: options.add_argument("--headless") # Suppress "DevTools listening on ws:..." message if BROWSER_NAME == "chrome": options.add_experimental_option("excludeSwitches", ["enable-logging"]) return options PREBUILT_OPTIONS = [_get_options(False), _get_options(True)] def get_user_agent(): driver = DRIVER_WRAPPER.driver( executable_path=DRIVER_PATH, options=PREBUILT_OPTIONS[True] ) user_agent = driver.execute_script("return navigator.userAgent") driver.quit() return user_agent def money2float(money): return float(money[1:].replace(",", "")) def fast_text(text): clipboard.copy(text) return (Keys.COMMAND if MAC else Keys.CONTROL) + "v" account_page_url = "https://www.bestbuy.com/site/customer/myaccount" billing_url = "https://www.bestbuy.com/profile/c/billinginfo/cc" def terminate(driver): driver.quit() sys.exit(1) def _login(driver, wait, headless, email, password, cookies_set): branch = wait.until( EC.presence_of_element_located( (By.CSS_SELECTOR, "#ca-remember-me, .shop-search-bar") ) ) if branch.get_attribute("class") == "shop-search-bar": # We are already logged in return # Click "Keep me signed in" button branch.click() if not cookies_set: # Fill in email box driver.find_element_by_id("fld-e").send_keys(fast_text(email)) # Fill in password box driver.find_element_by_id("fld-p1").send_keys(fast_text(password)) # Click the submit button driver.find_element_by_css_selector( ".btn.btn-secondary.btn-lg.btn-block.c-button-icon.c-button-icon-leading.cia-form__controls__submit" ).click() # Check for error or redirect branch = wait.until( EC.presence_of_element_located( ( By.CSS_SELECTOR, ".shop-search-bar, " # We got redirected to the account page ".cia-cancel, " # Skippable verification page ".c-alert.c-alert-level-error, " # Error popup message "#fld-e-text, " # Invalid email address "#fld-p1-text", # Invalid password ) ) ) # If we hit an error if branch.get_attribute( "class" ) == "c-alert c-alert-level-error" or branch.get_attribute("id") in [ "fld-e-text", "fld-p1-text", ]: if headless: # If headless raise error Colors.print( "Incorrect login info. Please correct the username or password.", properties=["fail", "bold"], ) terminate(driver) else: # If headful ask the user to take over Colors.print( "Unable to login automatically. Please correct your credentials or enter the information manually.", properties=["fail"], ) branch = wait.until( EC.presence_of_element_located( (By.CSS_SELECTOR, ".shop-search-bar, .cia-cancel") ) ) # If we hit a skippable verification page if "cia-cancel" in branch.get_attribute("class"): # Redirect to the "my account" page driver.get(account_page_url) wait.until(EC.presence_of_element_located((By.CLASS_NAME, "shop-search-bar"))) save_cookies(driver) def check_cart(driver): with loading("Confirming cart is empty"): # Confirm that the cart is empty headers = { "Host": "www.bestbuy.com", "User-Agent": driver.execute_script("return navigator.userAgent"), "Accept": "*/*", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate, br", "Referer": "https://www.bestbuy.com/site/customer/myaccount", "X-CLIENT-ID": "browse", "X-REQUEST-ID": "global-header-cart-count", "Connection": "keep-alive", "Cookie": driver.execute_script("return document.cookie"), "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin", "Cache-Control": "max-age=0", } # Make a get request to the Best Buy API to get the number of items in the cart response = requests.get( "https://www.bestbuy.com/basket/v1/basketCount", headers=headers ) items = response.json()["count"] if items != 0: Colors.print( "Too many items in the cart. Please empty your cart before starting the bot.", properties=["fail", "bold"], ) terminate(driver) def perform_account_verification(driver, wait): with loading("Verifying account setup"): # Check that a shipping address has been set shipping_address = wait.until( EC.presence_of_element_located( ( By.CSS_SELECTOR, "div.account-setting-block-container:nth-child(1) > div:nth-child(2) > a:last-child", ) ) ) if shipping_address.get_attribute("class") == "": Colors.print( "Shipping address has not been set. You can add a shipping address to \ your account at https://www.bestbuy.com/profile/c/address/shipping/add.", properties=["fail", "bold"], ) terminate(driver) # Confirm that a default payment method has been created driver.get(billing_url) payment_method_list = wait.until( EC.presence_of_element_located( ( By.CSS_SELECTOR, ".pf-credit-card-list__content-spacer > ul.pf-credit-card-list__credit-card-list", ) ) ) if payment_method_list.size["height"] == 0: Colors.print( f"A default payment method has not been created. Please create one at {billing_url}.", properties=["fail", "bold"], ) terminate(driver) Colors.print("Account has passed all checks!", properties=["success"]) def collect_item_cookies(driver, wait, urls): login_cookies_list = [] predicted_prices = [] price_element = None with loading("Collecting cookies for each URL"): for url in urls: driver.get(url) if price_element is not None: wait.until(EC.staleness_of(price_element)) price_element = wait.until( EC.presence_of_element_located( ( By.CSS_SELECTOR, ".pricing-price > div > div > div > .priceView-hero-price.priceView-customer-price, " ".pricing-price > div > div > div > div > section > div > div > .priceView-hero-price.priceView-customer-price", ) ) ) item_price = price_element.text.split("\n")[0] predicted_prices.append(money2float(item_price) * (1 + TAX)) login_cookies_list.append(driver.get_cookies()) return login_cookies_list, predicted_prices def _browser_startup( driver, headless, email, password, urls, verify_account, skip_verification ): wait = WebDriverWait(driver, USER_TAKEOVER) with loading("Logging in"): driver.get(account_page_url) # We will then get redirected to the sign in page # If we have logged in previously we can use the cookies from that session # to skip steps in the login process and prevent the system from detecting # a bunch of logins from the same account cookies_exist = cookies_available() if cookies_exist: if load_cookies(driver): driver.refresh() else: # An error occurred while adding the login cookies cookies_exist = False _login(driver, wait, headless, email, password, cookies_exist) check_cart(driver) if not skip_verification: if SETTINGS["account verification"] or verify_account: perform_account_verification(driver, wait) if not verify_account: print("This was a one time test and will not be performed again.\n") update_setting("account verification", False) item_cookies = collect_item_cookies(driver, wait, urls) driver.quit() return item_cookies def browser_startup(headless, *args, **kwargs): driver = DRIVER_WRAPPER.driver( executable_path=DRIVER_PATH, options=PREBUILT_OPTIONS[headless] ) try: return _browser_startup(driver, headless, *args, **kwargs) # Timed out while trying to locate element except TimeoutException: Colors.print( "Browser window has timed out. Closing bot.", properties=["fail", "bold"] ) terminate(driver) # User has closed the browser window except NoSuchWindowException: terminate(driver) def _purchase( driver, title, password, cvv, money_manager, ): # Go to the checkout page driver.get("https://www.bestbuy.com/checkout/r/fast-track") wait = WebDriverWait(driver, USER_TAKEOVER) # Get to the CVV page while True: branch = wait.until( EC.element_to_be_clickable( ( By.CSS_SELECTOR, "#credit-card-cvv, " # Place order page ".button--continue > button.btn.btn-lg.btn-block.btn-secondary, " # Continue to payment info page ".checkout-buttons__checkout > .btn.btn-lg.btn-block.btn-primary", # We got redirected to the cart ) ) ) # If we got redirected to the cart if branch.get_attribute("class") == "btn btn-lg btn-block btn-primary": # Click "proceed to checkout" button branch.click() branch = wait.until( EC.element_to_be_clickable( ( By.CSS_SELECTOR, "#credit-card-cvv, " # Place order page "#cvv, " # Review and place order page ".button--continue > button.btn.btn-lg.btn-block.btn-secondary, " # Continue to place order page (page before place order page) "#fld-p1", # Sign in (only requires password) ) ) ) # If it wants to confirm our password if branch.get_attribute("class").strip() == "tb-input": branch.send_keys(fast_text(password)) driver.find_element_by_css_selector( ".btn.btn-secondary.btn-lg.btn-block.c-button-icon.c-button-icon-leading.cia-form__controls__submit" ).click() # Click sign in button # We will loop back around and handle what comes next else: break else: break # Select the CVV text box if branch.get_attribute("class") == "btn btn-lg btn-block btn-secondary": branch.click() cvv_box = wait.until( EC.element_to_be_clickable( ( By.CSS_SELECTOR, "#credit-card-cvv, #cvv", ) ) ) else: cvv_box = branch cvv_box.send_keys(fast_text(cvv)) # Locate and parse the grand total text grand_total = money2float( driver.find_element_by_css_selector( ".order-summary__total > .order-summary__price > .cash-money" ).text ) # Make sure we have sufficient funds for the purchase if money_manager.check_funds(grand_total): # Click place order button driver.find_element_by_css_selector( ".btn.btn-lg.btn-block.btn-primary, .btn.btn-lg.btn-block.btn-primary.button__fast-track" ).click() # Deduct grand total from available funds money_manager.make_purchase(grand_total) Colors.print( f"Successfully purchased {title}. The item was a grand total of ${grand_total:,.2f} leaving you with ${money_manager.get_funds():,.2f} of available funds.", properties=["success", "bold"], ) return True else: Colors.print( f"Insuffient funds to purchase {title} which costs a grand total of ${grand_total:,.2f} while you only have ${money_manager.get_funds():,.2f} of available funds.", properties=["fail"], ) return False def purchase( url, login_cookies, headless, headless_driver, headless_wait, *args, **kwargs ): if not headless: # Create a new visible driver for the checkout process driver = DRIVER_WRAPPER.driver( executable_path=DRIVER_PATH, options=PREBUILT_OPTIONS[False] ) driver.get(url) for cookie in login_cookies: driver.add_cookie(cookie) else: # Use the old headless driver so we don't have to create a new one driver = headless_driver # Have the existing headless tracker driver click the add-to-cart button headless_wait.until( EC.element_to_be_clickable( ( By.CSS_SELECTOR, ".fulfillment-add-to-cart-button > div > div > button", ) ) ).click() try: return _purchase(driver, *args, **kwargs) except TimeoutException: Colors.print( "3B Bot got stuck and nobody took over. Tracking will resume.", properties=["fail"], ) except NoSuchWindowException: driver.quit() return False
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/best_buy_bullet_bot/browser.py
browser.py
import warnings import psutil from rich import get_console from rich.columns import Columns from rich.live import Live from rich.spinner import Spinner from rich.table import Table def _pretty_warning(msg, *args, **kwargs): return Colors.str(f"WARNING: {msg}\n", properties=["warning"]) warnings.formatwarning = _pretty_warning class Colors: SUCCESS = "\033[92m" WARNING = "\033[93m" FAIL = "\033[91m" BLUE = "\033[94m" BOLD = "\033[1m" _ENDC = "\033[0m" @staticmethod def _props2str(props): return "".join([getattr(Colors, prop.upper()) for prop in props]) @staticmethod def str(string, properties=[]): return Colors._props2str(properties) + string + Colors._ENDC @staticmethod def print(*args, properties=[], **kwargs): print(Colors._props2str(properties), end="") print_end = kwargs.pop("end", "\n") print(*args, **kwargs, end=Colors._ENDC + print_end) @staticmethod def warn(*args, **kwargs): warnings.warn(*args, **kwargs) def print_table(columns, rows, justifications=["left", "center"]): table = Table(show_lines=True) for i, column in enumerate(columns): table.add_column(column, justify=justifications[i]) for row in rows: row = list(map(str, row)) max_lines = max(string.count("\n") for string in row) vert_align_row = [ "\n" * int((max_lines - string.count("\n")) / 2) + string for string in row ] table.add_row(*vert_align_row) with get_console() as console: console.print(table) def count_cores(): cores = psutil.cpu_count(logical=False) print("Cores:", cores) threads = psutil.cpu_count(logical=True) / cores int_threads = int(threads) if int_threads == threads: print("Threads per core:", int_threads) def warnings_suppressed(): return any( [filter[0] == "ignore" and filter[2] is Warning for filter in warnings.filters] ) def loading(msg): loading_text = Columns([msg, Spinner("simpleDotsScrolling")]) return Live(loading_text, refresh_per_second=5, transient=True) def yes_or_no(prompt): while True: response = input(prompt).lower().strip() if response == "": continue responded_yes = response == "yes"[: len(response)] responded_no = response == "no"[: len(response)] if responded_yes != responded_no: # responeded_yes xor responded_no return responded_yes else: Colors.print( 'Invalid response. Please enter either "y" or "n"', properties=["fail"] ) def validate_num(val, dtype): try: cast_val = dtype(val) except ValueError: return if dtype is int and cast_val != float(val): return return cast_val
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/best_buy_bullet_bot/utils.py
utils.py
__version__ = "1.1.0"
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/best_buy_bullet_bot/version.py
version.py
import os from threading import Event, Thread from playsound import playsound path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "notification.wav") playing = Event() def _repeat(): while True: playing.wait() playsound(path) repeat_loop = Thread(target=_repeat, daemon=True) repeat_loop.start() def play(block=False): playsound(path, block) def start(): playing.set() def stop(): playing.clear()
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/best_buy_bullet_bot/audio/sound_effects.py
sound_effects.py
import sys import time from collections import deque from datetime import timedelta from rich import get_console from rich.progress import BarColumn, Progress, ProgressColumn, SpinnerColumn, TextColumn class TimeRemainingColumn(ProgressColumn): """Renders estimated time remaining.""" # Only refresh twice a second to prevent jitter max_refresh = 0.5 def __init__(self, *args, **kwargs): self.start_time = time.time() super().__init__(*args, **kwargs) def render(self, *args, **kwargs): delta = timedelta(seconds=int(time.time() - self.start_time)) return str(delta) class IterationsPerSecond: def format(self, task): if "times" in dir(task) and len(task.times): speed = len(task.times) / task.times[-1] return f"{speed:.2f}it/s" return "0.00it/s" class IndefeniteProgressBar: def __init__(self): with get_console() as console: self.pbar = Progress( SpinnerColumn(style=""), TextColumn("{task.completed}it"), BarColumn(console.width), TextColumn(IterationsPerSecond()), TimeRemainingColumn(), console=console, expand=True, ) self.pbar.start() self.pbar.add_task(None, start=False) self.pbar.tasks[0].times = deque(maxlen=100) self.start_time = time.time() def print(self, *args, sep=" ", end="\n"): msg = sep.join(map(str, args)) sys.stdout.writelines(msg + end) def update(self): task = self.pbar.tasks[0] task.completed += 1 task.times.append(time.time() - self.start_time) def close(self): self.pbar.stop()
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/best_buy_bullet_bot/tracker/progress_bar.py
progress_bar.py
import builtins import os import signal import sys import time from multiprocessing import Pool from multiprocessing.managers import BaseManager from multiprocessing.pool import ThreadPool from threading import Event, Lock import psutil from bs4 import BeautifulSoup from requests import Session from requests.adapters import HTTPAdapter from requests.exceptions import RequestException from requests.packages.urllib3.util.retry import Retry from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from best_buy_bullet_bot.audio import sound_effects from best_buy_bullet_bot.browser import purchase from best_buy_bullet_bot.data import user_data from best_buy_bullet_bot.data.setting_utils import ( DRIVER_NAMES, SOUND_MODES, MoneyManager, get_settings, ) from best_buy_bullet_bot.data.url_utils import QtyManager from best_buy_bullet_bot.tracker.progress_bar import IndefeniteProgressBar from best_buy_bullet_bot.utils import Colors WINDOWS = sys.platform == "win32" SETTINGS = get_settings() SOUND_MODE = SETTINGS["sound mode"] AUTO_CHECKOUT = SETTINGS["auto checkout"] BROWSER_NAME = SETTINGS["browser"] DRIVER_WRAPPER = DRIVER_NAMES[BROWSER_NAME] NUM_THREADS = SETTINGS["threads"] class TwoWayPause: def __init__(self): self.play = Event() self.play.set() self.pause = Event() def is_set(self): return self.pause.is_set() def set(self): self.play.clear() self.pause.set() def clear(self): self.pause.clear() self.play.set() def wait(self): self.pause.wait() def wait_inverse(self): self.play.wait() # The following two classes are needed to use magic methods with `BaseManager` class NoMagicLock: def __init__(self): self.lock = Lock() def enter(self, *args, **kwargs): self.lock.__enter__(*args, **kwargs) def exit(self, *args, **kwargs): self.lock.__exit__(*args, **kwargs) class NormalLock: def __init__(self, no_magic_lock): self.lock = no_magic_lock def __enter__(self, *args, **kwargs): self.lock.enter(*args, **kwargs) def __exit__(self, *args, **kwargs): self.lock.exit(*args, **kwargs) BaseManager.register("ThreadLock", NoMagicLock) BaseManager.register("QtyManager", QtyManager) BaseManager.register("IndefeniteProgressBar", IndefeniteProgressBar) BaseManager.register("PauseEvent", TwoWayPause) BaseManager.register("MoneyManager", MoneyManager) STOCK = False def track( title, url, qty, headless, login_cookies, password, cvv, thread_lock, paused, pbar, pred_price, money_manager, headers, ): builtins.print = pbar.print if not AUTO_CHECKOUT: headers["referer"] = url thread_lock = NormalLock(thread_lock) with ThreadPool(NUM_THREADS) as pool: pool.starmap_async( run, [ [ title, url, qty, login_cookies, thread_lock, paused, pbar, pred_price, money_manager, headers, ] for _ in range(NUM_THREADS) ], ) await_checkout( title, url, qty, headless, login_cookies, password, cvv, paused, pred_price, money_manager, ) def await_checkout( title, url, qty, headless, login_cookies, password, cvv, paused, pred_price, money_manager, ): global STOCK while True: paused.wait() if STOCK: if not money_manager.check_funds(pred_price) or not qty.get(): paused.clear() if SOUND_MODE == SOUND_MODES[2]: sound_effects.stop() Colors.print( f'All requested "{title}" were purchased.' if money_manager.check_funds(pred_price) else f"With only ${money_manager.get_funds():,.2f} you cannot afford {title}.", "It will no longer be tracked to conserve resources.\n", properties=["warning"], ) return current_time = time.strftime("%H:%M:%S", time.localtime()) Colors.print( f'\n{current_time} - "{title}" - {url}\n', properties=["bold"], ) # Plays a sound if SOUND_MODE == SOUND_MODES[1]: sound_effects.play() elif SOUND_MODE == SOUND_MODES[2]: sound_effects.start() if AUTO_CHECKOUT: try: while money_manager.check_funds(pred_price) and qty.get(): if purchase( url, login_cookies, headless, *STOCK, # `headless_driver` and `headless_wait` title, password, cvv, money_manager, ): qty.decrement() else: break except Exception as e: Colors.print( f"CHECKOUT ERROR: {e}", ) STOCK = False paused.clear() else: paused.wait_inverse() def run( title, url, qty, login_cookies, thread_lock, paused, pbar, pred_price, money_manager, headers, ): global STOCK stop_tracker = False if AUTO_CHECKOUT: options = DRIVER_WRAPPER.options() options.page_load_strategy = "none" options.add_argument("--proxy-server='direct://'") options.add_argument("--proxy-bypass-list=*") options.add_argument("--headless") # Suppress "DevTools listening on ws:..." message if BROWSER_NAME == "chrome": options.add_experimental_option("excludeSwitches", ["enable-logging"]) # Create the browser window driver = DRIVER_WRAPPER.driver( executable_path=DRIVER_WRAPPER.manager().install(), options=options ) # Login to the browser by setting the cookies driver.get(url) for cookie in login_cookies: driver.add_cookie(cookie) wait = WebDriverWait(driver, 120) button_locator = EC.presence_of_element_located( ( By.CSS_SELECTOR, ".fulfillment-add-to-cart-button > div > div > button", ) ) # Confirm that we have a stable connection and that Best Buy hasn't made any # changes to their website that would break out locator try: btn = wait.until(button_locator) except TimeoutException: Colors.print( f"Unable to connect to {title}. Closing tracker.", properties=["fail"], ) stop_tracker = True else: session = Session() session.headers.update(headers) retry = Retry( connect=3, backoff_factor=0.25, status_forcelist=[429, 500, 502, 503, 504], method_whitelist=["HEAD", "GET", "OPTIONS"], ) adapter = HTTPAdapter(max_retries=retry) session.mount("https://", adapter) session.mount("http://", adapter) connection_status = True available = False prev_available = False # Track item so long as we have sufficient funds and haven't bought the item too many times while not stop_tracker and ( not AUTO_CHECKOUT or (money_manager.check_funds(pred_price) and qty.get()) ): # Stop trackers to conserve resources during the auto checkout process if paused.is_set(): paused.wait_inverse() continue if AUTO_CHECKOUT: driver.get(url) try: # Wait until old page has unloaded wait.until(EC.staleness_of(btn)) if paused.is_set(): # Stop page load (page will reload when tracker restarts) driver.execute_script("window.stop();") continue # Wait until the add-to-cart button is present on the new page btn = wait.until(button_locator) # Inform the user if an error occurs while trying to locate the add-to-cart button except TimeoutException: if connection_status: start_time = time.time() Colors.print( f"{title} tracker has lost connection.\n", properties=["fail"], ) connection_status = False continue # Check if it is an add-to-cart button available = btn.get_attribute("data-button-state") == "ADD_TO_CART" else: try: # Make a get request response = session.get(url, timeout=10) response.raise_for_status() except RequestException as e: # Inform the user if an error occurs while trying to make a get request if connection_status: start_time = time.time() Colors.print( f"Unable to establish a connection to {title} remote endpoint.", properties=["fail"], ) print(e, "\n") connection_status = False continue if paused.is_set(): continue # Look for add-to-cart button soup = BeautifulSoup(response.text, "html.parser") available = ( soup.find( "button", {"data-button-state": "ADD_TO_CART"}, ) is not None ) pbar.update() # If we reconnected, inform the user if not connection_status: Colors.print( f"{title} tracker has successfully reconnected!", properties=["success"], ) print(f"Downtime: {time.time()-start_time:.2f} seconds \n") connection_status = True # If the item is in stock if available: # Unlock the checkout process if it hasn't been already with thread_lock: if paused.is_set(): continue if AUTO_CHECKOUT: if not STOCK: STOCK = (driver, wait) else: STOCK = True paused.set() # If item went back to being out of stock elif prev_available != available: if SOUND_MODE == SOUND_MODES[2]: sound_effects.stop() prev_available = available # Stop the auto checkout function if STOCK is not True: STOCK = True paused.set() if AUTO_CHECKOUT: driver.close() else: session.close() def set_priority(high_priority): p = psutil.Process(os.getpid()) """ EASTER EGG: Thank you for reading the source code! To run the bot with a higher priority level and achieve better performance complete the following. If using Firefox, complete the following before moving on to the next step: WINDOWS: Open a Command Prompt window with "Run as administrator" https://www.educative.io/edpresso/how-to-run-cmd-as-an-administrator MAC: Enter the command `su` in your terminal to gain root privileges. Beware your settings may be different in the root session, but you can always return to a normal session with the `exit` command. Then regardless of your browser: Run `3b-bot --fast` in your shell. """ # Windows: REALTIME_PRIORITY_CLASS, HIGH_PRIORITY_CLASS, ABOVE_NORMAL_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, BELOW_NORMAL_PRIORITY_CLASS, IDLE_PRIORITY_CLASS # MacOS: -20 is highest priority while 20 is lowest priority # Lower priorities are used here so other things can still be done on the computer while the bot is running priority = ( (psutil.HIGH_PRIORITY_CLASS if WINDOWS else -10) if high_priority else (psutil.BELOW_NORMAL_PRIORITY_CLASS if WINDOWS else 10) ) p.nice(priority) def start(fast=False, headless=False, verify_account=False, skip_verification=False): from elevate import elevate from best_buy_bullet_bot.browser import browser_startup, get_user_agent from best_buy_bullet_bot.data import close_data, url_utils from best_buy_bullet_bot.utils import loading, warnings_suppressed, yes_or_no """ EASTER EGG: Thank you for reading the source code! To run the bot with a higher priority level and achieve better performance complete the following. If using Firefox, complete the following before moving on to the next step: WINDOWS: Open a Command Prompt window with "Run as administrator" https://www.educative.io/edpresso/how-to-run-cmd-as-an-administrator MAC: Enter the command `su` in your terminal to gain root privileges. Beware your settings may be different in the root session, but you can always return to a normal session with the `exit` command. Then regardless of your browser: Run `3b-bot --fast` in your shell. """ # If we don't have admin privileges try to elevate permissions if fast and hasattr(os, "getuid") and os.getuid() != 0: print("Elevating permissions to run in fast mode.") elevate(graphical=False) def kill_all(*args, **kwargs): if not WINDOWS: # Delete the temp file close_data() # Forcefully close everything os.system( f"taskkill /F /im {psutil.Process(os.getpid()).name()}" ) if WINDOWS else os.killpg(os.getpgid(os.getpid()), signal.SIGKILL) def clean_kill(*args, **kwargs): # Suppress error messages created as a result of termination # Selenium will often print long error messages during termination sys.stderr = open(os.devnull, "w") # Close the pbar and kill everything if the process pool has been created if "pbar" in locals(): pbar.close() print() kill_all() # Inelegant but fast # Otherwise we can exit the traditional way else: print() sys.exit(0) # Use custom functions to exit properly for sig in [signal.SIGINT, signal.SIGBREAK if WINDOWS else signal.SIGQUIT]: signal.signal(sig, clean_kill) signal.signal(signal.SIGTERM, kill_all) print( """ .d8888b. 888888b. 888888b. 888 d88P Y88b 888 "88b 888 "88b 888 .d88P 888 .88P 888 .88P 888 8888" 8888888K. 8888888K. .d88b. 888888 "Y8b. 888 "Y88b 888 "Y88b d88""88b 888 888 888 888 888 888 888 888 888 888 Y88b d88P 888 d88P 888 d88P Y88..88P Y88b. "Y8888P" 8888888P" 8888888P" "Y88P" "Y888 """ ) # Check if a flag has been passed to suppress warnings suppress_warnings = warnings_suppressed() raw_urls = url_utils.get_url_data() if not len(raw_urls): print() Colors.warn("No URLs have been set to be tracked.") if not suppress_warnings: if yes_or_no("Would you like to set some URLs for tracking (y/n): "): while True: url_utils.add_url() if not yes_or_no("Do you want to add another url (y/n): "): break raw_urls = url_utils.get_url_data() if not len(raw_urls): Colors.print( "Not enough URLs for tracking.", "Please add at least 1 URL.", "URLs can be added with `3b-bot add-url`.", properties=["fail", "bold"], ) sys.exit(1) print("Tracking the following URLs.") url_utils.view_urls(AUTO_CHECKOUT) manager = BaseManager() manager.start() money_manager = manager.MoneyManager() if AUTO_CHECKOUT: print(f"Current funds: ${money_manager.get_funds():,.2f}") print() # Get URLs and a quantity object for each URL urls, qtys = [], [] for url_group, raw_qty in raw_urls: int_qty = -1 if raw_qty == "inf" else raw_qty # Create a shared qty manager between URLs for URL groups qty = manager.QtyManager(int_qty) if len(url_group) > 1 else QtyManager(int_qty) urls += url_group qtys += [qty] * len(url_group) with loading("Checking URLs"): titles = list(url_utils.get_url_titles()) if len(titles) < len(urls): sys.exit(1) elif len(titles) > len(urls): Colors.print( "Something went wrong!", "Please report the issue to https://github.com/LeonShams/BestBuyBulletBot/issues.", "Feel free to copy and paste the following when opening an issue.", properties=["fail", "bold"], ) print( "ERROR ENCOUNTERED DURING EXECUTION: More titles than URLs!", f"Raw URLs: {raw_urls}", f"URLs: {urls}", f"Titles: {titles}", sep="\n", ) sys.exit(1) if AUTO_CHECKOUT: email, password, cvv = user_data.get_creds() if not (email or password or cvv): Colors.warn( "\nCheckout credentials have not been set. Run `3b-bot set-creds` to add the necessary information." ) if not suppress_warnings: if yes_or_no("Would you like to set your checkout credentials (y/n): "): user_data.set_creds() email, password, cvv = user_data.get_creds() print() login_cookies_list, predicted_prices = browser_startup( headless, email, password, urls, verify_account, skip_verification ) headers = {} else: email, password, cvv = "", "", "" login_cookies_list, predicted_prices = ((None for _ in urls) for i in range(2)) headers = { "accept": "*/*", "accept-encoding": "gzip, deflate, br", "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7", "sec-ch-ua-mobile": "?0", "sec-fetch-dest": "script", "sec-fetch-mode": "no-cors", "sec-fetch-site": "same-origin", "user-agent": get_user_agent(), } Colors.print("Availability tracking has started!", properties=["success"]) if fast: Colors.print("Fast tracking enabled!", properties=["blue"]) print() # Create remaining shared objects thread_lock = manager.ThreadLock() paused = manager.PauseEvent() pbar = manager.IndefeniteProgressBar() # Start process for each URL with Pool(len(urls), set_priority, [fast]) as p: p.starmap( track, [ [ title, url, qty, headless, login_cookies, password, cvv, thread_lock, paused, pbar, pred_price, money_manager, headers, ] for title, url, qty, login_cookies, pred_price in zip( titles, urls, qtys, login_cookies_list, predicted_prices ) ], ) pbar.close() print("\nAll processes have finished.")
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/best_buy_bullet_bot/tracker/__init__.py
__init__.py
import json import os.path from bs4 import BeautifulSoup from requests import Session from requests.adapters import HTTPAdapter from requests.exceptions import RequestException from requests.packages.urllib3.util.retry import Retry from best_buy_bullet_bot.browser import get_user_agent from best_buy_bullet_bot.data import SHARED_DIR from best_buy_bullet_bot.utils import ( Colors, loading, print_table, validate_num, yes_or_no, ) URL_DIR = os.path.join(SHARED_DIR, "urls.json") def _read(): with open(URL_DIR) as f: return json.load(f) def _save(data): with open(URL_DIR, "w+") as f: json.dump(data, f) if not os.path.isfile(URL_DIR): _save({}) def get_url_data(): items = _read().items() return [[item.split("\n"), qty] for item, qty in items] def view_urls(show_qty=True): data = _read().items() columns = ["URL"] + (["Quantity"] if show_qty else []) rows = [[url, qty] for url, qty in data] if show_qty else zip(list(zip(*data))[0]) print_table(columns, rows) def get_qty(): while True: qty = input("Quantity (optional): ") if qty.strip() == "" or qty == "inf": return "inf" qty = validate_num(qty, int) if qty is None or qty < 1: Colors.print( "Invalid input for quantity. Please enter an integer greater than or equal to 1.", properties=["fail"], ) else: return qty class QtyManager: def __init__(self, qty): self.qty = qty def get(self): return self.qty def decrement(self): self.qty -= 1 def add_url(): new_url = input("URL to add: ") if new_url.strip() == "": print("Aborted.") return urls = _read() qty = get_qty() urls[new_url] = qty _save(urls) Colors.print( f"Successfully added {new_url}{'' if qty == 'inf' else f' with a quantity of {qty}'}!", properties=["success"], ) def add_url_group(): url_group = [] i = 1 while True: new_url = input("URL to add: ") if new_url.strip() == "": if i == 1: print("Aborted.") break else: continue url_group.append(new_url) if i >= 2 and not yes_or_no("Would you like to add another URL (y/n): "): break i += 1 urls = _read() qty = get_qty() urls["\n".join(url_group)] = qty _save(urls) Colors.print( f"Successfully added a URL group with {len(url_group)} URLs{'' if qty == 'inf' else f' and a quantity of {qty} for the group'}!", properties=["success"], ) def remove_url(): urls = _read() ids = range(1, len(urls) + 1) rows = list(zip(ids, urls.keys())) print_table(["ID", "Active URLs"], rows, justifications=["center", "left"]) while True: url_id = input("URL ID to remove: ").strip() if url_id == "": continue url_id = validate_num(url_id, int) if url_id is None or url_id < ids[0] or url_id > ids[-1]: Colors.print( f"Please enter valid URL ID between {ids[0]}-{ids[-1]}. Do not enter the URL itself.", properties=["fail"], ) else: break selected_url = list(urls.keys())[url_id - 1] del urls[selected_url] _save(urls) comma_separated_selection = selected_url.replace("\n", ", ") Colors.print( f"Successfully removed: {comma_separated_selection}", properties=["success"] ) def get_url_titles(): flattened_urls = [ url for url_group, _ in get_url_data() for url in (url_group if type(url_group) is list else [url_group]) ] session = Session() session.headers.update({"user-agent": get_user_agent()}) retry = Retry( connect=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504], method_whitelist=["HEAD", "GET", "OPTIONS"], ) adapter = HTTPAdapter(max_retries=retry) session.mount("https://", adapter) session.mount("http://", adapter) for url in flattened_urls: try: response = session.get(url, timeout=10) except RequestException as e: Colors.print(e, properties=["fail", "bold"]) continue soup = BeautifulSoup(response.text, "html.parser") raw_title = soup.find("div", class_="sku-title") if raw_title is None: Colors.print( f"Unable to find title for {url}.", properties=["fail", "bold"] ) continue title = raw_title.get_text().strip() in_stock = soup.find( "button", {"data-button-state": "ADD_TO_CART"}, ) if in_stock: Colors.warn(f"{title} is already in stock.") yield title session.close() def test_urls(): with loading("Testing URLs"): for title in get_url_titles(): Colors.print(f"Confirmed {title}!", properties=["success"]) def clear_urls(): _save({}) Colors.print("Successfully removed all URLs!", properties=["success"])
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/best_buy_bullet_bot/data/url_utils.py
url_utils.py
import json import logging import os.path import shutil import sys from time import sleep from selenium.common.exceptions import WebDriverException from selenium.webdriver import Chrome, Firefox from selenium.webdriver.chrome.options import Options as ChromeOptions from selenium.webdriver.firefox.options import Options as FirefoxOptions from webdriver_manager.chrome import ChromeDriverManager from webdriver_manager.firefox import GeckoDriverManager from best_buy_bullet_bot.audio import sound_effects from best_buy_bullet_bot.data import HEADLESS_WARNED, SHARED_DIR from best_buy_bullet_bot.utils import ( Colors, loading, print_table, validate_num, warnings_suppressed, yes_or_no, ) SETTINGS_DIR = os.path.join(SHARED_DIR, "settings.json") SOUND_MODES = ["disabled", "single", "repeat"] DEFAULT_SETTINGS = { "funds": 1000, "tax": 0.095, "auto checkout": True, "account verification": True, "browser": "firefox", "sound mode": SOUND_MODES[2], "threads": 1, } def _save(data): with open(SETTINGS_DIR, "w+") as f: json.dump(data, f) # Get the current settings CURRENT_SETTINGS = DEFAULT_SETTINGS.copy() if os.path.isfile(SETTINGS_DIR): save = False with open(SETTINGS_DIR) as f: for key, value in json.load(f).items(): if key in CURRENT_SETTINGS: CURRENT_SETTINGS[key] = value elif not HEADLESS_WARNED(): Colors.warn( f"{key} is no longer supported and will be removed from your settings." ) save = True if save and not HEADLESS_WARNED(): if not warnings_suppressed() and yes_or_no( "Delete unsupported settings from your settings file (y/n): " ): _save(CURRENT_SETTINGS) HEADLESS_WARNED.update(True) else: _save(DEFAULT_SETTINGS) def get_settings(): # A copy is returned so the settings can be safely manipulated return CURRENT_SETTINGS.copy() def update_setting(setting, new_val): CURRENT_SETTINGS[setting] = new_val _save(CURRENT_SETTINGS) def view_settings(show_default=False): settings = (DEFAULT_SETTINGS if show_default else CURRENT_SETTINGS).copy() settings["funds"] = f"${settings['funds']:,.2f}" settings["tax"] = f"{settings['tax'] * 100:.2f}%" settings["browser"] = settings["browser"].title() # Hidden property del settings["account verification"] rows = [[k.title(), v] for k, v in settings.items()] print_table(["Property", "Value"], rows) def set_funds(): while True: funds = input("Allotted money: $") funds = validate_num(funds.replace("$", ""), float) if funds is None or funds < 0: Colors.print( "Invalid input for funds. Please enter a positive number.", properties=["fail"], ) else: break update_setting("funds", funds) Colors.print(f"Successfully set funds to ${funds:,.2f}!", properties=["success"]) def set_tax(): while True: tax = input("Sales tax rate (%): ") tax = validate_num(tax.replace("%", ""), float) if tax is None or tax < 0: Colors.print( "Invalid input. Please enter a positive percentage for tax.", properties=["fail"], ) else: break update_setting("tax", tax / 100) Colors.print( f"Successfully set the state sales tax rate to {tax:,.2f}%", properties=["success"], ) class MoneyManager: def get_funds(self): return CURRENT_SETTINGS["funds"] def check_funds(self, cost): return CURRENT_SETTINGS["funds"] - cost >= 0 def make_purchase(self, cost): update_setting("funds", CURRENT_SETTINGS["funds"] - cost) def _toggle_setting(setting_name): update_setting(setting_name, not CURRENT_SETTINGS[setting_name]) Colors.print( f"Successfully {'enabled' if CURRENT_SETTINGS[setting_name] else 'disabled'} {setting_name}!", properties=["success"], ) def toggle_auto_checkout(): _toggle_setting("auto checkout") class DriverClassWrapper: def __init__(self, driver, manager, options): self.driver = driver self.manager = manager self.options = options logging.disable(logging.WARNING) DRIVER_NAMES = { "chrome": DriverClassWrapper(Chrome, ChromeDriverManager, ChromeOptions), "firefox": DriverClassWrapper(Firefox, GeckoDriverManager, FirefoxOptions), } def is_installed(browser_name): """Check if browser is installed Done by installing the drivers and trying to open the browser with selenium. If we can successfully open the browser then it is installed. """ browser_name = browser_name.lower() if browser_name in DRIVER_NAMES: wrap = DRIVER_NAMES[browser_name] else: raise ValueError( f"3B Bot does not support {browser_name.title()}. Please pick either Chrome or Firefox." ) # Install the drivers try: manager = wrap.manager() path = manager.install() except ValueError: return False options = wrap.options() options.add_argument("--headless") if CURRENT_SETTINGS["browser"] == "chrome": options.add_experimental_option("excludeSwitches", ["enable-logging"]) try: # Try to open a browser window driver = wrap.driver(executable_path=path, options=options) driver.quit() return True except (WebDriverException, ValueError): # Delete the drivers we just installed name = manager.driver.get_name() driver_dir = path.split(name)[0] + name if os.path.isdir(driver_dir): shutil.rmtree(driver_dir) return False def change_browser(): with loading("Detecting browsers"): available_browsers = [ browser.title() for browser in DRIVER_NAMES.keys() if is_installed(browser) ] if not len(available_browsers): Colors.print( "No available browsers. Please install either Chrome or Firefox and try again.", "Chrome can be installed from https://www.google.com/chrome/.", "Firefox can ben installed from https://www.mozilla.org/en-US/firefox/new/.", sep="\n", properties=["fail", "bold"], ) sys.exit() # Print available browsers print("\n • ".join(["Available Browsers:"] + available_browsers), "\n") while True: new_browser = input("Select a browser from the list above: ").strip().title() if new_browser == "": continue if new_browser not in available_browsers: Colors.print("Invalid selection. Try again.", properties=["fail"]) else: break update_setting("browser", new_browser.lower()) Colors.print( f"Successfully changed browser to {new_browser}!", properties=["success"] ) def test_sound(repetitions=3, print_info=True): if print_info: print("Playing sound...") sleep(0.15) for i in range(repetitions): sound_effects.play(block=True) def set_sound_mode(): while True: sound_mode = input( f"Select a sound mode ({SOUND_MODES[0]}/{SOUND_MODES[1]}/{SOUND_MODES[2]}): " ) if sound_mode not in SOUND_MODES: Colors.print( f'Invalid input for sound mode. Please enter either "{SOUND_MODES[0]}" (no sound),' f' "{SOUND_MODES[1]}" (plays sound once after coming back in stock), or "{SOUND_MODES[2]}"' " (plays sound repeatedly until item is no longer in stock).", properties=["fail"], ) else: break update_setting("sound mode", sound_mode) Colors.print( f"Successfully set sound mode to {sound_mode}!", properties=["success"] ) sleep(1) print("\nThat sounds like...") sleep(0.75) # No sound if sound_mode == SOUND_MODES[0]: sleep(0.5) print("Nothing. Crazy, right?") # Play sound once elif sound_mode == SOUND_MODES[1]: test_sound(repetitions=1, print_info=False) # Play sound on repeat elif sound_mode == SOUND_MODES[2]: test_sound(print_info=False) def set_threads(): while True: threads = input("Threads (per URL): ") threads = validate_num(threads, int) if threads is None or threads < 1: Colors.print( "Invalid number of threads. Please enter an integer greater than or equal to 1.", properties=["fail"], ) else: break update_setting("threads", threads) Colors.print( f"Now using {threads} threads to track each URL!", properties=["success"] ) def reset_settings(): print("Default settings:") view_settings(show_default=True) print() if yes_or_no("Reset (y/n): "): _save(DEFAULT_SETTINGS) Colors.print("Successfully reset settings!", properties=["success"]) else: print("Settings reset aborted.")
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/best_buy_bullet_bot/data/setting_utils.py
setting_utils.py
import json import os from json.decoder import JSONDecodeError from best_buy_bullet_bot.data import SHARED_DIR COOKIES_DIR = os.path.join(SHARED_DIR, "login_cookies.json") def save_cookies(driver): with open(COOKIES_DIR, "w+") as f: json.dump(driver.get_cookies(), f) def load_cookies(driver): try: with open(COOKIES_DIR) as f: for cookie in json.load(f): driver.add_cookie(cookie) return True # An error occurred while adding the cookies except AssertionError: # Delete previous cookies delete_cookies() return False def cookies_available(): file_exists = os.path.isfile(COOKIES_DIR) if file_exists: # Make sure file is JSON decodable try: with open(COOKIES_DIR) as f: json.load(f) return True except JSONDecodeError: _delete_cookies() return False def delete_cookies(): if cookies_available(): _delete_cookies() def _delete_cookies(): os.remove(COOKIES_DIR)
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/best_buy_bullet_bot/data/browser_login.py
browser_login.py
import os import sys from getpass import getpass from keyring.errors import PasswordDeleteError from keyring.util import properties from keyrings.cryptfile.cryptfile import CryptFileKeyring from keyrings.cryptfile.file_base import FileBacked from best_buy_bullet_bot.data import SHARED_DIR from best_buy_bullet_bot.utils import Colors, yes_or_no EMAIL_VAR = "BB_EMAIL" PASS_VAR = "BB_PASS" CVV_VAR = "BB_CVV" @properties.NonDataProperty def file_path(self): return os.path.join(SHARED_DIR, self.filename) FileBacked.file_path = file_path SERVICE_ID = "3B_BOT" KR = CryptFileKeyring() def set_access_pass(access_pass): KR._keyring_key = access_pass def authenticate(): attempts = 0 while True: try: KR.keyring_key return except ValueError: if str(KR._keyring_key).strip() == "": sys.exit() attempts += 1 if attempts >= 3: print("Too many attempts, please try again later.") sys.exit() print("Sorry, try again.") KR._keyring_key = None def _get_cred(name, default_value): cred = KR.get_password(SERVICE_ID, name) return cred if cred is not None else default_value def get_creds(default_value=""): authenticate() return [_get_cred(var, default_value) for var in [EMAIL_VAR, PASS_VAR, CVV_VAR]] def _get_input(prompt): while True: value = input(prompt) if yes_or_no("Continue (y/n): "): return value def set_creds(): authenticate() KR.set_password(SERVICE_ID, EMAIL_VAR, _get_input("Email: ")) print() while True: password = getpass("Best Buy password: ") confirm_pass = getpass("Confirm password: ") if password == confirm_pass: break print("Passwords didn't match! Try again.") KR.set_password(SERVICE_ID, PASS_VAR, password) print() KR.set_password(SERVICE_ID, CVV_VAR, _get_input("CVV: ")) Colors.print("Successfully updated credentials!", properties=["success"]) def print_creds(): email, password, cvv = get_creds(Colors.str("EMPTY", ["fail"])) print("Email:", email) print("Password:", password) print("CVV:", cvv) def clear_creds(): for name in [EMAIL_VAR, PASS_VAR, CVV_VAR]: try: KR.delete_password(SERVICE_ID, name) except PasswordDeleteError: pass Colors.print("Credentials cleared!\n", properties=["success", "bold"]) # Check if user wants to reset their password if yes_or_no("Would you like to reset your password (y/n): "): os.remove(KR.file_path) KR.keyring_key
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/best_buy_bullet_bot/data/user_data.py
user_data.py
import json import os import sys import tempfile from glob import glob from best_buy_bullet_bot.utils import Colors def _read_file(): FP.seek(0) return json.load(FP) def _write_file(content): FP.seek(0) FP.write(json.dumps(content)) FP.truncate() # This function is called before killing all processes to # make sure the temp file is deleted def close_data(): FP.close() if num_temp_files == 1 and os.path.isfile(FP.name): os.remove(FP.name) # Windows doesn't allow for temporary files to be opened by a subprocess # by default so we have to pass a flag to do so def temp_opener(name, flag, mode=0o777): return os.open(name, flag | os.O_TEMPORARY, mode) # TODO: Prevent directory from changing based on whether or not we are in root temp_dir = os.path.dirname(tempfile.mkdtemp()) prefix = "best_buy_bullet_bot_global_vars" suffix = ".json" available_temp_files = glob(os.path.join(temp_dir, f"{prefix}*{suffix}")) num_temp_files = len(available_temp_files) if num_temp_files == 1: # Open the existing temp file FP = open( os.path.join(temp_dir, available_temp_files[0]), "r+", opener=temp_opener if sys.platform == "win32" else None, ) else: if num_temp_files > 1: # Too many temp files Colors.warn( f"Too many temporary files detected: {available_temp_files}. Deleting all temporary files." ) for filename in available_temp_files: os.remove(os.path.join(temp_dir, filename)) # Create a new temp file since we don't have any FP = tempfile.NamedTemporaryFile("r+", prefix=prefix, suffix=suffix, dir=temp_dir) _write_file({}) class ReferenceVar: """Points to a specific variable in the temp file. If a variale in changed by one process all other processes with that variable will receive that change when trying to access the variable. """ def __init__(self, var_name): self.var_name = var_name def __new__(cls, var_name): # Return the value of the variable if it is a constant # else return this object self = super().__new__(cls) self.__init__(var_name) return self() if var_name.endswith("constant") else self def __call__(self): return _read_file()[self.var_name] def update(self, new_value, constant=False): # Update the value of the variable in the temp file updated_dict = _read_file() new_name = self.var_name new_name += "_constant" if constant else "" updated_dict.update({new_name: new_value}) _write_file(updated_dict) return new_value if constant else self if num_temp_files != 1: # We are in the main process. This is where variables are created. from keyring.util import platform_ # We store data here so it doesn't get overwritten during an update shared_dir = os.path.join( os.path.dirname(platform_.data_root()), "best_buy_bullet_bot" ) if not os.path.isdir(shared_dir): os.makedirs(shared_dir) # Save to temporary file HEADLESS_WARNED = ReferenceVar("HEADLESS_WARNED").update(False) SHARED_DIR = ReferenceVar("SHARED_DIR").update(shared_dir, constant=True) else: # We are in a separate process. This is where variables are copied over from the main process. # Copy over all variables in the temp file to the locals dict so they can be imported for var_name in _read_file(): locals()[var_name.replace("_constant", "")] = ReferenceVar(var_name)
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/best_buy_bullet_bot/data/__init__.py
__init__.py
import glob import os.path from pathlib import Path def calculate_indentation(string): return string[: string.index(string.strip())] def starts_with(string, *substrings, begin=0, end=None): starts_with_substring = list(map(string[begin:end].startswith, substrings)) if any(starts_with_substring): return substrings[starts_with_substring.index(True)] return False MSG = '''""" EASTER EGG: Thank you for reading the source code! To run the bot with a higher priority level and achieve better performance complete the following. If using Firefox, complete the following before moving on to the next step: WINDOWS: Open a Command Prompt window with "Run as administrator" https://www.educative.io/edpresso/how-to-run-cmd-as-an-administrator MAC: Enter the command `su` in your terminal to gain root privileges. Beware your settings may be different in the root session, but you can always return to a normal session with the `exit` command. Then regardless of your browser: Run `3b-bot --fast` in your shell. """''' split_msg = MSG.split("\n") def indent_msg(indent): return "\n".join( [indent + msg_line if msg_line.strip() else "" for msg_line in split_msg] ) if __name__ == "__main__": # Get path of best_buy_bullet_bot directory parent_dir = Path(__file__).parents[1] search_dir = os.path.join(parent_dir, "best_buy_bullet_bot") for filename in glob.iglob(os.path.join(search_dir, "**"), recursive=True): # Skip if not a python file if not filename.endswith(".py"): continue with open(filename, "r+") as f: code = f.read() lowercase_code = code.lower() # Skip file if no easter egg comments need to be added if "easter egg" not in lowercase_code: continue lines = code.split("\n") lower_lines = lowercase_code.split("\n") for idx, line in enumerate(lines): line = line.lower().strip() # Skip line if the text "easter egg" is not in it if "easter egg" not in line: continue # This variable means we will delete the following lines until we find a line that ends in the variable clear_multiline_string = starts_with(line, "'''", '"""') # If the multiline comment starts on the previous line if not clear_multiline_string and not starts_with(line, "'", '"', "#"): previous_line = lines[idx - 1] indent = calculate_indentation(previous_line) previous_line = previous_line.strip() clear_multiline_string = starts_with(previous_line, "'''", '"""') if clear_multiline_string: # Delete the previous line lines.pop(idx - 1) idx -= 1 else: # Its not a comment, just the text "easter egg" laying around somewhere continue else: indent = calculate_indentation(lines[idx]) if clear_multiline_string: # Delete all subsequent lines until the comment ends while not lines[idx + 1].strip().endswith(clear_multiline_string): lines.pop(idx + 1) lines.pop(idx + 1) # Replace the current line with the correct message lines.pop(idx) lines.insert(idx, indent_msg(indent)) easter_egg_code = "\n".join(lines) # Update the file with the new code if easter_egg_code != code: f.seek(0) f.write(easter_egg_code) f.truncate()
3b-bot
/3b-bot-1.1.0.tar.gz/3b-bot-1.1.0/custom_hooks/easter_egg.py
easter_egg.py
About ====== 3color Press is a flask based application intended to streamline making your own comic based website. It is a static website generator that takes markdown formatted text files and turns them into new pages. I am new to programming and I'm kind of brute learning python and flask with this project. The project is under heavy development and features are being added as we work on them, however a very functional core set of features is included For more in depth information on how to use check the doc pages You can see a demo site generated with version 0.1 of this tool at http://3color.noties.org Features * automatic handling of book pages, news pages and single pages * easily add a page to the main menu * easily add custom single pages * News page to collect news feed page * Support for showing a thumbnail of most recent comic in desired story line on every page * command line tools for easy management In Progress Features * custom themeing support * toggle-able theme elements * improvement on handling in site menus * admin interface * better error checking * much more?! Installation ------------- The package is available in pypi:: $ pip install 3color-Press see :doc:`install` Contribute ---------- If you're interested in contributing or checking out the source code you can take a look at: * Issue Tracker: https:github.com/chipperdoodles/3color/issues * Source Code: https:github.com/chipperdoodles/3color Support ------- If you're having problems or have some questions, feel free to check out the github page: https://github.com/chipperdoodles/3color License -------- 3color-Press is (c) Martin Knobel and contributors and is licensed under a BSD license see :doc:`license`
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/README.txt
README.txt
import os import platform import subprocess from setuptools import setup, find_packages #foldercreation instfolder = os.path.join(os.path.expanduser("~"), '3color-Press') folders = ['content','images','themes'] contfolders = ['book', 'news', 'single'] # TODO: add checks for if os.path.exists(instfolder) is False: os.mkdir(instfolder) for folder in folders: os.mkdir(os.path.join(instfolder, folder)) for folder in contfolders: os.mkdir(os.path.join(instfolder, 'content', folder)) with open('README.txt') as file: long_description = file.read() if platform.system() == 'Windows': subprocess.call( ['easy_install', "http://www.voidspace.org.uk/downloads/pycrypto26/pycrypto-2.6.win-amd64-py2.7.exe"] ) setup( name='3color-Press', version='0.2.1', author='Martin Knobel', author_email='mknobel@noties.org', license='BSD', url='3color.noties.org', description='A Flask based static site generator for comics', long_description=long_description, packages=find_packages(), include_package_data=True, data_files=[ (instfolder, ['threecolor/configs/example.settings.cfg']), ], install_requires=[ 'Click', 'Flask > 0.8', 'Flask-FlatPages', 'Frozen-Flask', 'Fabric' ], entry_points=''' [console_scripts] 3color=threecolor.manager:cli ''', classifiers=[ 'Environment :: Console', 'Environment :: Web Environment', 'Framework :: Flask', 'License :: OSI Approved :: BSD License', 'Intended Audience :: End Users/Desktop', 'Development Status :: 3 - Alpha', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Site Management', ] )
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/setup.py
setup.py
import os from flask import Flask from .tools import misc from .configs import config # set application root path APP_ROOT = os.path.dirname(os.path.abspath(__file__)) instfolder = config.instfolder THEME_DIR = config.THEME_DIR def create_site(): """App factory to create website""" if os.path.exists(instfolder): app = Flask('threecolor', instance_path=instfolder, instance_relative_config=True) # configure flask app from default settings, then overide with settings.cfg app.config.from_object('threecolor.configs.default_settings') app.config.from_pyfile('settings.cfg') # configure paths and folders according to instance path app.config['FLATPAGES_ROOT'] = os.path.join(app.instance_path, 'content') app.config['IMAGE_DIR'] = os.path.join(app.instance_path, 'images') app.config['FREEZER_DESTINATION'] = os.path.join(app.instance_path, app.config['BUILD_DIR']) from .site.coolviews import site, pages, freezer app.register_blueprint(site) pages.init_app(app) freezer.init_app(app) return app else: # app = Flask('threecolor') # # # configure flask app from default settings, then overide with settings.cfg # app.config.from_object('threecolor.configs.default_settings') misc.make_home(APP_ROOT) return app def create_admin(): """Place holder for eventual admin site interface""" pass
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/threecolor/application.py
application.py
import click import subprocess from datetime import date from .application import create_site, instfolder from .tools import publish, misc from .models import PagesCreator, PageCreator from .site import coolviews up = click.UNPROCESSED @click.group() def cli(): """ 3color Press command line tool This provides command line tools to manage your 3color site. Simply pass a command after 3color to get something done! The project folder is the 3color-Press folder in your home directory. Commands available: \b build Builds your website as static html to your build folder. The default build folder is 'build' in your project folder \b compress Archives your build directory into a tar.gz file. Does the same as if your PUB_METHOD is local \b publish Pushes your website to your remote server. It will use configured PUB_METHOD by default unless you supply --pubmethod option. Using --pubmethod will override your default method and must be one of these options: sftp, rsync, local, or git. \b example: 3color publish --pubmethod rysnc \b all Builds and then publishes your website. This is the same as running '3color build' and then '3color publish' \b open Opens the project folder in your file browser \b atom If you have the Atom Editor installed, this will call on atom to open your project folder in atom \b newpage Creates a new page (.md file) based on your inputs. You can pass the option --batch in order to created a batch of pages with auto page numbering and file naming. \b example: 3color newpage --batch \b run Runs your website locally on port 5000 and opens http://localhost:5000 in your default web browser. Use this command in order to see what your website will look like before you build it. Useful for Theme building. press contrl+c to halt the live server. """ pass @cli.command(name='all') def build_push(): """Builds and then publishes your website.""" click.echo('building to build folder') app = create_site() coolviews.chill() click.echo('publishing with default pub method') publish.publish @cli.command() def build(): """Builds website into static files""" click.echo('building') app = create_site() coolviews.chill() @cli.command() def compress(): """Compress build folder into a tar.gz file""" click.echo('compressing') execute(publish.archive) @cli.command(name='publish') @click.option('--pubmethod', type=click.Choice(['sftp', 'rsync', 'local', 'git' ])) def push_site(pubmethod): """Publish site to remote server""" click.echo('publishing') if pubmethod: publish.publish(pubmethod) else: publish.publish() # FIXME launches browser windows @cli.command() def run(): """Run website locally in debug mode""" click.launch('http://localhost:5000/') app = create_site() app.run() @cli.command(name='open') def open_file(): """Open project folder""" click.launch(instfolder) @cli.command() @click.option('--batch', is_flag=True, help='For making more than one new page') @click.option('--pagetype', prompt='Page type to be created', type=click.Choice(['book', 'news', 'single']), default='book') # TODO: Create pagetype specific forms def newpage(batch, pagetype): """Create a new page""" path = misc.page_dir(pagetype) if batch: pamount = click.prompt('Amount of new pages to make', type=int) lname = click.prompt('The title of the Book', default='', type=up) sname = click.prompt('The shortname of your book (used for filenames)', default='', type=up) ptype = pagetype data = dict( longname=lname, shortname=sname, pagetype=ptype, path=path, page_amount=pamount ) thing = PagesCreator(**data) thing.write_page() else: lname = click.prompt('The title of the Book', default='', type=up) sname = click.prompt('The shortname of your book (used for filenames)', default='', type=up) ptype = pagetype ptitle = click.prompt('The title of the page', default='{:%Y-%m-%d}'.format(date.today())) pnumber = click.prompt('The number of the page', type=int) chptr = click.prompt('The chapter number', type=int) img = click.prompt('The name of the image file of your comic page', default=sname+'_'+str(pnumber)+'.png', type=up) menu = click.prompt('True or False for link in main menu', type=bool, default=False) data = { "longname": lname, "shortname": sname, "pagetype": ptype, "pagetitle": ptitle, "pagenumber": pnumber, "chapter": chptr, "image": img, "menu": menu, "path": path } thing = PageCreator(**data) thing.write_page() @cli.command() def atom(): """ Open project folder with atom editor""" try: if misc.system == 'Windows': subprocess.check_call(["atom", instfolder], shell=True) else: subprocess.check_call(["atom", instfolder]) except OSError as e: print(os.strerror(e)) print("The atom editor command line tool not installed") # @cli.command(name='setup') # def make_instance(): # """Create your Project folder and copy over default config file""" # misc.make_home()
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/threecolor/manager.py
manager.py
""" 3color Press A Static Website generator by a webcomic author for webcomic authors """ __author__='Martin Knobel' __license__='BSD' __version__='0.2.1'
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/threecolor/__init__.py
__init__.py
import os import yaml from . import __version__ from datetime import date class PageHeader(object): """ Class that handles page header data. The page header is a yaml header at the beginnning of the markdown file that will be turned into a page. """ def __init__(self, **kwargs): # self.longname = kwargs['longname'] # self.pagetype = kwargs['pagetype'] # self.pageamount = kwargs['pageamount'] # self.pagetitle = kwargs['pagetitle'] # self.pagenumber = kwargs['pagenumber'] # self.published = kwargs['pub'] # self.modified = kwargs['mod'] # self.image = kwargs['image'] # self.menu = kwargs['menu'] self.__dict__.update(kwargs) @property def header(self): """ Make a dict from kwargs """ return { "title": self.pagetitle, "published": self.pub, "modified": self.mod, "page_type": self.pagetype, "book": { 'title': self.longname, 'chapter': self.chapter, 'page_number': self.pagenumber, 'image': self.image }, "menu": self.menu, "version": __version__ } def write_page(self): """ Writes the dict from header funtion into a file. This is our page metadata information""" name = os.path.join(self.path, self.shortname+'_'+str(self.pagenumber)+'.md') with open(name, "ab") as f: yaml.dump(self.header, f) def dump(self): """test function""" name = os.path.join(self.path, self.shortname+'_'+str(self.pagenumber)+'.md') info = yaml.safe_dump(self.header) return name+'\n'+info class PagesCreator(PageHeader): """Subclass of PageHeader for making batch yaml headers and markdown files""" def __init__(self, **kwargs): super(PagesCreator, self).__init__(**kwargs) self.index = 0 self.pub = '{:%Y-%m-%d}'.format(date.today()) self.mod = '{:%Y-%m-%d}'.format(date.today()) def header(self, n): """ Overrides PageHeader's header funtion to one needed for batch creation """ return { "title": '', "published": self.pub, "modified": self.mod, "page_type": self.pagetype, "book": {'title': self.longname, 'chapter': '', 'page_number': n, 'image': ''}, "menu": False, "version": __version__ } def write_page(self): """ Writes the dict from header funtion into a file. This is our page metadata information""" for x in range(1, self.page_amount+1): name = os.path.join(self.path, self.shortname+'_'+str(self.index+x)+'.md') number = self.index+x with open(name, "ab") as f: yaml.safe_dump(self.header(number), f) class PageCreator(PageHeader): def __init__(self, **kwargs): super(PageCreator, self).__init__(**kwargs) self.pub = '{:%Y-%m-%d}'.format(date.today()) self.mod = '{:%Y-%m-%d}'.format(date.today())
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/threecolor/models.py
models.py
import os from ..configs import config from flask import abort, current_app, Blueprint, render_template, send_from_directory from flask_flatpages import FlatPages from flask_frozen import Freezer freezer = Freezer() pages = FlatPages() cfg = config.make_usr_cfg() site = Blueprint('site', __name__, url_prefix='', template_folder=cfg['TEMPLATES'], static_folder=cfg['STATIC'], static_url_path='/static/site' ) @site.context_processor def page_types(): # injects variables for book pages and menu pages, menu pages are used to build main menu links menu_pages = (p for p in pages if (p['menu'])) book_page = (p for p in pages if 'book' == p['page_type']) news_page = (p for p in pages if 'news' == p['page_type']) # FIXME: uses same name as route function below thumb_nail = latest_comic(book_page, current_app.config['THUMB_STORY'], 1) book_list = (p['page_type'] for p in pages) # FIXME: uses same name as book_list function below return { "book_page": book_page, "menu_pages": menu_pages, "news_page": news_page, "thumb_nail": thumb_nail, "book_list": book_list, "pages": pages } def total_pages(pages, book): # takes a count of pages in the book and returns sum of pages, used for page navigation t_pages = (1 for p in pages if p.meta['book'] == book) t_pages = sum(t_pages) return t_pages def latest_comic(pages, book, limit=None): # for sorting published pages that are books in the main story by latest l_comic = (p for p in pages if ((p['page_type'] == 'book') and p['book']['title'] == book)) l_comic = sorted(l_comic, reverse=True, key=lambda p: p.meta['published']) return l_comic[:limit] def page_feed(pages, limit=None): # for sorting published pages that are books by latest l_comic = (p for p in pages if p['page_type'] == 'book') l_comic = sorted(l_comic, reverse=True, key=lambda p: p.meta['published']) return l_comic[:limit] def book_list(): # returns a list of the book titles in book type first_page = (p for p in pages if p['book']['chapter'] == 1 and p['book']['page_number'] == 1) book_titles = [p['book']['title'] for p in first_page] return book_titles @site.route('/images/<name>') # static image file delivery def images(name): path = current_app.config['IMAGE_DIR'] if '..' in name or name.startswith('/'): abort(404) else: return send_from_directory(path, name) @freezer.register_generator # makes sure images in the instance/images folder get built into site def images_url_generator(): path = os.listdir(current_app.config['IMAGE_DIR']) for f in path: yield '/images/'+f @site.route('/') def index(): # take 1 most recent page of published comics front_page = latest_comic(pages, current_app.config['MAIN_STORY'], 1) return render_template('home.html', front_page=front_page) @site.route('/books/') def books(): # finds and lists pages that are chapter: 1 and page_number: 1 in yaml header first_page = (p for p in pages if p['book']['chapter'] == 1 and p['book']['page_number'] == 1) return render_template('books.html', first_page=first_page) @site.route('/news/') def news(): # renders news template return render_template('news.html') # @site.route('/atom.xml') # atom feed, only works with a patch to werkzeug/contrip/atom.py file will look into more # https://github.com/mitsuhiko/werkzeug/issues/695 # def atom_feed(): # feed = AtomFeed('Feed for '+current_app.config['SITE_NAME'], # feed_url=current_app.config['DOMAIN']+url_for('.atom_feed'), # url=current_app.config['DOMAIN']) # # comic_feed = (p for p in pages if p.meta['page_type'] != 'single_page') # comic_feed = page_feed(pages, 10) # for p in comic_feed: # feed.add(p.meta['title'], # content_type='html', # url=current_app.config['DOMAIN']+p.path+'.html', # updated=p.meta['published'], # summary=p.body) # return feed.get_response() @site.route('/<name>.html') def single_page(name): # route for custom single pages, usually text pages such as about me or f.a.q's path = '{}/{}'.format(current_app.config['PAGE_DIR'], name) page = pages.get_or_404(path) return render_template('page.html', page=page) @site.route('/news/<name>.html') def news_page(name): # route for single pages, usually text pages path = '{}/{}'.format(current_app.config['NEWS_DIR'], name) page = pages.get_or_404(path) return render_template('page.html', page=page) @site.route('/<book>/c<int:chapter>/p<int:number>/<name>.html') def comic_page(book, chapter, number, name): # variables after 'p' are used to create pagination links within the book stories. # these are only passed into the page.html template and work only on 'comic_page' urls path = '{}/{}'.format(current_app.config['BOOK_DIR'], name) p = pages.get_or_404(path) t_pages = total_pages(pages, p['book']['title']) minus = p['book']['page_number'] - 1 plus = p['book']['page_number'] + 1 current_book = p['book']['title'] current_chapter = p.meta['book']['chapter'] first_page = (p for p in pages if p['book']['page_number'] == 1 and p['book']['title'] == current_book) last_page = (p for p in pages if p['book']['page_number'] == t_pages) previous_page = (p for p in pages if p['book']['page_number'] == minus) next_page = (p for p in pages if p['book']['page_number'] == plus) return render_template( 'comic.html', current_book=current_book, current_chapter=current_chapter, p=p, previous_page=previous_page, next_page=next_page, t_pages=t_pages, last_page=last_page, first_page=first_page ) def chill(): # function to build the site into static files freezer.freeze()
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/threecolor/site/coolviews.py
coolviews.py
""" The main site views """ __author__='Martin Knobel'
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/threecolor/site/__init__.py
__init__.py
DEBUG = True FLATPAGES_AUTO_RELOAD = DEBUG FLATPAGES_EXTENSION = '.md' FLATPAGES_ROOT = 'content' FREEZER_DESTINATION_IGNORE = ['.git*', '.gitignore', 'CNAME'] FEEZER_RELATIVE_URLS = True SITE_NAME = '3color Press Site' BUILD_DIR = 'build' BOOK_DIR = 'book' PAGE_DIR = 'single' NEWS_DIR = 'news' DOMAIN = '' MAIN_STORY = '' THUMB_STORY = '' USER_NAME = '' REMOTE_SERVER = '' PUB_METHOD = 'local' ACTIVE_THEME = 'default'
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/threecolor/configs/default_settings.py
default_settings.py
import os import shutil from flask import config from . import default_settings APP_ROOT = os.path.dirname(os.path.abspath(__file__)) # Flask instance folder, currently folder named 3color-Press in user's home folder instfolder = os.path.join(os.path.expanduser("~"), '3color-Press') examplecfg = os.path.join(instfolder, 'example.settings.cfg') THEME_DIR = os.path.join(instfolder, 'themes') def cfg_check(file): if os.path.exists(file): return True elif os.path.exists(examplecfg): shutil.copyfile(examplecfg, file) return True else: return False def make_usr_cfg(): if os.path.exists(instfolder): cfgfile = os.path.join(instfolder, 'settings.cfg') cfgcheck = cfg_check(cfgfile) # config using subclass of flask Config usr_cfg = config.Config(instfolder) usr_cfg.from_object(default_settings) if cfgcheck is True: usr_cfg.from_pyfile(cfgfile) # configure some path based values usr_cfg['TEMPLATES'] = os.path.join(THEME_DIR, usr_cfg['ACTIVE_THEME'], 'templates') usr_cfg['STATIC'] = os.path.join(THEME_DIR, usr_cfg['ACTIVE_THEME'], 'static') usr_cfg['FLATPAGES_ROOT'] = os.path.join(instfolder, 'content') usr_cfg['FREEZER_DESTINATION'] = os.path.join(instfolder, usr_cfg['BUILD_DIR']) # check to see if there is a theme folder with same name as active theme config if os.path.exists(os.path.join(THEME_DIR, usr_cfg['ACTIVE_THEME'])): usr_cfg['IMAGE_DIR'] = os.path.join(instfolder, 'images') else: usr_cfg['TEMPLATES'] = 'templates' usr_cfg['STATIC'] = 'static' return usr_cfg else: usr_cfg = config.Config(APP_ROOT) usr_cfg.from_object(default_settings) usr_cfg['TEMPLATES'] = 'templates' usr_cfg['STATIC'] = 'static' return usr_cfg
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/threecolor/configs/config.py
config.py
""" The main site views """ __author__='Martin Knobel'
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/threecolor/configs/__init__.py
__init__.py
import os import subprocess import shutil import platform from ..configs import config instfolder = config.instfolder system = platform.system() def page_dir(dirname): """used in command line tools to determine path for content type""" ptype_dir = os.path.join(instfolder, 'content', dirname) return ptype_dir def open_browser(): """ Try's to open system's file browser. Currently the command line tool uses click.launch but this may be used for future admin interface """ if system == 'Windows': os.startfile(instfolder['open']) elif system == 'Darwin': subprocess.call(["open", instfolder]) else: try: subprocess.call(['xdg-open', instfolder]) except OSError: print("Operating system doesn't have lazy file browser opener") def make_home(root_path): """ This function looks for the user's 3color-Press folder (instance folder) and creates one if it doesn't exist. Currently not in use """ inst_dir_list = ['content', 'images', 'themes'] content_dir_list = ['book', 'news', 'single'] if os.path.exists(instfolder): print("3color-Press folder already exists") else: os.mkdir(instfolder) shutil.copyfile(os.path.join(root_path, 'configs', 'example.settings.cfg'), os.path.join(instfolder, 'settings.cfg')) for folder in inst_dir_list: os.mkdir(os.path.join(instfolder, folder)) for folder in content_dir_list: os.mkdir(os.path.join(instfolder, 'content', folder))
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/threecolor/tools/misc.py
misc.py
import click from ..models import PagesCreator, PageCreator from ..application import page_dir from ..manager import cli # TODO currently file is not used @cli.command() @click.option('--batch', is_flag=True, help='For making more than one new page') @click.option('--pagetype', prompt='Page type to be created', type=click.Choice(['book', 'news', 'single'])) def newpage(batch, pagetype): """Creates a new page, prompting you for information""" path = page_dir(pagetype) if batch: pamount = click.prompt('Amount of new pages to make', type=int) lname = click.prompt('The title of the Book', default=None) sname = click.prompt('The shortname of your book (used for filenames)', default='') ptype = pagetype data = { "longname": lname, "shortname": sname, "pagetype": ptype, "path": path, "page_amount": pamount } thing = PagesCreator(**data) thing.write_page() else: lname = click.prompt('The title of the Book', default='') sname = click.prompt('The shortname of your book (used for filenames)', default='') ptype = pagetype ptitle = click.prompt('The title of the page', default=None) pnumber = click.prompt('The number of the page', type=int, default=None) chptr = click.prompt('The chapter number', type=int, default=None) img = click.prompt('The name of the image file of your comic page', default=sname+'_'+str(pnumber)+'.png') menu = click.prompt('True or False if you want to show up in main menu', type=bool, default=False) data = { "longname": lname, "shortname": sname, "pagetype": ptype, "pagetitle": ptitle, "pagenumber": pnumber, "chapter": chptr, "image": img, "menu": menu, "path": path } thing = PageCreator(**data) click.echo(thing.dump())
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/threecolor/tools/pagecreator.py
pagecreator.py
""" Tools for 3color Press """ __author__='Martin Knobel'
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/threecolor/tools/__init__.py
__init__.py
import os import subprocess from ..application import create_site from ..configs import config # TODO: make fabric optional from fabric.api import * from fabric.api import execute from fabric.contrib.project import rsync_project from fabric.contrib.files import exists from shutil import make_archive instfolder = config.instfolder cfg = config.make_usr_cfg() # configure user and hostname for remote server env.user = cfg['USER_NAME'] env.hosts = cfg['REMOTE_SERVER'] pub_method = cfg['PUB_METHOD'] build_dir = cfg['FREEZER_DESTINATION'] def archive(): """ Makes a local tar.gz file """ make_archive(os.path.join(instfolder, '3colorSite'), 'gztar', build_dir) def rsync(): """ Uses a wrapper to call rsync to deploy your site with the rsync tool this has the delete option which will delete any remote files that are not in your local build folder """ local = os.path.join(instfolder, build_dir+'/') remote = '3colorsite/' rsync_project(remote, local, delete=True) # TODO test functionality def git_deploy(): """ simply changes the directory to your build directory and calls git commits to add all files, commit all changes with commit message updated and then push your commit, then change back to your project directory """ project = os.getcwd() local = os.path.join(instfolder, build_dir) os.chdir(local) subprocess.call(['git', 'add', '-A']) subprocess.call(['git', 'commit', '-a', '-m', 'updated']) subprocess.call(['git', 'push']) os.chdir(project) # TODO: make nicer, add non-fabric plain FTP support def sftp(): """ archives then uploads site via fabric sftp and then unarchives on server. The remote folder for your site will be 3colorsite and contents will be deleted if the directory exists remotely therefore ensuring to remove changes before the upload """ make_archive(os.path.join(instfolder, '3colorSite'), 'gztar', build_dir) tarfile = os.path.join(instfolder, '3colorSite.tar.gz') if exists('~/3colorSite'): run('rm -rf ~/3colorSite/*') put(tarfile, '~/3colorSite/3colorSite.tar.gz') with cd('~/3colorSite/'): run('tar xzf 3colorSite.tar.gz') run('rm -rf 3colorSite.tar.gz') else: run('mkdir ~/3colorSite') put(tarfile, '~/3colorSite/3colorSite.tar.gz') with cd('~/3colorSite/'): run('tar xzf 3colorSite.tar.gz') run('rm -rf 3colorSite.tar.gz') os.remove(tarfile) def publish(pubmethod=pub_method): """Main function to pubish site""" if pubmethod == 'sftp': execute(sftp) elif pubmethod == 'rsync': execute(rsync) elif pubmethod == 'git': git_deploy() elif pubmethod == 'local': archive() else: print("You did not configure your publish method")
3color-Press
/3color-Press-0.2.1.tar.gz/3color-Press-0.2.1/threecolor/tools/publish.py
publish.py
# 3d-connectX-env [![BuildStatus][build-status]][ci-server] [![PackageVersion][pypi-version]][pypi-home] [![Stable][pypi-status]][pypi-home] [![Format][pypi-format]][pypi-home] [![License][pypi-license]](LICENSE) ![pattern1.gif](assets/pattern1.gif) [build-status]: https://travis-ci.com/youngeek-0410/3d-connectX-env.svg?branch=main [ci-server]: https://travis-ci.com/youngeek-0410/3d-connectX-env [pypi-version]: https://badge.fury.io/py/3d-connectX-env.svg [pypi-license]: https://img.shields.io/github/license/youngeek-0410/3d-connectX-env [pypi-status]: https://img.shields.io/pypi/status/3d-connectX-env.svg [pypi-format]: https://img.shields.io/pypi/format/3d-connectX-env.svg [pypi-home]: https://badge.fury.io/py/3d-connectX-env [python-version]: https://img.shields.io/pypi/pyversions/3d-connectX-env.svg [python-home]: https://python.org 3D connectX repository, developed for the [OpenAI Gym](https://github.com/openai/gym) format. ## Installation The preferred installation of `3d-connectX-env` is from `pip`: ```shell pip install 3d-connectX-env ``` ## Usage ### Python ```python import gym_3d_connectX import gym env = gym.make('3d-connectX-v0') env.reset() env.utils.win_reward = 100 env.utils.draw_penalty = 50 env.utils.lose_penalty = 100 env.utils.could_locate_reward = 10 env.utils.couldnt_locate_penalty = 10 env.utils.time_penalty = 1 env.player = 1 actions = [0, 0, 1, 1, 2, 2, 4, 4, 0, 0, 1, 1, 2, 2, 0, 3] for action in actions: obs, reward, done, info = env.step(action) env.render(mode="plot") ``` ## Environments The environments only send reward-able game-play frames to agents; No cut-scenes, loading screens, etc. are sent to an agent nor can an agent perform actions during these instances. Environment: `3d-connectX-v0` ### Factor at initialization. | Key | Type | Description |:------------------------|:---------|:------------------------------------------------------| | `num_grid ` | `int` | Length of a side. | `num_win_seq` | `int` | The number of sequence necessary for winning. | `win_reward` | `float` | The reward agent gets when win the game. | `draw_penalty` | `float` | The penalty agent gets when it draw the game. | `lose_penalty` | `float` | The penalty agent gets when it lose the game. | `couldnt_locate_penalty`| `float` | The penalty agent gets when it choose the location where the stone cannot be placed. | `could_locate_reward` | `float` | The additional reward for agent being able to put the stone. | `time_penalty` | `float` | The penalty agents gets along with timesteps. | `first_player` | `int` | Define which is the first player. ## Step Info about the rewards and info returned by the `step` method. | Key | Type | Description |:-------------------|:---------|:------------------------------------------------------| | `turn` | `int` | The number of the player at this step | `winner` | `int` | Value of the player on the winning side | `is_couldnt_locate`| `bool` | In this step the player chooses where to place the stone.
3d-connectX-env
/3d-connectX-env-1.0.1.tar.gz/3d-connectX-env-1.0.1/README.md
README.md
import setuptools import os def read_requirements(): """Parse requirements from requirements.txt.""" reqs_path = os.path.join('.', 'requirements.txt') with open(reqs_path, 'r') as f: requirements = [line.rstrip() for line in f] return requirements def main(): with open('README.md', 'r') as fp: readme = fp.read() setuptools.setup( name='3d-connectX-env', version='1.0.1', description='3D ConnectX for OpenAI Gym.', long_description=readme, long_description_content_type='text/markdown', url='https://github.com/youngeek-0410/3d-connectX-env', license='', author='Ryusei Ito', author_email='31807@toyota.kosen-ac.jp', packages=['gym_3d_connectX'], install_requires=read_requirements(), python_requires='>=3.7', ) main()
3d-connectX-env
/3d-connectX-env-1.0.1.tar.gz/3d-connectX-env-1.0.1/setup.py
setup.py
from gym.envs.registration import register register( id='3d-connectX-v0', entry_point='gym_3d_connectX.env:AnyNumberInARow3dEnv' )
3d-connectX-env
/3d-connectX-env-1.0.1.tar.gz/3d-connectX-env-1.0.1/gym_3d_connectX/__init__.py
__init__.py
import unittest import gym import gym_3d_connectX class TestCombination(unittest.TestCase): @classmethod def setUpClass(self): self.pattern = [ { "actions": [0, 0, 1, 1, 2, 2, 4, 4, 0, 0, 1, 1, 2, 2, 0, 3], "rewards": [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, -10, 100], "dones": [False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True], "players": [1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, 1], "winners": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "couldnt_locates": [False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False], }, ] self.envs = [] env = gym.make('3d-connectX-v0') env.reset() env.utils.win_reward = 100 env.utils.draw_penalty = 50 env.utils.lose_penalty = 100 env.utils.could_locate_reward = 10 env.utils.couldnt_locate_penalty = 10 env.utils.time_penalty = 1 env.player = 1 self.envs.append(env) @classmethod def tearDownClass(cls): print("Your environment has passed the test!!!!") def test_pattern(self): for env, answer_dict in zip(self.envs, self.pattern): for idx, action in enumerate(answer_dict["actions"]): obs, reward, done, info = env.step(action) self.assertEqual(answer_dict["rewards"][idx], reward) self.assertEqual(answer_dict["dones"][idx], done) self.assertEqual(answer_dict["players"][idx], info["turn"]) self.assertEqual(answer_dict["winners"][idx], info["winner"]) self.assertEqual(answer_dict["couldnt_locates"][idx], info["is_couldnt_locate"]) if __name__ == '__main__': unittest.main()
3d-connectX-env
/3d-connectX-env-1.0.1.tar.gz/3d-connectX-env-1.0.1/test/test.py
test.py
## Python 3D Models Converter A module, which helps convert different 3d formats **Version**: 0.9.0
3d-converter
/3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/README.md
README.md
import setuptools with open('README.md') as fh: long_description = fh.read() fh.close() setuptools.setup( name='3d-converter', version='0.9.0', author='Vorono4ka', author_email='crowo4ka@gmail.com', description='Python 3D Models Converter', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/vorono4ka/3d-converter', license='GPLv3', packages=setuptools.find_packages(), classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', ], python_requires='>=3.9', )
3d-converter
/3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/setup.py
setup.py
__all__ = [ 'formats', 'utilities' ]
3d-converter
/3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/__init__.py
__init__.py
import abc from models_converter.formats.universal import Scene class ParserInterface: @abc.abstractmethod def __init__(self, file_data: bytes or str): self.scene: Scene or None = None @abc.abstractmethod def parse(self): """ :return: """
3d-converter
/3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/interfaces/parser_interface.py
parser_interface.py
import abc from models_converter.formats.universal import Scene class WriterInterface: MAGIC: bytes @abc.abstractmethod def __init__(self): self.writen: bytes or str = None @abc.abstractmethod def write(self, scene: Scene): """ :param scene: :return: """
3d-converter
/3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/interfaces/writer_interface.py
writer_interface.py