def session(file): print('\nWelcome to Vocabulary Expander!\n' '\nWhich mod do you prefer?\n' 'Just write one of the given names:\n' 'Smart / Simple\n' 'To exit print 0.') mod = input() mod = mod.capitalize() while mod != 'Simple' and mod != 'Smart': if mod == '0': program_exit() print('Wrong value. Try again. To exit print 0.') mod = input() mod = mod.capitalize() expander = Expander(file, mod) print('\nWhat number of words would you like to learn for each iteration?' '\nTo exit print value 0 or less.') w_num = int(input()) if w_num <= 0: program_exit() expander.teaching(w_num)
def testDoSubstitutionNoDefinition(self): if IGNORE_TEST: return executor = Executor() expander = Expander(executor, self.message) result = expander.do(SUBSTITUTION1) self.assertEqual(result[0], SUBSTITUTION1)
def __init__(self, template_string): """ :param str template_string: string containing template variables and template escape statements to execute """ self._extractor = LineExtractor(template_string) self._message = StatusMessage(self._extractor) self._executor = Executor() self._expander = Expander(self._executor, self._message) self._command = None # Command being processed self._define_variable_statements = []
def testDo(self): if IGNORE_TEST: return executor = Executor() executor.setDefinitions(DEFINITIONS) expander = Expander(executor, self.message) result = expander.do(SUBSTITUTION1) self.assertEqual(result[0], SUBSTITUTION1) result = expander.do(SUBSTITUTION2) expected = len(DEFINITIONS['a']) self.assertEqual(len(result), expected)
def testMakeSubtitutionList(self): if IGNORE_TEST: return substitution_list = Expander.makeSubstitutionList(DEFINITIONS) expected = np.prod([len(v) for v in DEFINITIONS.values()]) self.assertEqual(len(substitution_list), expected) substitution_list = Expander.makeSubstitutionList({}) self.assertEqual(len(substitution_list), 0) definitions = dict(DEFINITIONS) key = list(DEFINITIONS.keys())[0] del definitions[key] substitution_list = Expander.makeSubstitutionList(definitions) expected = np.prod([len(v) for v in definitions.values()]) self.assertEqual(len(substitution_list), expected)
def __init__(self, vp_value_count, output_shape, name='Full Network'): """ Initializes the Full Network. :param output_shape: (5-tuple) The desired output shape for generated videos. Must match video input shape. Legal values: (bsz, 3, 8, 112, 112) and (bsz, 3, 16, 112, 112) :param name: (str, optional) The name of the network (default 'Full Network'). Raises: ValueError: if 'vp_value_count' is not a legal value count ValueError: if 'output_shape' does not contain a legal number of frames. """ if vp_value_count not in self.VALID_VP_VALUE_COUNTS: raise ValueError('Invalid number of vp values: %d' % vp_value_count) if output_shape[2] not in self.VALID_FRAME_COUNTS: raise ValueError('Invalid number of frames in desired output: %d' % output_shape[2]) super(FullNetwork, self).__init__() self.net_name = name self.vp_value_count = vp_value_count self.output_shape = output_shape self.out_frames = output_shape[2] self.vgg = vgg16(pretrained=True, weights_path=vgg_weights_path) self.i3d = InceptionI3d(final_endpoint='Mixed_5c_small', in_frames=self.out_frames, pretrained=True, weights_path=i3d_weights_path) self.deconv = Deconv(in_channels=256, out_frames=self.out_frames) self.exp = Expander(vp_value_count=self.vp_value_count, out_frames=self.out_frames, out_size=28) self.trans = Transformer(in_channels=32 + self.vp_value_count) self.gen = Generator(in_channels=32 + 32, out_frames=self.out_frames)
def testExpandTemplateExpressions(self): if IGNORE_TEST: return executor = Executor() var = 'n' definitions = {var: [1, 2, 3]} executor.setDefinitions(definitions) expander = Expander(executor, self.message) template = "T{%s} + A -> T{%s+1}" % (var, var) expansion = expander.do(template) self.assertEqual(len(expansion), len(definitions[var])) # Check that each substitution is found for value in definitions[var]: found = False for substitution in expansion: if "T%d" % value in substitution: found = True break self.assertTrue(found)
def EnumerateExpanders(self): """Enumerate all storage expanders on the system returns: An array of object paths for storage expanders """ l = list() for i in self.iface.EnumerateExpanders(): obj = Expander(i) l.append(obj) return l
class Geochains: def __init__(self): self.pattern = PATTERN self.sub_rule = GeochainsSubstitutionRule() self.geodb = GeoIPDBMaxMind() self.sub_rule.geodb = self.geodb self.expander = Expander(self.pattern, self.sub_rule) def process_file(self, filename): f = open(filename, 'r') input_str = f.read() f.close() self.process_input(input_str) def process_input(self, input_str): output = self.expander.expand(input_str) print output
def __init__(self): self.pattern = PATTERN self.sub_rule = GeochainsSubstitutionRule() self.geodb = GeoIPDBMaxMind() self.sub_rule.geodb = self.geodb self.expander = Expander(self.pattern, self.sub_rule)
class TemplateProcessor(object): """ This class processes an Antimony model written using template variable substitutions. See the project README for syntax details. """ def __init__(self, template_string): """ :param str template_string: string containing template variables and template escape statements to execute """ self._extractor = LineExtractor(template_string) self._message = StatusMessage(self._extractor) self._executor = Executor() self._expander = Expander(self._executor, self._message) self._command = None # Command being processed self._define_variable_statements = [] @classmethod def processFile(cls, inpath, outpath): """ Processes template strings in a file. :param str inpath: path to the file containing the templated model :param str outpath: path to the file where the flattened model is placed """ template = '' with open(inpath, 'r') as infile: for line in infile: template += "\n" + line processor = cls(template) expansion = processor.do() with open(outpath, 'w') as outfile: outfile.write(expansion) @staticmethod def _makeComment(line): return "%s%s" % (COMMENT_STG, line) def _processCommand(self): """ Handles command processing, either the current line is a command or in the midst of processing a paired command. :param list-of-str expansion: :return bool: True if processed line """ line = self._extractor.getCurrentLine() line_type = self._extractor.getCurrentLineType() is_processed = False # Current line is a command if line_type == LINE_COMMAND: is_processed = True # Check for nested commands if self._command is not None: new_command = Command(line) # Is this a paired command? if new_command.getCommandVerb() \ == self._command.getCommandVerb(): if new_command.isEnd(): pass else: self._message.error("Cannot nest commands") # Valid placement for a command. self._command = Command(line) # DefineVariables Command if self._command.isDefineVariables(): if self._command.isBegin(): self._define_variables_statements = [] elif self._command.isEnd(): try: program = '\n'.join(self._define_variables_statements) self._executor.doScript(program) except Exception as err: msg = "***Error %s executing in : \n%s" \ % (str(err), program) self._message.error(msg) self._command = None # SetVersion command elif self._command.isSetVersion(): version = self._command.getArguments()[0] if float(version) > float(VERSION): self._message.error("Unsupported version %s" % version) self._command = None # Other commands else: self._message.error("Unknown command") # Process statements occurring within paired commands elif self._command is not None: is_processed = True if self._command.isDefineVariables() and self._command.isBegin(): self._define_variables_statements.append(line) else: self._message.error("Invalid paired command.") return is_processed def do(self): """ Processes the template string and returns the expanded lines for input to road runner. Phases 1. Construct content lines (non-blank, not comments) 2. Extract the template variable definitions 3. Construct the substitution instances 4. Process the lines with template variables State used: reads: _definitions :return str expanded_string: :raises ValueError: errors encountered in the template string """ cls = TemplateProcessor expansion = [] line, line_type = self._extractor.do() statements = [] while line is not None: if self._processCommand(): expansion.append(cls._makeComment(line)) # No command being processed else: # Transparent line (comment) if line_type == LINE_TRAN: expansion.append(line) elif line_type == LINE_NONE: pass # Line to be substituted elif line_type == LINE_SUBS: # Do the variable substitutions try: substitutions = self._expander.do(line) except Exception as err: msg = "Runtime error in expression" self._message.error(msg) if len(substitutions) > 1: expansion.append(cls._makeComment(line)) expansion.extend(substitutions) else: import pdb pdb.set_trace() raise RuntimeError("Unexepcted state") line, line_type = self._extractor.do() if self._command is not None: msg = "Still processing command %s at EOF" % str(self._command) self._message.error(msg) return "\n".join(expansion)
class MainWindow(QMainWindow): htmlReady = pyqtSignal(str) def __init__(self, app): QMainWindow.__init__(self) self.install_directory = os.getcwd() self.app = app self.book = None self.last_book = "" self.filename = "" self._part_is_new = False self.tread_running = False self.initTheme() self.createUi() self.loadPlugins() self.createMenus() self.createStatusBar() self.readSettings() self.text_edit.textChanged.connect(self.textChanged) def initTheme(self): settings = QSettings(QSettings.IniFormat, QSettings.UserScope, QCoreApplication.organizationName(), QCoreApplication.applicationName()) self.theme = settings.value("theme", "DarkFusion") hilite_color = settings.value( "hiliteColor", self.palette().highlight().color().name()) self.changeStyle(self.theme, hilite_color) def showEvent(self, event): if self.last_book: self.loadBook(self.last_book) def changeStyle(self, theme, hilite_color): self.theme = theme if theme == "DarkFusion": QApplication.setStyle(DarkFusion(hilite_color)) else: QApplication.setStyle(QStyleFactory.create(theme)) pal = self.app.palette() pal.setColor(QPalette.Highlight, QColor(hilite_color)) self.app.setPalette(pal) def createUi(self): self.content = Expander("Content", ":/images/parts.svg") self.images = Expander("Images", ":/images/images.svg") self.settings = Expander("Settings", ":/images/settings.svg") self.setWindowTitle(QCoreApplication.applicationName() + " " + QCoreApplication.applicationVersion()) vbox = QVBoxLayout() vbox.addWidget(self.content) vbox.addWidget(self.images) vbox.addWidget(self.settings) vbox.addStretch() self.content_list = QListWidget() self.content_list.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) content_box = QVBoxLayout() content_box.addWidget(self.content_list) self.item_edit = QLineEdit() self.item_edit.setMaximumHeight(0) self.item_edit.editingFinished.connect(self.editItemFinished) self.item_anim = QPropertyAnimation(self.item_edit, "maximumHeight".encode("utf-8")) content_box.addWidget(self.item_edit) button_layout = QHBoxLayout() plus_button = FlatButton(":/images/plus.svg") self.edit_button = FlatButton(":/images/edit.svg") self.trash_button = FlatButton(":/images/trash.svg") self.up_button = FlatButton(":/images/up.svg") self.down_button = FlatButton(":/images/down.svg") self.trash_button.enabled = False self.up_button.enabled = False self.down_button.enabled = False button_layout.addWidget(plus_button) button_layout.addWidget(self.up_button) button_layout.addWidget(self.down_button) button_layout.addWidget(self.edit_button) button_layout.addWidget(self.trash_button) content_box.addLayout(button_layout) self.content.addLayout(content_box) plus_button.clicked.connect(self.addPart) self.trash_button.clicked.connect(self.dropPart) self.up_button.clicked.connect(self.partUp) self.down_button.clicked.connect(self.partDown) self.edit_button.clicked.connect(self.editPart) self.image_list = QListWidget() self.image_list.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) image_box = QVBoxLayout() image_box.addWidget(self.image_list) image_button_layout = QHBoxLayout() image_plus_button = FlatButton(":/images/plus.svg") self.image_trash_button = FlatButton(":/images/trash.svg") self.image_trash_button.enabled = False image_button_layout.addWidget(image_plus_button) image_button_layout.addWidget(self.image_trash_button) image_box.addLayout(image_button_layout) self.images.addLayout(image_box) image_plus_button.clicked.connect(self.addImage) self.image_trash_button.clicked.connect(self.dropImage) scroll_content = QWidget() scroll_content.setLayout(vbox) scroll = QScrollArea() scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) scroll.setWidget(scroll_content) scroll.setWidgetResizable(True) scroll.setMaximumWidth(200) scroll.setMinimumWidth(200) self.navigationdock = QDockWidget("Navigation", self) self.navigationdock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.navigationdock.setWidget(scroll) self.navigationdock.setObjectName("Navigation") self.addDockWidget(Qt.LeftDockWidgetArea, self.navigationdock) self.splitter = QSplitter() self.text_edit = MarkdownEdit() self.text_edit.setFont(QFont("Courier", 15)) # 11 on Linux self.preview = QWebEngineView() self.preview.setMinimumWidth(300) self.setWindowTitle(QCoreApplication.applicationName()) self.splitter.addWidget(self.text_edit) self.splitter.addWidget(self.preview) self.setCentralWidget(self.splitter) self.content.expanded.connect(self.contentExpanded) self.images.expanded.connect(self.imagesExpanded) self.settings.expanded.connect(self.settingsExpanded) self.settings.clicked.connect(self.openSettings) self.content_list.currentItemChanged.connect(self.partSelectionChanged) self.image_list.currentItemChanged.connect(self.imageSelectionChanged) self.image_list.itemDoubleClicked.connect(self.insertImage) self.text_edit.undoAvailable.connect(self.undoAvailable) self.text_edit.redoAvailable.connect(self.redoAvailable) self.text_edit.copyAvailable.connect(self.copyAvailable) QApplication.clipboard().dataChanged.connect(self.clipboardDataChanged) def undoAvailable(self, value): self.undo_act.setEnabled(value) def redoAvailable(self, value): self.redo_act.setEnabled(value) def copyAvailable(self, value): self.copy_act.setEnabled(value) self.cut_act.setEnabled(value) def clipboardDataChanged(self): md = QApplication.clipboard().mimeData() self.paste_act.setEnabled(md.hasText()) def openSettings(self): dlg = Settings(self.book, self.install_directory) dlg.exec() if dlg.saved: self.setWindowTitle(QCoreApplication.applicationName() + " - " + self.book.name) def addPart(self): self.item_edit.setText("") self.item_edit.setFocus() self.item_anim.setStartValue(0) self.item_anim.setEndValue(23) self.item_anim.start() self._part_is_new = True def addItem(self): text = self.item_edit.text() if text: if not self.book.getPart(text): self.book.addPart(text) self.loadBook(self.last_book) def updateItem(self): text = self.item_edit.text() if text: if not self.book.getPart(text): self.book.updatePart( self.content_list.currentItem().data(1).name, text) self.loadBook(self.last_book) def editItemFinished(self): if self._part_is_new: self.addItem() else: self.updateItem() self.item_anim.setStartValue(23) self.item_anim.setEndValue(0) self.item_anim.start() def editPart(self): item = self.content_list.currentItem().data(1).name self.item_edit.setText(item) self.item_edit.setFocus() self.item_anim.setStartValue(0) self.item_anim.setEndValue(23) self.item_anim.start() self._part_is_new = False def dropPart(self): item = self.content_list.currentItem().data(1).name msgBox = QMessageBox() msgBox.setText("You are about to delete the part <i>" + item + "</i>") msgBox.setInformativeText("Do you really want to delete the item?") msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) msgBox.setDefaultButton(QMessageBox.Cancel) ret = msgBox.exec() if ret == QMessageBox.Yes: self.book.dropPart(item) self.loadBook(self.last_book) def addImage(self): fileName = "" dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) dialog.setNameFilter("Image Files(*.png *.jpg *.bmp *.gif);;All (*)") dialog.setWindowTitle("Load Image") dialog.setOption(QFileDialog.DontUseNativeDialog, True) dialog.setAcceptMode(QFileDialog.AcceptOpen) if dialog.exec_(): fileName = dialog.selectedFiles()[0] del dialog if not fileName: return base = os.path.basename(fileName) if not os.path.exists( os.path.join(self.book.source_path, "images", base)): copy(fileName, os.path.join(self.book.source_path, "images")) item = QListWidgetItem() item.setText(Path(fileName).name) item.setData( 1, os.path.join(self.book.source_path, "images", Path(fileName).name)) self.image_list.addItem(item) def dropImage(self): item = self.image_list.currentItem() image = item.data(1) filename = os.path.join(self.book.source_path, "parts", image) os.remove(filename) self.loadImages() def loadImages(self): self.image_list.clear() for root, dir, files in os.walk( os.path.join(self.book.source_path, "images")): for file in files: filename = os.path.join(self.book.source_path, "images", Path(file).name) item = QListWidgetItem() item.setToolTip("Doubleclick image to insert into text") item.setText(Path(file).name) item.setData(1, filename) self.image_list.addItem(item) def partUp(self): pos = self.content_list.currentRow() item = self.content_list.takeItem(pos) self.content_list.insertItem(pos - 1, item) self.content_list.setCurrentRow(pos - 1) self.book.partUp(item.data(1).name) def partDown(self): pos = self.content_list.currentRow() item = self.content_list.takeItem(pos) self.content_list.insertItem(pos + 1, item) self.content_list.setCurrentRow(pos + 1) self.book.partDown(item.data(1).name) def partSelectionChanged(self, item): if item: part = item.data(1) self.filename = os.path.join(self.book.source_path, "parts", part.src) with open(self.filename, "r") as f: t = f.read() self.text_edit.setPlainText(t) self.trash_button.enabled = True self.up_button.enabled = self.content_list.currentRow() > 0 self.down_button.enabled = self.content_list.currentRow( ) < self.content_list.count() - 1 self.edit_button.enabled = True else: self.text_edit.setText("") self.trash_button.enabled = False self.up_button.enabled = False self.down_button.enabled = False self.edit_button.enabled = False def imageSelectionChanged(self, item): if item: self.image_trash_button.enabled = True else: self.image_trash_button.enabled = False def contentExpanded(self, value): if value: self.images.setExpanded(False) self.settings.setExpanded(False) def imagesExpanded(self, value): if value: self.content.setExpanded(False) self.settings.setExpanded(False) def appearanceExpanded(self, value): if value: self.content.setExpanded(False) self.images.setExpanded(False) self.settings.setExpanded(False) def settingsExpanded(self, value): if value: self.content.setExpanded(False) self.images.setExpanded(False) def closeEvent(self, event): self.writeSettings() event.accept() def createMenus(self): new_icon = QIcon(QPixmap(":/images/new.svg")) open_icon = QIcon(QPixmap(":/images/open.svg")) book_icon = QIcon(QPixmap(":/images/book.svg")) bold_icon = QIcon(QPixmap(":/images/bold.svg")) italic_icon = QIcon(QPixmap(":/images/italic.svg")) image_icon = QIcon(QPixmap(":/images/image.svg")) table_icon = QIcon(QPixmap(":/images/table.svg")) á_icon = QIcon(QPixmap(":/images/á.svg")) ã_icon = QIcon(QPixmap(":/images/ã.svg")) é_icon = QIcon(QPixmap(":/images/é.svg")) ê_icon = QIcon(QPixmap(":/images/ê.svg")) ó_icon = QIcon(QPixmap(":/images/ó.svg")) new_act = QAction(new_icon, "&New", self) new_act.setShortcuts(QKeySequence.New) new_act.setStatusTip("Create a new ebook project") new_act.triggered.connect(self.newFile) new_act.setToolTip("Create new ebook project") open_act = QAction(open_icon, "&Open", self) open_act.setShortcuts(QKeySequence.Open) open_act.setStatusTip("Open an existing ebook project") open_act.triggered.connect(self.open) open_act.setToolTip("Open an existing ebook project") book_act = QAction(book_icon, "&Create Book", self) book_act.setShortcuts(QKeySequence.SaveAs) book_act.setStatusTip("Create an ebook") book_act.triggered.connect(self.create) book_act.setToolTip("Create an ebook") pdf_act = QAction("Create &PDF", self) pdf_act.setStatusTip("Create PDF") pdf_act.setToolTip("Create PDF") pdf_act.triggered.connect(self.pdfExport) settings_act = QAction("&Settings", self) settings_act.setStatusTip("Open settings dialog") settings_act.triggered.connect(self.settingsDialog) settings_act.setToolTip("Open settings dialog") exit_act = QAction("E&xit", self) exit_act.setShortcuts(QKeySequence.Quit) exit_act.setStatusTip("Exit the application") exit_act.triggered.connect(self.close) self.undo_act = QAction("Undo", self) self.undo_act.setShortcut(QKeySequence.Undo) self.undo_act.setEnabled(False) self.undo_act.triggered.connect(self.doUndo) self.redo_act = QAction("Redo", self) self.redo_act.setShortcut(QKeySequence.Redo) self.redo_act.setEnabled(False) self.undo_act.triggered.connect(self.doRedo) self.cut_act = QAction("Cu&t", self) self.cut_act.setShortcut(QKeySequence.Cut) self.cut_act.triggered.connect(self.doCut) self.cut_act.setEnabled(False) self.copy_act = QAction("&Copy", self) self.copy_act.setShortcut(QKeySequence.Copy) self.copy_act.triggered.connect(self.doCopy) self.copy_act.setEnabled(False) self.paste_act = QAction("&Paste", self) self.paste_act.setShortcut(QKeySequence.Paste) self.paste_act.triggered.connect(self.doPaste) self.paste_act.setEnabled(False) bold_act = QAction(bold_icon, "Bold", self) bold_act.setShortcut(Qt.CTRL + Qt.Key_B) bold_act.triggered.connect(self.bold) italic_act = QAction(italic_icon, "Italic", self) italic_act.setShortcut(Qt.CTRL + Qt.Key_I) italic_act.triggered.connect(self.italic) image_act = QAction(image_icon, "Image", self) image_act.setShortcut(Qt.CTRL + Qt.Key_G) image_act.triggered.connect(self.insertImage) image_act.setToolTip("Insert an image") table_act = QAction(table_icon, "Table", self) table_act.setShortcut(Qt.CTRL + Qt.Key_T) table_act.triggered.connect(self.insertTable) table_act.setToolTip("Insert a table") á_act = QAction(á_icon, "á", self) á_act.triggered.connect(self.insertLetterA1) á_act.setToolTip("Insert letter á") ã_act = QAction(ã_icon, "ã", self) ã_act.triggered.connect(self.insertLetterA2) ã_act.setToolTip("Insert letter ã") é_act = QAction(é_icon, "é", self) é_act.triggered.connect(self.insertLetterE1) é_act.setToolTip("Insert letter é") ê_act = QAction(ê_icon, "ê", self) ê_act.triggered.connect(self.insertLetterE2) ê_act.setToolTip("Insert letter ê") ó_act = QAction(ó_icon, "ó", self) ó_act.triggered.connect(self.insertLetterO1) ó_act.setToolTip("Insert letter ó") about_act = QAction("&About", self) about_act.triggered.connect(self.about) about_act.setStatusTip("Show the application's About box") spell_act = QAction("&Spellcheck", self) spell_act.setShortcut(Qt.CTRL + Qt.Key_P) spell_act.triggered.connect(self.spellCheck) spell_act.setStatusTip("Spellcheck") file_menu = self.menuBar().addMenu("&File") file_menu.addAction(new_act) file_menu.addAction(open_act) file_menu.addAction(book_act) file_menu.addAction(pdf_act) file_menu.addSeparator() file_menu.addAction(settings_act) file_menu.addSeparator() file_menu.addAction(exit_act) edit_menu = self.menuBar().addMenu("&Edit") edit_menu.addAction(self.undo_act) edit_menu.addAction(self.redo_act) edit_menu.addSeparator() edit_menu.addAction(self.cut_act) edit_menu.addAction(self.copy_act) edit_menu.addAction(self.paste_act) format_menu = self.menuBar().addMenu("&Format") format_menu.addAction(bold_act) format_menu.addAction(italic_act) insert_menu = self.menuBar().addMenu("&Insert") insert_menu.addAction(image_act) insert_menu.addAction(table_act) for key in Plugins.generatorPluginNames(): gen = Plugins.getGeneratorPlugin(key) if gen: act = QAction(gen.display_name, self) #act.triggered.connect(self.insertTable) #act.setToolTip("Insert a table") insert_menu.addAction(act) act.triggered.connect(gen.menu_action) help_menu = self.menuBar().addMenu("&Help") help_menu.addAction(about_act) help_menu.addAction(spell_act) file_tool_bar = self.addToolBar("File") file_tool_bar.addAction(new_act) file_tool_bar.addAction(open_act) file_tool_bar.addAction(book_act) format_tool_bar = self.addToolBar("Format") format_tool_bar.addAction(bold_act) format_tool_bar.addAction(italic_act) insert_toolbar = self.addToolBar("Insert") insert_toolbar.addAction(image_act) insert_toolbar.addAction(table_act) insert_toolbar.addAction(á_act) insert_toolbar.addAction(ã_act) insert_toolbar.addAction(é_act) insert_toolbar.addAction(ê_act) insert_toolbar.addAction(ó_act) def doUndo(self): self.text_edit.undo() def doRedo(self): self.text_edit.redo() def doCut(self): self.text_edit.cut() def doCopy(self): self.text_edit.copy() def doPaste(self): self.text_edit.paste() def insertImage(self): if not self.book: QMessageBox.warning(self, QCoreApplication.applicationName(), "You have to load or create a book first!") return if not self.filename: QMessageBox.warning( self, QCoreApplication.applicationName(), "You have to select part from the book content first!") return if self.image_list.count() == 0: QMessageBox.warning( self, QCoreApplication.applicationName(), "You have to add an image to the image list first!") return if not self.image_list.currentItem(): QMessageBox.warning( self, QCoreApplication.applicationName(), "You have to select an image from the image list first!") return item = self.image_list.currentItem() filename = item.text() cursor = self.text_edit.textCursor() pos = cursor.position() base = filename.split(".")[0].replace("_", "-") cursor.insertText("![" + base + "](../images/" + filename + " \"" + base + "\")") cursor.setPosition(pos) self.text_edit.setTextCursor(cursor) def insertTable(self): cursor = self.text_edit.textCursor() pos = cursor.position() cursor.insertText( "| alignLeft | alignCenter | unAligned | alignRight |\n" "| :--- | :---: | --- | ---: |\n" "| cell a | cell b | cell c | cell d |\n" "| cell e | cell f | cell g | cell h |\n") cursor.setPosition(pos) self.text_edit.setTextCursor(cursor) def insertLetterA1(self): cursor = self.text_edit.textCursor() pos = cursor.position() cursor.insertText("á") cursor.setPosition(pos + 1) self.text_edit.setTextCursor(cursor) def insertLetterA2(self): cursor = self.text_edit.textCursor() pos = cursor.position() cursor.insertText("ã") cursor.setPosition(pos + 1) self.text_edit.setTextCursor(cursor) def insertLetterE1(self): cursor = self.text_edit.textCursor() pos = cursor.position() cursor.insertText("é") cursor.setPosition(pos + 1) self.text_edit.setTextCursor(cursor) def insertLetterE2(self): cursor = self.text_edit.textCursor() pos = cursor.position() cursor.insertText("ê") cursor.setPosition(pos + 1) self.text_edit.setTextCursor(cursor) def insertLetterO1(self): cursor = self.text_edit.textCursor() pos = cursor.position() cursor.insertText("ó") cursor.setPosition(pos + 1) self.text_edit.setTextCursor(cursor) def createStatusBar(self): self.statusBar().showMessage("Ready") def about(self): QMessageBox.about( self, "About " + QCoreApplication.applicationName(), "EbookCreator\nVersion: " + QCoreApplication.applicationVersion() + "\n(C) Copyright 2020 CrowdWare. All rights reserved.\n\nThis program is provided AS IS with NO\nWARRANTY OF ANY KIND, INCLUDING THE\nWARRANTY OF DESIGN, MERCHANTABILITY AND\nFITNESS FOR A PATICULAR PURPOSE." ) def newFile(self): dlg = ProjectWizard(self.install_directory, parent=self) dlg.loadBook.connect(self.loadBook) dlg.show() def open(self): fileName = "" dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) dialog.setNameFilter("EbookCreator (book.qml);;All (*)") dialog.setWindowTitle("Load Ebook") dialog.setOption(QFileDialog.DontUseNativeDialog, True) dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.setDirectory(os.path.join(self.install_directory, "sources")) if dialog.exec_(): fileName = dialog.selectedFiles()[0] del dialog if not fileName: return self.loadBook(fileName) def writeSettings(self): settings = QSettings(QSettings.IniFormat, QSettings.UserScope, QCoreApplication.organizationName(), QCoreApplication.applicationName()) settings.setValue("geometry", self.saveGeometry()) settings.setValue("lastBook", self.last_book) def readSettings(self): settings = QSettings(QSettings.IniFormat, QSettings.UserScope, QCoreApplication.organizationName(), QCoreApplication.applicationName()) geometry = settings.value("geometry", QByteArray()) self.last_book = settings.value("lastBook") if not geometry: availableGeometry = QApplication.desktop().availableGeometry(self) self.resize(availableGeometry.width() / 3, availableGeometry.height() / 2) self.move((availableGeometry.width() - self.width()) / 2, (availableGeometry.height() - self.height()) / 2) else: self.restoreGeometry(geometry) def bold(self): if not self.filename: QMessageBox.warning( self, QCoreApplication.applicationName(), "You have to select part from the book content first!") return cursor = self.text_edit.textCursor() pos = cursor.position() if not cursor.hasSelection(): cursor.select(QTextCursor.WordUnderCursor) cursor.insertText("**" + cursor.selectedText() + "**") cursor.setPosition(pos + 2) self.text_edit.setTextCursor(cursor) def italic(self): if not self.filename: QMessageBox.warning( self, QCoreApplication.applicationName(), "You have to select part from the book content first!") return cursor = self.text_edit.textCursor() pos = cursor.position() if not cursor.hasSelection(): cursor.select(QTextCursor.WordUnderCursor) cursor.insertText("*" + cursor.selectedText() + "*") cursor.setPosition(pos + 1) self.text_edit.setTextCursor(cursor) def create(self): filename = "" dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) dialog.setNameFilter("ePub3 (*.epub);;All (*)") dialog.setWindowTitle("Create Ebook") dialog.setOption(QFileDialog.DontUseNativeDialog, True) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setDirectory(self.book.source_path) dialog.setDefaultSuffix("epub") if dialog.exec_(): filename = dialog.selectedFiles()[0] del dialog if not filename: return QApplication.setOverrideCursor(Qt.WaitCursor) createEpub(filename, self.book, self) QApplication.restoreOverrideCursor() def loadStatusChanged(self, status): if status == 1: self.book = self.component.create() if self.book is not None: self.book.setFilename(self.last_book) self.book.setWindow(self) else: for error in self.component.errors(): print(error.toString()) return self.content_list.clear() for part in self.book.parts: item = QListWidgetItem() item.setText(part.name) item.setData(1, part) self.content_list.addItem(item) self.loadImages() self.setWindowTitle(QCoreApplication.applicationName() + " - " + self.book.name) self.content.setExpanded(True) self.content_list.setCurrentRow(0) elif status == 3: for error in self.component.errors(): print(error.toString()) return def loadBook(self, filename): self.last_book = filename self.filename = "" engine = QQmlEngine() self.component = QQmlComponent(engine) self.component.statusChanged.connect(self.loadStatusChanged) self.component.loadUrl(QUrl.fromLocalFile(filename)) def settingsDialog(self): dlg = SettingsDialog(self.theme, self.palette().highlight().color().name(), parent=self) dlg.exec() if dlg.theme != self.theme or dlg.hilite_color != self.palette( ).highlight().color().name(): settings = QSettings(QSettings.IniFormat, QSettings.UserScope, QCoreApplication.organizationName(), QCoreApplication.applicationName()) settings.setValue("theme", dlg.theme) settings.setValue("hiliteColor", dlg.hilite_color) msgBox = QMessageBox() msgBox.setText("Please restart the app to change the theme!") msgBox.exec() def textChanged(self): text = self.text_edit.toPlainText() if self.filename: with open(self.filename, "w") as f: f.write(text) self.lock = Lock() with self.lock: if not self.tread_running: self.tread_running = True self.htmlReady.connect(self.previewReady) thread = Thread(target=self.createHtml, args=(text, )) thread.daemon = True thread.start() def previewReady(self, html): self.preview.setHtml( html, baseUrl=QUrl( Path(os.path.join(self.book.source_path, "parts", "index.html")).as_uri())) self.htmlReady.disconnect() with self.lock: self.tread_running = False def createHtml(self, text): html = '<html>\n<head>\n' html += '<link href="../css/pastie.css" rel="stylesheet" type="text/css"/>\n' html += '<link href="../css/stylesheet.css" rel="stylesheet" type="text/css"/>\n' html += '</head>\n<body>\n' html += markdown(text, html4tags=False, extras=[ "fenced-code-blocks", "wiki-tables", "tables", "header-ids" ]) html += '\n</body>\n</html>' html = addLineNumbers(html) self.htmlReady.emit(html) def pdfExport(self): p = PdfExport(self.book, self.statusBar()) def spellCheck(self): if not self.filename: QMessageBox.warning( self, QCoreApplication.applicationName(), "You have to select part from the book content first!") return cursor = self.text_edit.textCursor() pos = cursor.position() if not cursor.hasSelection(): cursor.select(QTextCursor.WordUnderCursor) spell = Speller(lang='en') changed = spell(cursor.selectedText()) if changed != cursor.selectedText(): cursor.insertText(changed) self.text_edit.setTextCursor(cursor) def loadPlugins(self): # check if we are running in a frozen environment (pyinstaller --onefile) if getattr(sys, "frozen", False): bundle_dir = sys._MEIPASS # if we are running in a onefile environment, then copy all plugin to /tmp/... if bundle_dir != os.getcwd(): os.mkdir(os.path.join(bundle_dir, "plugins")) for root, dirs, files in os.walk( os.path.join(os.getcwd(), "plugins")): for file in files: shutil.copy(os.path.join(root, file), os.path.join(bundle_dir, "plugins")) print("copy", file) break # do not copy __pycache__ else: bundle_dir = os.getcwd() plugins_dir = os.path.join(bundle_dir, "plugins") for root, dirs, files in os.walk(plugins_dir): for file in files: modulename, ext = os.path.splitext(file) if ext == ".py": module = import_module("plugins." + modulename) for name, klass in inspect.getmembers( module, inspect.isclass): if klass.__module__ == "plugins." + modulename: instance = klass() if isinstance(instance, GeneratorInterface): Plugins.addGeneratorPlugin(name, instance) instance.setTextEdit(self.text_edit) #instance.registerContenType() break # not to list __pycache__
def __init__(self): QMainWindow.__init__(self) self.setWindowTitle("Qt Expander Demo") self.resize(640, 480) edit = QTextEdit() edit.setPlainText("Lorem ipsum dolor...") self.content = Expander("Content", "parts.svg") self.images = Expander("Images", "images.svg") self.settings = Expander("Settings", "settings.svg") vbox = QVBoxLayout() vbox.addWidget(self.content) vbox.addWidget(self.images) vbox.addWidget(self.settings) vbox.addStretch() scroll_content = QWidget() scroll_content.setLayout(vbox) scroll = QScrollArea() scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) scroll.setWidget(scroll_content) scroll.setWidgetResizable(True) scroll.setMaximumWidth(200) scroll.setMinimumWidth(200) self.navigationdock = QDockWidget("Navigation", self) self.navigationdock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.navigationdock.setWidget(scroll) self.navigationdock.setObjectName("Navigation") self.addDockWidget(Qt.LeftDockWidgetArea, self.navigationdock) self.setCentralWidget(edit) # fill content self.content_list = QListWidget() self.content_list.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) for i in range(5): item = QListWidgetItem() item.setText("Item " + str(i)) self.content_list.addItem(item) content_box = QVBoxLayout() content_box.addWidget(self.content_list) self.content.addLayout(content_box) # fill images self.images_list = QListWidget() self.images_list.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) for i in range(5): item = QListWidgetItem() item.setText("Image " + str(i)) self.images_list.addItem(item) images_box = QVBoxLayout() images_box.addWidget(self.images_list) self.images.addLayout(images_box) #fill settings self.settings_list = QListWidget() self.settings_list.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) for i in range(5): item = QListWidgetItem() item.setText("Setting " + str(i)) self.settings_list.addItem(item) settings_box = QVBoxLayout() settings_box.addWidget(self.settings_list) self.settings.addLayout(settings_box) self.content.expanded.connect(self.contentExpanded) self.images.expanded.connect(self.imagesExpanded) self.settings.expanded.connect(self.settingsExpanded)
def __init__(self, id, parent): Widget.__init__(self, id, parent) self.widgets.expander = Expander() self.widgets.surface_table = FitTable() self.widgets.signal_table = FitTable()
def setUp(self): self.extractor = LineExtractor("") self.message = StatusMessage(self.extractor) self.expander = Expander(Executor(), self.message)
class TestSubtituter(unittest.TestCase): def setUp(self): self.extractor = LineExtractor("") self.message = StatusMessage(self.extractor) self.expander = Expander(Executor(), self.message) def testMakeSubtitutionList(self): if IGNORE_TEST: return substitution_list = Expander.makeSubstitutionList(DEFINITIONS) expected = np.prod([len(v) for v in DEFINITIONS.values()]) self.assertEqual(len(substitution_list), expected) substitution_list = Expander.makeSubstitutionList({}) self.assertEqual(len(substitution_list), 0) definitions = dict(DEFINITIONS) key = list(DEFINITIONS.keys())[0] del definitions[key] substitution_list = Expander.makeSubstitutionList(definitions) expected = np.prod([len(v) for v in definitions.values()]) self.assertEqual(len(substitution_list), expected) def testGetTemplateExpressions(self): if IGNORE_TEST: return expression1 = "a + b" expression2 = "x" expression3 = "cos(a) + sin(b)" proto_template = "xy%s%s%sz + yz%s%s%sx" for expr in [expression1, expression2, expression3]: template = proto_template % ( EXPRESSION_START, expr, EXPRESSION_END, EXPRESSION_START, expr, EXPRESSION_END) result = self.expander.getTemplateExpressions(template) self.assertEqual(len(result), 1) self.assertEqual(result[0], expr) def _testGetTemplateExpression(self, line, expecteds): if IGNORE_TEST: return expressions = self.expander.getTemplateExpressions(line) self.assertEqual(set(expressions), set(expecteds)) def testGetTemplateExpressions2(self): if IGNORE_TEST: return self._testGetTemplateExpression("x{a} -> x + {a}; k*{a}", ["a"]) self._testGetTemplateExpression("x{a} -> x + {b}; k*{a}", ["a", "b"]) self._testGetTemplateExpression("x{a} -> x + { b }; k*{a}", ["a", "b"]) self._testGetTemplateExpression("T{n} + A -> A + T{n+1}", ["n", "n+1"]) self._testGetTemplateExpression("T{n} + A -> A + T{n+1} + T{2*n + n }", ["n", "n+1", "2*n + n"]) def testDo(self): if IGNORE_TEST: return executor = Executor() executor.setDefinitions(DEFINITIONS) expander = Expander(executor, self.message) result = expander.do(SUBSTITUTION1) self.assertEqual(result[0], SUBSTITUTION1) result = expander.do(SUBSTITUTION2) expected = len(DEFINITIONS['a']) self.assertEqual(len(result), expected) def testDoSubstitutionNoDefinition(self): if IGNORE_TEST: return executor = Executor() expander = Expander(executor, self.message) result = expander.do(SUBSTITUTION1) self.assertEqual(result[0], SUBSTITUTION1) def testExpandTemplateExpressions(self): if IGNORE_TEST: return executor = Executor() var = 'n' definitions = {var: [1, 2, 3]} executor.setDefinitions(definitions) expander = Expander(executor, self.message) template = "T{%s} + A -> T{%s+1}" % (var, var) expansion = expander.do(template) self.assertEqual(len(expansion), len(definitions[var])) # Check that each substitution is found for value in definitions[var]: found = False for substitution in expansion: if "T%d" % value in substitution: found = True break self.assertTrue(found)
def createUi(self): self.content = Expander("Content", ":/images/parts.svg") self.images = Expander("Images", ":/images/images.svg") self.settings = Expander("Settings", ":/images/settings.svg") self.setWindowTitle(QCoreApplication.applicationName() + " " + QCoreApplication.applicationVersion()) vbox = QVBoxLayout() vbox.addWidget(self.content) vbox.addWidget(self.images) vbox.addWidget(self.settings) vbox.addStretch() self.content_list = QListWidget() self.content_list.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) content_box = QVBoxLayout() content_box.addWidget(self.content_list) self.item_edit = QLineEdit() self.item_edit.setMaximumHeight(0) self.item_edit.editingFinished.connect(self.editItemFinished) self.item_anim = QPropertyAnimation(self.item_edit, "maximumHeight".encode("utf-8")) content_box.addWidget(self.item_edit) button_layout = QHBoxLayout() plus_button = FlatButton(":/images/plus.svg") self.edit_button = FlatButton(":/images/edit.svg") self.trash_button = FlatButton(":/images/trash.svg") self.up_button = FlatButton(":/images/up.svg") self.down_button = FlatButton(":/images/down.svg") self.trash_button.enabled = False self.up_button.enabled = False self.down_button.enabled = False button_layout.addWidget(plus_button) button_layout.addWidget(self.up_button) button_layout.addWidget(self.down_button) button_layout.addWidget(self.edit_button) button_layout.addWidget(self.trash_button) content_box.addLayout(button_layout) self.content.addLayout(content_box) plus_button.clicked.connect(self.addPart) self.trash_button.clicked.connect(self.dropPart) self.up_button.clicked.connect(self.partUp) self.down_button.clicked.connect(self.partDown) self.edit_button.clicked.connect(self.editPart) self.image_list = QListWidget() self.image_list.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) image_box = QVBoxLayout() image_box.addWidget(self.image_list) image_button_layout = QHBoxLayout() image_plus_button = FlatButton(":/images/plus.svg") self.image_trash_button = FlatButton(":/images/trash.svg") self.image_trash_button.enabled = False image_button_layout.addWidget(image_plus_button) image_button_layout.addWidget(self.image_trash_button) image_box.addLayout(image_button_layout) self.images.addLayout(image_box) image_plus_button.clicked.connect(self.addImage) self.image_trash_button.clicked.connect(self.dropImage) scroll_content = QWidget() scroll_content.setLayout(vbox) scroll = QScrollArea() scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) scroll.setWidget(scroll_content) scroll.setWidgetResizable(True) scroll.setMaximumWidth(200) scroll.setMinimumWidth(200) self.navigationdock = QDockWidget("Navigation", self) self.navigationdock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.navigationdock.setWidget(scroll) self.navigationdock.setObjectName("Navigation") self.addDockWidget(Qt.LeftDockWidgetArea, self.navigationdock) self.splitter = QSplitter() self.text_edit = MarkdownEdit() self.text_edit.setFont(QFont("Courier", 15)) # 11 on Linux self.preview = QWebEngineView() self.preview.setMinimumWidth(300) self.setWindowTitle(QCoreApplication.applicationName()) self.splitter.addWidget(self.text_edit) self.splitter.addWidget(self.preview) self.setCentralWidget(self.splitter) self.content.expanded.connect(self.contentExpanded) self.images.expanded.connect(self.imagesExpanded) self.settings.expanded.connect(self.settingsExpanded) self.settings.clicked.connect(self.openSettings) self.content_list.currentItemChanged.connect(self.partSelectionChanged) self.image_list.currentItemChanged.connect(self.imageSelectionChanged) self.image_list.itemDoubleClicked.connect(self.insertImage) self.text_edit.undoAvailable.connect(self.undoAvailable) self.text_edit.redoAvailable.connect(self.redoAvailable) self.text_edit.copyAvailable.connect(self.copyAvailable) QApplication.clipboard().dataChanged.connect(self.clipboardDataChanged)
def create_model(): m = pe.ConcreteModel() m.fs = fs = FlowsheetBlock(default={"dynamic": False}) fs.vapor_props = vapor_props = PhysicalParameterBlock( default={"valid_phase": 'Vap'}) fs.properties = props = PhysicalParameterBlock( default={"valid_phase": ('Vap', 'Liq')}) fs.reaction_params = MethanolReactionParameterBlock( default={'property_package': vapor_props}) fs.feed = feed = Feed(default={"property_package": vapor_props}) fs.compressor1 = IdealGasIsentropicCompressor( default={ "property_package": vapor_props, "has_phase_equilibrium": False }) fs.cooler1 = Heater(default={ "property_package": vapor_props, "has_phase_equilibrium": False }) fs.compressor2 = IdealGasIsentropicCompressor( default={ "property_package": vapor_props, "has_phase_equilibrium": False }) fs.equal_electric = pe.Constraint( expr=fs.compressor1.work[0.0] == fs.compressor2.work[0.0]) fs.mixer = Mixer( default={ 'property_package': vapor_props, 'inlet_list': ['feed', 'recycle'], 'momentum_mixing_type': MomentumMixingType.equality }) # Reactor fs.reactor = StoichiometricReactor( default={ 'property_package': vapor_props, 'reaction_package': fs.reaction_params, 'has_heat_of_reaction': True, 'has_pressure_change': False }) fs.reactor.conversion_eq = pe.Var() fs.reactor.t_inv = pe.Var() fs.reactor.p_sq_inv = pe.Var() fs.reactor.conversion = pe.Var() fs.reactor.consumption_rate = pe.Var() fs.reactor.t_inv_con = pe.Constraint(expr=fs.reactor.t_inv * fs.reactor.outlet.temperature[0] == 1) fs.reactor.p_sq_inv_con = pe.Constraint( expr=fs.reactor.p_sq_inv * fs.reactor.inlet.pressure[0]**2 == 1) fs.reactor.conversion_eq_con = pe.Constraint(expr=( fs.reactor.conversion_eq == 0.415 * (1 - 26.25 * pe.exp(-18 * fs.reactor.t_inv) * fs.reactor.p_sq_inv))) fs.reactor.conversion_con = pe.Constraint( expr=(fs.reactor.conversion == fs.reactor.conversion_eq * (1 - pe.exp(-5)) * (fs.reactor.inlet.mole_frac[0, "H2"] + fs.reactor.inlet.mole_frac[0, "CO"] + fs.reactor.inlet.mole_frac[0, "CH3OH"]))) fs.reactor.consumption_rate_con = pe.Constraint( expr=(fs.reactor.consumption_rate == fs.reactor.conversion * fs.reactor.inlet.mole_frac[0, "H2"] * fs.reactor.inlet.flow_mol[0])) fs.reactor.h2_consumption_con = pe.Constraint(expr=( fs.reactor.outlet.flow_mol[0] * fs.reactor.outlet.mole_frac[0, "H2"] == fs.reactor.inlet.flow_mol[0] * fs.reactor.inlet.mole_frac[0, "H2"] - fs.reactor.consumption_rate)) fs.expander = Expander(default={ 'property_package': vapor_props, 'has_phase_equilibrium': False }) fs.cooler2 = Heater(default={ "property_package": vapor_props, "has_phase_equilibrium": False }) fs.flash = Flash(default={"property_package": props}) fs.purge_splitter = Separator( default={ 'property_package': vapor_props, 'outlet_list': ['purge', 'recycle'], 'ideal_separation': False }) fs.compressor3 = IdealGasIsentropicCompressor( default={ "property_package": vapor_props, "has_phase_equilibrium": False }) ########################### # Set scaling factors ########################### fs.compressor1.control_volume.scaling_factor_energy.value = 1 fs.compressor2.control_volume.scaling_factor_energy.value = 1 fs.cooler1.control_volume.scaling_factor_energy.value = 1 fs.flash.control_volume.scaling_factor_energy.value = 1 fs.reactor.control_volume.scaling_factor_energy.value = 1 fs.cooler2.control_volume.scaling_factor_energy.value = 1 fs.compressor3.control_volume.scaling_factor_energy.value = 1 fs.mixer.scaling_factor_energy.value = 1 fs.cooler1.control_volume.scaling_factor_pressure.value = 1 fs.flash.control_volume.scaling_factor_pressure.value = 1 fs.reactor.control_volume.scaling_factor_pressure.value = 1 fs.cooler2.control_volume.scaling_factor_pressure.value = 1 ########################### # Objective ########################### m.objective = pe.Objective(expr=(-fs.flash.liq_outlet.flow_mol[0.0])) ########################### # Connect Units ########################### fs.stream1 = network.Arc(source=feed.outlet, destination=fs.compressor1.inlet) fs.stream2 = network.Arc(source=fs.compressor1.outlet, destination=fs.cooler1.inlet) fs.stream3 = network.Arc(source=fs.cooler1.outlet, destination=fs.compressor2.inlet) fs.stream4 = network.Arc(source=fs.compressor2.outlet, destination=fs.mixer.feed) fs.stream5 = network.Arc(source=fs.mixer.outlet, destination=fs.reactor.inlet) fs.stream6 = network.Arc(source=fs.reactor.outlet, destination=fs.expander.inlet) fs.stream7 = network.Arc(source=fs.expander.outlet, destination=fs.cooler2.inlet) fs.stream8 = network.Arc(source=fs.cooler2.outlet, destination=fs.flash.inlet) fs.stream9 = network.Arc(source=fs.flash.vap_outlet, destination=fs.purge_splitter.inlet) fs.stream10 = network.Arc(source=fs.purge_splitter.recycle, destination=fs.compressor3.inlet) fs.stream11 = network.Arc(source=fs.compressor3.outlet, destination=fs.mixer.recycle) pe.TransformationFactory("network.expand_arcs").apply_to(m) ########################### # Set problem specs ########################### feed.flow_mol.fix(3.40898) feed.pressure.fix(1) feed.temperature.fix(3) feed.mole_frac[0.0, "CH4"].fix(0.05) feed.mole_frac[0.0, "CO"].fix(0.3) feed.mole_frac[0.0, "H2"].fix(0.6) feed.mole_frac[0.0, "CH3OH"].fix(0.05) fs.cooler1.heat_duty[0.0].setub(0) # it is a cooler fs.cooler1.outlet.temperature[0.0].setlb(3) fs.flash.heat_duty.fix(0) fs.flash.deltaP.fix(0) fs.cooler2.heat_duty[0.0].setub(0) # it is a cooler fs.cooler2.outlet.temperature[0.0].setlb(3) fs.compressor2.outlet.pressure[0.0].setub(10) fs.flash.liq_outlet.mole_frac[0.0, 'CH3OH'].expr.setlb(0.9) fs.purge_splitter.split_fraction[0.0, 'purge'].fix(0.05) ########################### # Prepare for initialization ########################### fs.compressor1.outlet.pressure.fix(5) fs.compressor2.outlet.pressure.fix(10) fs.cooler1.outlet.temperature.fix(3) fs.expander.outlet.pressure[0.0].fix(5) fs.cooler2.outlet.temperature[0.0].fix(3) fs.flash.liq_outlet.mole_frac[0.0, 'CH3OH'].expr.setlb(None) # Setup decomposition process seq = network.SequentialDecomposition() seq.options.select_tear_method = "heuristic" seq.options.tear_method = "Wegstein" seq.options.iterLim = 5 # Determine tear stream and calculation order G = seq.create_graph(m) heu_result = seq.tear_set_arcs(G, method="heuristic") order = seq.calculation_order(G) # Display tear stream and calculation order print("Tear") for o in heu_result: print(o.name) print("Order") for o in order: for oo in o: print(oo.name) # Set guesses for tear stream tear_guesses = { "flow_mol": { 0: 10 }, "mole_frac": { (0, 'CH3OH'): 0.06, (0, 'CH4'): 0.21, (0, 'CO'): 0.24, (0, 'H2'): 0.50 }, "temperature": { 0: 4.4 }, "pressure": { 0: 15 } } seq.set_guesses_for(m.fs.reactor.inlet, tear_guesses) # Define method for initialising each block def function(unit): unit.initialize(outlvl=1) # Run sequential initialisation seq.run(m, function) ########################### # Unfix vars that were fixed for initialization ########################### m.fs.compressor1.outlet.pressure.unfix() m.fs.compressor2.outlet.pressure.unfix() m.fs.cooler1.outlet.temperature.unfix() m.fs.expander.outlet.pressure.unfix() m.fs.cooler2.outlet.temperature.unfix() m.fs.flash.liq_outlet.mole_frac[0.0, 'CH3OH'].expr.setlb(0.9) return m