def _test_newfile(browser):
    # Creates a file in the GUI.
    projects_page, project_info_page, project_dict, workspace_page = startup(browser)

    # Open code editor.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()

    # test the 'ok' and 'cancel' buttons on the new file dialog
    dlg = editor_page.new_file_dialog()
    dlg.set_text("ok_file1")
    dlg.click_ok()
    NotifierPage.wait(editor_page)

    dlg = editor_page.new_file_dialog()
    dlg.set_text("cancel_file")
    dlg.click_cancel()

    dlg = editor_page.new_file_dialog()
    dlg.set_text("ok_file2")
    dlg.click_ok()
    NotifierPage.wait(editor_page)

    file_names = editor_page.get_files()
    expected_file_names = ["ok_file1", "ok_file2"]
    if sorted(file_names) != sorted(expected_file_names):
        raise TestCase.failureException(
            "Expected file names, '%s', should match existing file names, '%s'" % (expected_file_names, file_names)
        )

    # Create the file (code editor automatically indents).
    editor_page.new_file(
        "plane.py",
        """
from openmdao.main.api import Component
from openmdao.lib.datatypes.api import Float

# lines will be auto-indented by ace editor
class Plane(Component):

x1 = Float(0.0, iotype='in')
x2 = Float(0.0, iotype='in')
x3 = Float(0.0, iotype='in')

f_x = Float(0.0, iotype='out')
""",
    )

    # Back to workspace.
    browser.close()
    browser.switch_to_window(workspace_window)

    # Drag over Plane.
    workspace_page.show_dataflow("top")
    workspace_page.set_library_filter("In Project")
    workspace_page.add_library_item_to_dataflow("plane.Plane", "plane")

    # Clean up.
    closeout(projects_page, project_info_page, project_dict, workspace_page)
def _test_console_errors(browser):
    #projects_page, project_info_page, project_dict, workspace_page = startup(browser)
    project_dict, workspace_page = startup(browser)

    # Set input to illegal value.
    top = workspace_page.get_dataflow_figure('driver', 'top')
    editor = top.editor_page(double_click=False, base_type='Driver')
    inputs = editor.get_inputs()
    inputs.rows[2].cells[1].click()
    inputs[2][2] = '42'  # printvars
    message = NotifierPage.wait(editor)
    eq(
        message, "TraitError: The 'printvars' trait of a "
        "Run_Once instance must be a list of items "
        "which are a legal value, but a value of 42 "
        "<type 'int'> was specified.")
    editor.close()

    # Attempt to save file with syntax error.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()
    editor_page.new_file('bug.py',
                         """
from openmdao.main.api import Component
class Bug(Component):
def execute(self)
    pass
""",
                         check=False)

    message = NotifierPage.wait(editor_page, base_id='file-error')
    browser.close()
    browser.switch_to_window(workspace_window)
    eq(message, 'invalid syntax (bug.py, line 6)\n    def execute(self)')

    # Load file with instantiation error.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()
    editor_page.new_file(
        'bug2.py', """
from openmdao.main.api import Component
class Bug2(Component):
def __init__(self):
raise RuntimeError("__init__ failed")
""")
    browser.close()
    browser.switch_to_window(workspace_window)
    workspace_page.add_library_item_to_dataflow('bug2.Bug2',
                                                'bug',
                                                check=False)
    message = NotifierPage.wait(workspace_page)
    eq(
        message,
        "NameError: unable to create object of type 'bug2.Bug2': __init__ failed"
    )

    # Clean up.
    #closeout(projects_page, project_info_page, project_dict, workspace_page)
    closeout(project_dict, workspace_page)
def _test_newfile(browser):
    # Creates a file in the GUI.
    projects_page, project_info_page, project_dict, workspace_page = startup(
        browser)

    # Open code editor.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()

    # test the 'ok' and 'cancel' buttons on the new file dialog
    dlg = editor_page.new_file_dialog()
    dlg.set_text('ok_file1')
    dlg.click_ok()
    NotifierPage.wait(editor_page)

    dlg = editor_page.new_file_dialog()
    dlg.set_text('cancel_file')
    dlg.click_cancel()

    dlg = editor_page.new_file_dialog()
    dlg.set_text('ok_file2')
    dlg.click_ok()
    NotifierPage.wait(editor_page)

    file_names = editor_page.get_files()
    expected_file_names = ['ok_file1', 'ok_file2']
    if sorted(file_names) != sorted(expected_file_names):
        raise TestCase.failureException(
            "Expected file names, '%s', should match existing file names, '%s'"
            % (expected_file_names, file_names))

    # Create the file (code editor automatically indents).
    editor_page.new_file(
        'plane.py', """
from openmdao.main.api import Component
from openmdao.lib.datatypes.api import Float

# lines will be auto-indented by ace editor
class Plane(Component):

x1 = Float(0.0, iotype='in')
x2 = Float(0.0, iotype='in')
x3 = Float(0.0, iotype='in')

f_x = Float(0.0, iotype='out')
""")

    # Back to workspace.
    browser.close()
    browser.switch_to_window(workspace_window)

    # Drag over Plane.
    workspace_page.show_dataflow('top')
    workspace_page.set_library_filter('In Project')
    workspace_page.add_library_item_to_dataflow('plane.Plane', 'plane')

    # Clean up.
    closeout(projects_page, project_info_page, project_dict, workspace_page)
def _test_console_errors(browser):
    projects_page, project_info_page, project_dict, workspace_page = startup(browser)

    # Set input to illegal value.
    top = workspace_page.get_dataflow_figure("driver", "top")
    editor = top.editor_page(double_click=False, base_type="Driver")
    inputs = editor.get_inputs()
    inputs[2][2] = "42"  # printvars
    message = NotifierPage.wait(editor)
    eq(
        message,
        "TraitError: The 'printvars' trait of a "
        "Run_Once instance must be a list of items "
        "which are a legal value, but a value of 42 "
        "<type 'int'> was specified.",
    )
    editor.close()

    # Attempt to save file with syntax error.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()
    editor_page.new_file(
        "bug.py",
        """
from openmdao.main.api import Component
class Bug(Component):
def execute(self)
    pass
""",
        check=False,
    )

    message = NotifierPage.wait(editor_page, base_id="file-error")
    eq(message, "invalid syntax (bug.py, line 6)")

    browser.close()
    browser.switch_to_window(workspace_window)

    # Load file with instantiation error.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()
    editor_page.new_file(
        "bug2.py",
        """
from openmdao.main.api import Component
class Bug2(Component):
def __init__(self):
raise RuntimeError("__init__ failed")
""",
    )
    browser.close()
    browser.switch_to_window(workspace_window)
    workspace_page.add_library_item_to_dataflow("bug2.Bug2", "bug", check=False)
    message = NotifierPage.wait(workspace_page)
    eq(message, "NameError: unable to create object of type 'bug2.Bug2': __init__ failed")

    # Clean up.
    closeout(projects_page, project_info_page, project_dict, workspace_page)
示例#5
0
def _test_slot_subclass(browser):
    # test that a slot will accept subclasses
    project_dict, workspace_page = startup(browser)

    file_path = pkg_resources.resource_filename('openmdao.gui.test.functional',
                                                'files/slot_test.py')
    workspace_page.add_file(file_path)

    name = workspace_page.put_element_on_grid("AutoAssemb")
    aa = workspace_page.get_dataflow_figure(name)
    editor = aa.editor_page(double_click=False)
    editor.move(-200, 200)

    inputs = editor.get_inputs()
    expected = [
        ['', 'input',              '0', '', ''],
        ['', 'directory',           '', '', 'If non-blank, the directory to execute in.'],
        ['', 'force_execute',  'False', '', 'If True, always execute even if all IO traits are valid.'],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])

    inputs[0][2] = "10"
    aa.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')

    outputs = editor.get_outputs()
    expected = [
        ['', 'output',                '80', '', ''],
        ['', 'derivative_exec_count',  '0', '', "Number of times this Component's derivative function has been executed."],
        ['', 'exec_count',             '1', '', 'Number of times this Component has been executed.'],
        ['', 'itername',                '', '', 'Iteration coordinates.'],
    ]
    for i, row in enumerate(outputs.value):
        eq(row, expected[i])

    editor.show_slots()
    recorders_slot = find_slot_figure(workspace_page, 'd2', prefix=name)
    workspace_page.fill_slot_from_library(recorders_slot, 'Dummy2')

    aa.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')

    outputs = editor.get_outputs()
    expected = [
        ['', 'output',                 '160', '', ''],
        ['', 'derivative_exec_count',    '0', '', "Number of times this Component's derivative function has been executed."],
        ['', 'exec_count',               '2', '', 'Number of times this Component has been executed.'],
        ['', 'itername',                  '', '', 'Iteration coordinates.'],
    ]
    for i, row in enumerate(outputs.value):
        eq(row, expected[i])

    # Clean up.
    closeout(project_dict, workspace_page)
示例#6
0
def _test_array_parameter(browser):
    # Test adding an array parameter.
    project_dict, workspace_page = startup(browser)

    file_path = pkg_resources.resource_filename('openmdao.gui.test.functional',
                                                'files/array_parameters.py')
    workspace_page.add_file(file_path)
    workspace_page.add_library_item_to_dataflow(
        'array_parameters.ArrayParameters', 'top')
    # Add parameter to driver.
    driver = workspace_page.get_dataflow_figure('driver', 'top')
    editor = driver.editor_page(base_type='Driver')
    editor('parameters_tab').click()
    dialog = editor.new_parameter()
    dialog.target = 'paraboloid.x'
    dialog.low = '-50'
    dialog.high = '[40, 50]'
    dialog.scaler = '[[1., 1]]'
    dialog('ok').click()

    parameters = editor.get_parameters()
    expected = [[
        '', 'paraboloid.x', '-50', '40,50', '1,1', '0', '', 'paraboloid.x'
    ]]
    eq(len(parameters.value), len(expected))
    for i, row in enumerate(parameters.value):
        eq(row, expected[i])

    editor.close()
    time.sleep(1)

    # Run optimization.
    top = workspace_page.get_dataflow_figure('top')
    top.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')

    # Check results.
    workspace_page.do_command("top.paraboloid.x[0][0]")
    x00 = workspace_page.history.split("\n")[-1]
    workspace_page.do_command("top.paraboloid.x[0][1]")
    x01 = workspace_page.history.split("\n")[-1]

    if abs(float(x00) - 6.6667) > 0.01:
        raise TestCase.failureException(
            "Parameter x[0][0] did not reach correct value, but instead is %s"
            % x00)

    if abs(float(x01) - -7.3333) > 0.01:
        raise TestCase.failureException(
            "Parameter x[0][1] did not reach correct value, but instead is %s"
            % x01)

    closeout(project_dict, workspace_page)
def _test_array_parameter(browser):
    # Test adding an array parameter.
    project_dict, workspace_page = startup(browser)

    file_path = pkg_resources.resource_filename('openmdao.gui.test.functional',
                                                'files/array_parameters.py')
    workspace_page.add_file(file_path)
    workspace_page.add_library_item_to_dataflow('array_parameters.ArrayParameters',
                                                'top')
    # Add parameter to driver.
    driver = workspace_page.get_dataflow_figure('driver', 'top')
    editor = driver.editor_page(base_type='Driver')
    editor('parameters_tab').click()
    dialog = editor.new_parameter()
    dialog.target = 'paraboloid.x'
    dialog.low = '-50'
    dialog.high = '[40, 50]'
    dialog.scaler = '[[1., 1]]'
    dialog('ok').click()

    parameters = editor.get_parameters()
    expected = [['', 'paraboloid.x', '-50', '40,50', '1,1', '0', '', 'paraboloid.x']]
    eq(len(parameters.value), len(expected))
    for i, row in enumerate(parameters.value):
        eq(row, expected[i])

    editor.close()
    time.sleep(1)

    # Run optimization.
    top = workspace_page.get_dataflow_figure('top')
    top.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')

    # Check results.
    workspace_page.do_command("top.paraboloid.x[0][0]")
    x00 = workspace_page.history.split("\n")[-1]
    workspace_page.do_command("top.paraboloid.x[0][1]")
    x01 = workspace_page.history.split("\n")[-1]

    if abs(float(x00) - 6.6667) > 0.01:
        raise TestCase.failureException(
            "Parameter x[0][0] did not reach correct value, but instead is %s"
            % x00)

    if abs(float(x01) - -7.3333) > 0.01:
        raise TestCase.failureException(
            "Parameter x[0][1] did not reach correct value, but instead is %s"
            % x01)

    closeout(project_dict, workspace_page)
def _test_basic(browser):
    project_dict, workspace_page = startup(browser)

    filename = pkg_resources.resource_filename('openmdao.gui.test.functional',
                                               'files/rosen_suzuki.py')
    workspace_page.add_file(filename)

    # Add a NestedSimulation.
    workspace_page.add_library_item_to_dataflow('rosen_suzuki.NestedSimulation',
                                                'nested', offset=(300, 300))
    # Verify full workflow shown.
    workspace_page('workflow_tab').click()
    eq(len(workspace_page.get_workflow_figures()), 2)
    eq(len(workspace_page.get_workflow_component_figures()), 5)

    # Verify flow layout is horizontal and can be switched to vertical
    sim = workspace_page.get_workflow_figure('sim.driver')
    assert sim.horizontal
    sim.flip()
    assert not sim.horizontal

    # Verify workflow can be collapsed and expanded
    sim.collapse()
    assert sim.collapsed
    sim.expand()
    assert sim.expanded

    # Verify that component state is represented properly
    driver = workspace_page.get_workflow_component_figure('sim.driver')
    assert driver.state == 'INVALID'
    driver.run()
    time.sleep(2.0)
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')
    assert driver.state == 'VALID'

    # Verify workflow can be cleared
    nested = workspace_page.get_workflow_figure('nested.driver')
    nested.clear()
    eq(len(workspace_page.get_workflow_component_figures()), 1)

    # Clean up.
    closeout(project_dict, workspace_page)
示例#9
0
def _test_basic(browser):
    project_dict, workspace_page = startup(browser)

    filename = pkg_resources.resource_filename('openmdao.gui.test.functional',
                                               'files/rosen_suzuki.py')
    workspace_page.add_file(filename)

    # Add a NestedSimulation.
    workspace_page.add_library_item_to_dataflow(
        'rosen_suzuki.NestedSimulation', 'nested', offset=(300, 300))
    # Verify full workflow shown.
    workspace_page('workflow_tab').click()
    eq(len(workspace_page.get_workflow_figures()), 2)
    eq(len(workspace_page.get_workflow_component_figures()), 5)

    # Verify flow layout is horizontal and can be switched to vertical
    sim = workspace_page.get_workflow_figure('sim.driver')
    assert sim.horizontal
    sim.flip()
    assert not sim.horizontal

    # Verify workflow can be collapsed and expanded
    sim.collapse()
    assert sim.collapsed
    sim.expand()
    assert sim.expanded

    # Verify that component state is represented properly
    driver = workspace_page.get_workflow_component_figure('sim.driver')
    assert driver.state == 'INVALID'
    driver.run()
    time.sleep(2.0)
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')
    assert driver.state == 'VALID'

    # Verify workflow can be cleared
    nested = workspace_page.get_workflow_figure('nested.driver')
    nested.clear()
    eq(len(workspace_page.get_workflow_component_figures()), 1)

    # Clean up.
    closeout(project_dict, workspace_page)
示例#10
0
def _test_console_errors(browser):
    project_dict, workspace_page = startup(browser)

    # Set input to illegal value.
    workspace_page.add_library_item_to_dataflow(
        'openmdao.main.assembly.Assembly', 'top')
    top = workspace_page.get_dataflow_figure('driver', 'top')
    editor = top.editor_page(double_click=False, base_type='Driver')
    editor.move(-100, -40)  # Make viewable on small screen.
    inputs = editor.get_inputs()
    inputs.rows[0].cells[2].click()
    inputs[0][2] = '42'  # printvars
    expected = "TraitError: The 'printvars' trait of a "     \
               "Run_Once instance must be a list of items "  \
               "which are a legal value, but a value of 42 " \
               "<type 'int'> was specified."
    time.sleep(0.5)
    eq(workspace_page.history, expected)
    editor.close()

    # Attempt to save file with syntax error.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()
    editor_page.new_file('bug.py',
                         """
from openmdao.main.api import Component
class Bug(Component):
def execute(self)
    pass
""",
                         check=False)

    # We expect 2 notifiers: save successful and file error.
    # These will likely overlap in a manner that 'Ok' is found but
    # later is hidden by the second notifier.
    try:
        message = NotifierPage.wait(editor_page, base_id='file-error')
    except WebDriverException as exc:
        err = str(exc)
        if 'Element is not clickable' in err:
            NotifierPage.wait(editor_page)
            message = NotifierPage.wait(editor_page)
    else:
        NotifierPage.wait(editor_page)
    eq(message, 'Error in file bug.py: invalid syntax (bug.py, line 6)')

    browser.close()
    browser.switch_to_window(workspace_window)

    # Load file with instantiation error.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()
    editor_page.new_file(
        'bug2.py', """
from openmdao.main.api import Component
class Bug2(Component):
def __init__(self):
raise RuntimeError("__init__ failed")
""")
    browser.close()
    browser.switch_to_window(workspace_window)

    workspace_page.add_library_item_to_dataflow('bug2.Bug2',
                                                'bug',
                                                check=False)
    expected = "NameError: unable to create object of type 'bug2.Bug2': __init__ failed"
    assert workspace_page.history.endswith(expected)

    # Clean up.
    closeout(project_dict, workspace_page)
def _test_console_errors(browser):
    project_dict, workspace_page = startup(browser)

    # Set input to illegal value.
    workspace_page.add_library_item_to_dataflow('openmdao.main.assembly.Assembly', 'top')
    top = workspace_page.get_dataflow_figure('driver', 'top')
    editor = top.editor_page(double_click=False, base_type='Driver')
    editor.move(-100, -40)  # Make viewable on small screen.
    inputs = editor.get_inputs()
    inputs.rows[4].cells[2].click()
    inputs[4][2] = '42'  # printvars
    expected = "TraitError: The 'printvars' trait of a "     \
               "Run_Once instance must be a list of items "  \
               "which are a legal value, but a value of 42 " \
               "<type 'int'> was specified."
    time.sleep(0.5)
    assert workspace_page.history.endswith(expected)
    editor.close()

    # Attempt to save file with syntax error.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()
    editor_page.new_file('bug.py', """
from openmdao.main.api import Component
class Bug(Component):
def execute(self)
    pass
""", check=False)

    # We expect 2 notifiers: save successful and file error.
    # These will likely overlap in a manner that 'Ok' is found but
    # later is hidden by the second notifier.
    try:
        message = NotifierPage.wait(editor_page, base_id='file-error')
    except WebDriverException as exc:
        err = str(exc)
        if 'Element is not clickable' in err:
            NotifierPage.wait(editor_page)
            message = NotifierPage.wait(editor_page)
    else:
        NotifierPage.wait(editor_page)
    eq(message, 'Error in file bug.py: invalid syntax (bug.py, line 6)')

    browser.close()
    browser.switch_to_window(workspace_window)

    # Load file with instantiation error.
    workspace_window = browser.current_window_handle
    if broken_chrome():
        raise SkipTest('Test broken for chrome/selenium combination')
    editor_page = workspace_page.open_editor()
    editor_page.new_file('bug2.py', """
from openmdao.main.api import Component
class Bug2(Component):
def __init__(self):
raise RuntimeError("__init__ failed")
""")
    browser.close()
    browser.switch_to_window(workspace_window)

    workspace_page.add_library_item_to_dataflow('bug2.Bug2', 'bug', check=False)
    expected = "NameError: unable to create object of type 'bug2.Bug2': __init__ failed"
    assert workspace_page.history.endswith(expected)

    # Clean up.
    closeout(project_dict, workspace_page)
def _test_macro(browser):
    project_dict, workspace_page = startup(browser)

    # Open code editor.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()

    # Create a file (code editor automatically indents).
    editor_page.new_file('foo.py', """
from openmdao.main.api import Component
from openmdao.main.datatypes.api import Float

class Foo(Component):

a = Float(0.0, iotype='in')
b = Float(0.0, iotype='out')
""")
    # Back to workspace.
    browser.close()
    browser.switch_to_window(workspace_window)

    # Add some Foo instances.
    workspace_page.add_library_item_to_dataflow('openmdao.main.assembly.Assembly', 'top')
    workspace_page.show_dataflow('top')
    time.sleep(2)  # Wait for it to get registered.
    workspace_page.set_library_filter('In Project')
    workspace_page.add_library_item_to_dataflow('foo.Foo', 'comp1')
    workspace_page.add_library_item_to_dataflow('foo.Foo', 'comp2')

    comp1 = workspace_page.get_dataflow_figure('comp1', 'top')
    comp2 = workspace_page.get_dataflow_figure('comp2', 'top')
    conn_page = workspace_page.connect(comp1, comp2)
    conn_page.connect_vars('comp1.b', 'comp2.a')
    conn_page.close()

    workspace_page.commit_project('added some Foos')

    if broken_chrome():
        raise SkipTest('Test broken for chrome/selenium combination')
    editor_page = workspace_page.open_editor()
    editor_page.edit_file('foo.py', dclick=False)
    editor_page.add_text_to_file('#just a comment\n')

    # forces a save and reload of project
    editor_page.save_document(overwrite=True, check=False)
    browser.switch_to_window(workspace_window)
    port = workspace_page.port
    workspace_page = WorkspacePage.verify(browser, port)

    workspace_page.show_dataflow('top')
    time.sleep(0.5)
    eq(sorted(workspace_page.get_dataflow_component_names()),
       ['comp1', 'comp2', 'driver', 'top'])

    # Check if running a component is recorded (it shouldn't be).
    top = workspace_page.get_dataflow_figure('top')
    top.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')
    history = workspace_page.history.split('\n')
    eq(history[-2], 'Executing...')
    eq(history[-1], 'Execution complete.')

    workspace_page.toggle_files('foo.py')
    workspace_page.expand_folder('_macros')
    editor = workspace_page.edit_file('_macros/default')
    contents = editor.get_code()
    browser.close()
    browser.switch_to_window(workspace_window)
    for line in contents.split('\n'):
        if 'run' in line:
            raise AssertionError(line)

    # Check if command errors are recorded (they shouldn't be).
    workspace_page.do_command('print xyzzy', ack=False)
    NotifierPage.wait(workspace_page, base_id='command')
    expected = "NameError: name 'xyzzy' is not defined"
    assert workspace_page.history.endswith(expected)

    editor = workspace_page.edit_file('_macros/default')
    contents = editor.get_code()
    browser.close()
    browser.switch_to_window(workspace_window)
    for line in contents.split('\n'):
        if 'xyzzy' in line:
            raise AssertionError(line)

    # Clean up.
    closeout(project_dict, workspace_page)
示例#13
0
def _test_connect(browser):
    project_dict, workspace_page = startup(browser)

    # Import connect.py
    file_path = pkg_resources.resource_filename('openmdao.gui.test.functional',
                                                'files/connect.py')
    workspace_page.add_file(file_path)
    workspace_page.add_library_item_to_dataflow('connect.Topp', 'top')

    # Connect components.
    workspace_page.show_dataflow('top')
    comp1 = workspace_page.get_dataflow_figure('comp1', 'top')
    comp2 = workspace_page.get_dataflow_figure('comp2', 'top')
    conn_page = workspace_page.connect(comp1, comp2)
    conn_page.move(-100, -100)
    eq(conn_page.dialog_title, 'Connections: top')
    eq(conn_page.source_component, 'comp1')
    eq(conn_page.target_component, 'comp2')
    for prefix in ('b', 'e', 'f', 'i', 's'):
        conn_page.connect_vars('comp1.' + prefix + '_out',
                               'comp2.' + prefix + '_in')
        time.sleep(0.5)  # Wait for display update.
    conn_page.close()

    # Set inputs (re-fetch required after updating).
    comp1 = workspace_page.get_dataflow_figure('comp1', 'top')
    props = comp1.properties_page()
    props.move(0, -120)  # Move up for short displays.
    time.sleep(0.5)      # Wait for header update.
    eq(props.header, 'Connectable: top.comp1')
    props.move(-100, -100)
    inputs = props.inputs
    eq(inputs[4].value, ['s_in', ''])
    inputs[4][1] = 'xyzzy'
    inputs = props.inputs
    eq(inputs[2].value, ['f_in', '0'])
    inputs[2][1] = '2.781828'
    inputs = props.inputs
    eq(inputs[3].value, ['i_in', '0'])
    inputs[3][1] = '42'

    inputs = props.inputs
    eq(inputs[0].value, ['b_in', 'False'])
    inputs.rows[0].cells[1].click()
    browser.find_element_by_xpath('//*[@id="bool-editor-b_in"]/option[1]').click()
    #inputs.rows[0].cells[0].click()
    #inputs[0][1] = 'True'

    inputs = props.inputs
    eq(inputs[1].value, ['e_in', '1'])
    inputs.rows[1].cells[1].click()
    browser.find_element_by_xpath('//*[@id="editor-enum-e_in"]/option[3]').click()
    #inputs.rows[2].cells[0].click()
    #inputs[2][1] = '3'

    props.close()

    # Run the simulation.
    top = workspace_page.get_dataflow_figure('top')
    top.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')

    # Verify outputs.
    comp2 = workspace_page.get_dataflow_figure('comp2', 'top')
    editor = comp2.editor_page()
    editor.move(-100, 0)
    eq(editor.dialog_title, 'Connectable: top.comp2')
    outputs = editor.get_outputs()
    expected = [
        ['', 'b_out', 'True', '', ''],
        ['', 'e_out', '3', '', ''],
        ['', 'f_out', '2.781828', '', ''],
        ['', 'i_out', '42', '', ''],
        ['', 's_out', 'xyzzy', '', ''],
        ['', 'derivative_exec_count', '0', '',
         "Number of times this Component's derivative function has been executed."],
        ['', 'exec_count', '1', '',
         'Number of times this Component has been executed.'],
        ['', 'itername', '1-2', '', 'Iteration coordinates.'],
    ]
    for i, row in enumerate(outputs.value):
        eq(row, expected[i])
    editor.close()

    # Clean up.
    closeout(project_dict, workspace_page)
示例#14
0
def _test_connections(browser):
    # Check connection frame functionality.
    project_dict, workspace_page = startup(browser)

    filename = pkg_resources.resource_filename('openmdao.examples.enginedesign',
                                               'vehicle_singlesim.py')
    workspace_page.add_file(filename)

    asm_name = 'sim'
    workspace_page.add_library_item_to_dataflow('vehicle_singlesim.VehicleSim',
                                                asm_name)
    # show dataflow for vehicle
    workspace_page.expand_object('sim')
    workspace_page.show_dataflow('sim.vehicle')
    workspace_page.hide_left()
    vehicle = workspace_page.get_dataflow_figure('vehicle', 'sim')

    # no connections between assembly vars
    conn_page = vehicle.connections_page()
    conn_page.move(-50, -100)
    eq(conn_page.dialog_title, 'Connections: vehicle')
    eq(conn_page.source_component, '-- Assembly --')
    eq(conn_page.target_component, '-- Assembly --')
    eq(conn_page.count_variable_connections(), 0)

    # two connections between engine and chassis
    conn_page.set_source_component('engine')
    conn_page.set_target_component('chassis')
    eq(conn_page.count_variable_figures(), 20)
    eq(conn_page.count_variable_connections(), 2)
    conn_page.show_connected_variables()
    time.sleep(0.5)
    eq(conn_page.count_variable_figures(), 4)
    eq(conn_page.count_variable_connections(), 2)
    eq(sorted(conn_page.get_variable_names()),
       ['engine_torque', 'engine_weight', 'mass_engine', 'torque'])

    # one connection between transmission and engine (RPM)
    conn_page.set_source_component('transmission')
    conn_page.set_target_component('engine')
    eq(conn_page.count_variable_figures(), 2)
    eq(conn_page.count_variable_connections(), 1)
    eq(sorted(conn_page.get_variable_names()),
       ['RPM', 'RPM'])

    # disconnect transmission
    conn_page.close()  # Sometimes obscures dataflow.
    tranny = workspace_page.get_dataflow_figure('transmission', 'sim.vehicle')
    tranny.disconnect()
    vehicle = workspace_page.get_dataflow_figure('vehicle', 'sim')
    conn_page = vehicle.connections_page()
    conn_page.move(-50, -100)
    conn_page.show_connected_variables()

    # now there are no connections between transmission and engine
    conn_page.set_source_component('transmission')
    conn_page.set_target_component('engine')
    time.sleep(0.5)
    eq(conn_page.count_variable_figures(), 0)
    eq(conn_page.count_variable_connections(), 0)

    # reconnect transmission RPM to engine RPM
    conn_page.connect_vars('transmission.RPM', 'engine.RPM')
    time.sleep(1)
    eq(conn_page.count_variable_figures(), 2)
    eq(conn_page.count_variable_connections(), 1)
    eq(sorted(conn_page.get_variable_names()),
       ['RPM', 'RPM'])

    # no connections between transmission and chassis
    conn_page.set_target_component('chassis')
    time.sleep(0.5)
    eq(conn_page.count_variable_figures(), 0)
    eq(conn_page.count_variable_connections(), 0)

    # reconnect transmission torque to chassis torque by dragging
    # conn_page.connect_vars('transmission.torque_ratio', 'chassis.torque_ratio')
    conn_page.show_all_variables()
    time.sleep(0.5)
    torque_vars = conn_page.find_variable_name('torque_ratio')
    eq(len(torque_vars), 2)
    chain = ActionChains(browser)
    chain.click_and_hold(torque_vars[0])
    chain.move_to_element(torque_vars[1])
    chain.release(on_element=None).perform()
    time.sleep(1.0)
    eq(conn_page.count_variable_connections(), 1)
    conn_page.show_connected_variables()
    time.sleep(0.5)
    eq(conn_page.count_variable_figures(), 2)
    eq(sorted(conn_page.get_variable_names()),
       ['torque_ratio', 'torque_ratio'])

    # no connections between vehicle assembly and transmission
    conn_page.set_source_component('')
    conn_page.set_target_component('transmission')
    time.sleep(0.5)
    eq(conn_page.count_variable_figures(), 0)
    eq(conn_page.count_variable_connections(), 0)

    # connect assembly variable to component variable
    conn_page.connect_vars('current_gear', 'transmission.current_gear')
    eq(conn_page.count_variable_figures(), 2)
    eq(conn_page.count_variable_connections(), 1)
    eq(sorted(conn_page.get_variable_names()),
       ['current_gear', 'current_gear'])

    # one connection from chassis component to vehicle assembly
    conn_page.set_source_component('chassis')
    conn_page.set_target_component('')
    eq(conn_page.count_variable_figures(), 2)
    eq(conn_page.count_variable_connections(), 1)
    eq(sorted(conn_page.get_variable_names()),
       ['acceleration', 'acceleration'])

    conn_page.close()

    # disconnect chassis
    chassis = workspace_page.get_dataflow_figure('chassis', 'sim.vehicle')
    chassis.disconnect()
    vehicle = workspace_page.get_dataflow_figure('vehicle', 'sim')

    conn_page = vehicle.connections_page()
    conn_page.move(-50, -100)

    eq(conn_page.count_variable_connections(), 0)

    # test invalid variable
    conn_page.connect_vars('chassis.acceleration', 'acceleration')
    message = NotifierPage.wait(workspace_page)
    eq(message, "Invalid source variable")

    # connect component variable to assembly variable
    conn_page.set_source_component('chassis')
    conn_page.connect_vars('chassis.acceleration', 'acceleration')
    eq(conn_page.count_variable_connections(), 1)
    conn_page.show_connected_variables()
    eq(sorted(conn_page.get_variable_names()),
       ['acceleration', 'acceleration'])

    conn_page.close()

    # Clean up.
    closeout(project_dict, workspace_page)
def _test_connect(browser):
    project_dict, workspace_page = startup(browser)

    # Import connect.py
    file_path = pkg_resources.resource_filename("openmdao.gui.test.functional", "files/connect.py")
    workspace_page.add_file(file_path)
    workspace_page.add_library_item_to_dataflow("connect.Topp", "top")

    # Connect components.
    workspace_page.show_dataflow("top")
    comp1 = workspace_page.get_dataflow_figure("comp1", "top")
    comp2 = workspace_page.get_dataflow_figure("comp2", "top")
    conn_page = workspace_page.connect(comp1, comp2)
    conn_page.move(-100, -100)
    eq(conn_page.dialog_title, "Connections: top")
    eq(conn_page.source_component, "comp1")
    eq(conn_page.target_component, "comp2")
    for prefix in ("b", "e", "f", "i", "s"):
        conn_page.connect_vars("comp1." + prefix + "_out", "comp2." + prefix + "_in")
        time.sleep(0.5)  # Wait for display update.
    conn_page.close()

    # Set inputs (re-fetch required after updating).
    comp1 = workspace_page.get_dataflow_figure("comp1", "top")
    props = comp1.properties_page()
    props.move(0, -120)  # Move up for short displays.
    time.sleep(0.5)  # Wait for header update.
    eq(props.header, "Connectable: top.comp1")
    props.move(-100, -100)
    inputs = props.inputs
    eq(inputs[4].value, ["s_in", ""])
    inputs[4][1] = "xyzzy"
    inputs = props.inputs
    eq(inputs[2].value, ["f_in", "0"])
    inputs[2][1] = "2.781828"
    inputs = props.inputs
    eq(inputs[3].value, ["i_in", "0"])
    inputs[3][1] = "42"

    inputs = props.inputs
    eq(inputs[0].value, ["b_in", "False"])
    inputs.rows[0].cells[1].click()
    browser.find_element_by_xpath('//*[@id="bool-editor-b_in"]/option[1]').click()
    # inputs.rows[0].cells[0].click()
    # inputs[0][1] = 'True'

    inputs = props.inputs
    eq(inputs[1].value, ["e_in", "1"])
    inputs.rows[1].cells[1].click()
    browser.find_element_by_xpath('//*[@id="editor-enum-e_in"]/option[3]').click()
    # inputs.rows[2].cells[0].click()
    # inputs[2][1] = '3'

    props.close()

    # Run the simulation.
    top = workspace_page.get_dataflow_figure("top")
    top.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, "Run complete: success")

    # Verify outputs.
    comp2 = workspace_page.get_dataflow_figure("comp2", "top")
    editor = comp2.editor_page()
    editor.move(-100, 0)
    eq(editor.dialog_title, "Connectable: top.comp2")
    outputs = editor.get_outputs()
    expected = [
        ["", "b_out", "True", "", ""],
        ["", "e_out", "3", "", ""],
        ["", "f_out", "2.781828", "", ""],
        ["", "i_out", "42", "", ""],
        ["", "s_out", "xyzzy", "", ""],
        [
            "",
            "derivative_exec_count",
            "0",
            "",
            "Number of times this Component's derivative function has been executed.",
        ],
        ["", "exec_count", "1", "", "Number of times this Component has been executed."],
        ["", "itername", "1-2", "", "Iteration coordinates."],
    ]
    for i, row in enumerate(outputs.value):
        eq(row, expected[i])
    editor.close()

    # Clean up.
    closeout(project_dict, workspace_page)
示例#16
0
def _test_macro(browser):
    project_dict, workspace_page = startup(browser)

    # Open code editor.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()

    # Create a file (code editor automatically indents).
    editor_page.new_file('foo.py', """
from openmdao.main.api import Component
from openmdao.lib.datatypes.api import Float

class Foo(Component):

a = Float(0.0, iotype='in')
b = Float(0.0, iotype='out')
""")
    # Back to workspace.
    browser.close()
    browser.switch_to_window(workspace_window)

    # Add some Foo instances.
    workspace_page.show_dataflow('top')
    time.sleep(1)  # Wait for it to get registered.
    workspace_page.set_library_filter('In Project')
    workspace_page.add_library_item_to_dataflow('foo.Foo', 'comp1')
    workspace_page.add_library_item_to_dataflow('foo.Foo', 'comp2')

    comp1 = workspace_page.get_dataflow_figure('comp1', 'top')
    comp2 = workspace_page.get_dataflow_figure('comp2', 'top')
    conn_page = workspace_page.connect(comp1, comp2)
    conn_page.connect_vars('comp1.b', 'comp2.a')
    conn_page.close()

    workspace_page.commit_project('added some Foos')

    editor_page = workspace_page.open_editor()
    editor_page.edit_file('foo.py', dclick=False)
    editor_page.add_text_to_file('#just a comment\n')

    # forces a save and reload of project
    editor_page.save_document(overwrite=True, check=False)
    browser.switch_to_window(workspace_window)
    port = workspace_page.port
    workspace_page = WorkspacePage.verify(browser, port)

    workspace_page.show_dataflow('top')
    time.sleep(0.5)
    eq(sorted(workspace_page.get_dataflow_component_names()),
       ['comp1', 'comp2', 'driver', 'top'])

    # Check if running a component is recorded (it shouldn't be).
    top = workspace_page.get_dataflow_figure('top')
    top.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')
    history = workspace_page.history.split('\n')
    eq(history[-2], 'Executing...')
    eq(history[-1], 'Execution complete.')

    workspace_page.toggle_files('foo.py')
    workspace_page.expand_folder('_macros')
    editor = workspace_page.edit_file('_macros/default')
    contents = editor.get_code()
    browser.close()
    browser.switch_to_window(workspace_window)
    for line in contents.split('\n'):
        if 'run' in line:
            raise AssertionError(line)

    # Check if command errors are recorded (they shouldn't be).
    workspace_page.do_command('print xyzzy', ack=False)
    # We expect 2 notifiers: command complete and error.
    # These will likely overlap in a manner that 'Ok' is found but
    # later is hidden by the second notifier.
    try:  # We expect 2 notifiers: command complete and error.
        NotifierPage.wait(workspace_page, base_id='command')
    except WebDriverException as exc:
        err = str(exc)
        if 'Element is not clickable' in err:
            err = NotifierPage.wait(workspace_page)
            NotifierPage.wait(workspace_page, base_id='command')
    else:
        err = NotifierPage.wait(workspace_page)
    if err != "NameError: name 'xyzzy' is not defined":
        raise AssertionError('Unexpected message: %r' % err)

    editor = workspace_page.edit_file('_macros/default')
    contents = editor.get_code()
    browser.close()
    browser.switch_to_window(workspace_window)
    for line in contents.split('\n'):
        if 'xyzzy' in line:
            raise AssertionError(line)

    # Clean up.
    #closeout(projects_page, project_info_page, project_dict, workspace_page)
    closeout(project_dict, workspace_page)
示例#17
0
def _test_replace(browser):
    # Replaces various connected components.
    project_dict, workspace_page = startup(browser)

    filename = pkg_resources.resource_filename('openmdao.gui.test.functional',
                                               'files/rosen_suzuki.py')
    workspace_page.add_file(filename)

    # Replace 'top' with Simulation.
    top = workspace_page.get_dataflow_figure('top')
    top.remove()
    workspace_page.add_library_item_to_dataflow('rosen_suzuki.Simulation',
                                                'top')

    # Show dataflow for Simulation.
    workspace_page.show_dataflow('top')
    workspace_page.hide_left()

    # Verify preproc is a PreProc.
    preproc = workspace_page.get_dataflow_figure('preproc', 'top')
    editor = preproc.editor_page()
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    expected = [
        [
            'directory', 'str', '', '', 'true',
            'If non-blank, the directory to execute in.', '', ''
        ],
        [
            'force_execute', 'bool', 'False', '', 'true',
            'If True, always execute even if all IO traits are valid.', '', ''
        ],
        ['x_in', 'ndarray', '[ 1. 1. 1. 1.]', '', 'true', '', '', ''],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])
    editor.close()

    # Replace preproc with a ScalingPreProc.
    workspace_page.replace('preproc', 'rosen_suzuki.ScalingPreProc')
    preproc = workspace_page.get_dataflow_figure('preproc', 'top')
    editor = preproc.editor_page()
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    expected = [
        [
            'directory', 'str', '', '', 'true',
            'If non-blank, the directory to execute in.', '', ''
        ],
        [
            'force_execute', 'bool', 'False', '', 'true',
            'If True, always execute even if all IO traits are valid.', '', ''
        ],
        ['scaler', 'float', '1', '', 'true', '', '', ''],
        ['x_in', 'ndarray', '[ 1. 1. 1. 1.]', '', 'true', '', '', ''],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])
    editor.close()

    # Verify postproc is a PostProc.
    postproc = workspace_page.get_dataflow_figure('postproc', 'top')
    editor = postproc.editor_page()
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    expected = [
        [
            'directory', 'str', '', '', 'true',
            'If non-blank, the directory to execute in.', '', ''
        ],
        [
            'force_execute', 'bool', 'False', '', 'true',
            'If True, always execute even if all IO traits are valid.', '', ''
        ],
        [
            'result_in', 'float', '0', '', 'false', '',
            "['parent.comp.result']", ''
        ],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])
    editor.close()

    # Replace postproc with a ScalingPostProc.
    workspace_page.replace('postproc', 'rosen_suzuki.ScalingPostProc')
    postproc = workspace_page.get_dataflow_figure('postproc', 'top')
    editor = postproc.editor_page()
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    expected = [
        [
            'directory', 'str', '', '', 'true',
            'If non-blank, the directory to execute in.', '', ''
        ],
        [
            'force_execute', 'bool', 'False', '', 'true',
            'If True, always execute even if all IO traits are valid.', '', ''
        ],
        [
            'result_in', 'float', '0', '', 'false', '',
            "['parent.comp.result']", ''
        ],
        ['scaler', 'float', '1', '', 'true', '', '', ''],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])
    editor.close()

    # Verify driver is a CONMINdriver.
    driver = workspace_page.get_dataflow_figure('driver', 'top')
    editor = driver.editor_page(base_type='Driver')
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    eq(inputs.value[0], [
        'cons_is_linear', 'ndarray', '[]', '', 'true',
        'Array designating whether each constraint is linear.', '', ''
    ])
    editor.close()

    # Replace driver with an SLSQPdriver.
    workspace_page.replace('driver',
                           'openmdao.lib.drivers.slsqpdriver.SLSQPdriver')
    driver = workspace_page.get_dataflow_figure('driver', 'top')
    editor = driver.editor_page(base_type='Driver')
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    eq(inputs.value[0], [
        'accuracy', 'float', '0.000001', '', 'true', 'Convergence accuracy',
        '', ''
    ])
    editor.close()

    # Verify comp is a OptRosenSuzukiComponent.
    comp = workspace_page.get_dataflow_figure('comp', 'top')
    editor = comp.editor_page()
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    expected = [
        [
            'directory', 'str', '', '', 'true',
            'If non-blank, the directory to execute in.', '', ''
        ],
        [
            'force_execute', 'bool', 'False', '', 'true',
            'If True, always execute even if all IO traits are valid.', '', ''
        ],
        [
            'x', 'ndarray', '[]', '', 'false', '', "['parent.preproc.x_out']",
            "['driver']"
        ],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])
    editor.close()

    # Replace comp with an Assembly.
    workspace_page.replace('comp', 'openmdao.main.assembly.Assembly')
    args_page = ArgsPrompt(workspace_page.browser, workspace_page.port)
    args_page.click_ok()
    message = NotifierPage.wait(workspace_page)
    eq(
        message, "RuntimeError: top: Can't connect 'comp.result' to"
        " 'postproc.result_in': top: Can't find 'comp.result'")
    comp = workspace_page.get_dataflow_figure('comp', 'top')
    editor = comp.editor_page()
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    expected = [
        [
            'directory', 'str', '', '', 'true',
            'If non-blank, the directory to execute in.', '', ''
        ],
        [
            'force_execute', 'bool', 'False', '', 'true',
            'If True, always execute even if all IO traits are valid.', '', ''
        ],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])
    editor.close()

    # Verify new figure.
    comp = workspace_page.get_dataflow_figure('comp', 'top')
    background = comp('top_right').value_of_css_property('background')
    assert background.find('circle-plus.png') >= 0

    # Clean up.
    closeout(project_dict, workspace_page)
示例#18
0
def _test_slot_subclass(browser):
    # test that a slot will accept subclasses
    project_dict, workspace_page = startup(browser)

    file_path = pkg_resources.resource_filename('openmdao.gui.test.functional',
                                                'files/slot_test.py')
    workspace_page.add_file(file_path)

    name = workspace_page.put_element_on_grid("AutoAssemb")
    aa = workspace_page.get_dataflow_figure(name)
    editor = aa.editor_page(double_click=False)
    editor.move(-200, 200)

    inputs = editor.get_inputs()
    expected = [
        ['', 'input', '0', '', ''],
        [
            '', 'directory', '', '',
            'If non-blank, the directory to execute in.'
        ],
        [
            '', 'force_execute', 'False', '',
            'If True, always execute even if all IO traits are valid.'
        ],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])

    inputs[0][2] = "10"
    aa.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')

    outputs = editor.get_outputs()
    expected = [
        ['', 'output', '80', '', ''],
        [
            '', 'derivative_exec_count', '0', '',
            "Number of times this Component's derivative function has been executed."
        ],
        [
            '', 'exec_count', '1', '',
            'Number of times this Component has been executed.'
        ],
        ['', 'itername', '', '', 'Iteration coordinates.'],
    ]
    for i, row in enumerate(outputs.value):
        eq(row, expected[i])

    editor.show_slots()
    recorders_slot = find_slot_figure(workspace_page, 'd2', prefix=name)
    workspace_page.fill_slot_from_library(recorders_slot, 'Dummy2')

    aa.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')

    outputs = editor.get_outputs()
    expected = [
        ['', 'output', '160', '', ''],
        [
            '', 'derivative_exec_count', '0', '',
            "Number of times this Component's derivative function has been executed."
        ],
        [
            '', 'exec_count', '2', '',
            'Number of times this Component has been executed.'
        ],
        ['', 'itername', '', '', 'Iteration coordinates.'],
    ]
    for i, row in enumerate(outputs.value):
        eq(row, expected[i])

    # Clean up.
    closeout(project_dict, workspace_page)
def _test_connect(browser):
    project_dict, workspace_page = startup(browser)

    # Import connect.py
    file_path = pkg_resources.resource_filename('openmdao.gui.test.functional',
                                                'files/connect.py')
    workspace_page.add_file(file_path)
    workspace_page.add_library_item_to_dataflow('connect.Topp', 'top')

    # Connect components.
    workspace_page.show_dataflow('top')
    comp1 = workspace_page.get_dataflow_figure('comp1', 'top')
    comp2 = workspace_page.get_dataflow_figure('comp2', 'top')
    conn_page = workspace_page.connect(comp1, comp2)
    time.sleep(0.5)
    conn_page.move(-100, -100)
    eq(conn_page.dialog_title, 'Connections: top')
    eq(conn_page.source_component, 'comp1')
    eq(conn_page.target_component, 'comp2')
    for prefix in ('b', 'e', 'f', 'i', 's', 'w'):
        conn_page.connect_vars('comp1.' + prefix + '_out',
                               'comp2.' + prefix + '_in')
        time.sleep(0.5)  # Wait for display update.

    conn_page.set_source_expression('comp1.f_out+comp1.i_out')
    conn_page.target_variable = 'comp2.x_in'
    conn_page.connect()

    time.sleep(0.5)  # Wait for display update.

    eq(conn_page.count_variable_figures(), 21)
    eq(conn_page.count_variable_connections(), 9)  # 3 connections for the expr

    conn_page.close()

    # Set inputs (re-fetch required after updating).
    comp1 = workspace_page.get_dataflow_figure('comp1', 'top')
    props = comp1.properties_page()
    props.move(0, -120)  # Move up for short displays.
    time.sleep(0.5)  # Wait for header update.
    eq(props.header, 'Connectable: top.comp1')
    props.move(-100, -100)
    inputs = props.inputs
    eq(inputs[4].value, ['s_in', ''])
    inputs[4][1] = 'xyzzy'
    inputs = props.inputs
    eq(inputs[2].value, ['f_in', '0'])
    inputs[2][1] = '2.781828'
    inputs = props.inputs
    eq(inputs[3].value, ['i_in', '0'])
    inputs[3][1] = '42'

    inputs = props.inputs
    eq(inputs[0].value, ['b_in', 'False'])
    inputs.rows[0].cells[1].click()
    browser.find_element_by_xpath(
        '//*[@id="bool-editor-b_in"]/option[1]').click()
    # inputs.rows[0].cells[0].click()
    # inputs[0][1] = 'True'

    inputs = props.inputs
    eq(inputs[1].value, ['e_in', '1'])
    inputs.rows[1].cells[1].click()
    browser.find_element_by_xpath(
        '//*[@id="editor-enum-e_in"]/option[3]').click()
    # inputs.rows[2].cells[0].click()
    # inputs[2][1] = '3'

    props.close()

    # Run the simulation.
    top = workspace_page.get_dataflow_figure('top')
    top.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')

    # Verify outputs.
    comp2 = workspace_page.get_dataflow_figure('comp2', 'top')
    editor = comp2.editor_page()
    editor.move(-100, 0)
    eq(editor.dialog_title, 'Connectable: top.comp2')

    inputs = editor.get_inputs()
    for i, row in enumerate(inputs.value):
        if row[1] == 'w_in':
            eq(row[2], '5000')

    outputs = editor.get_outputs()
    expected = [
        ['', 'b_out', 'True', '', ''],
        ['', 'e_out', '3', '', ''],
        ['', 'f_out', '2.781828', '', ''],
        ['', 'i_out', '42', '', ''],
        ['', 's_out', 'xyzzy', '', ''],
        ['', 'w_out', '5', 'kg', ''],
        ['', 'x_out', '44.781828', '', ''],
        [
            '', 'derivative_exec_count', '0', '',
            "Number of times this Component's derivative function has been executed."
        ],
        [
            '', 'exec_count', '1', '',
            'Number of times this Component has been executed.'
        ],
        ['', 'itername', '1-comp2', '', 'Iteration coordinates.'],
    ]
    for i, row in enumerate(outputs.value):
        eq(row, expected[i])

    editor.close()

    # Clean up.
    closeout(project_dict, workspace_page)
def _test_connections(browser):
    # Check connection frame functionality.
    project_dict, workspace_page = startup(browser)

    filename = pkg_resources.resource_filename(
        'openmdao.examples.enginedesign', 'vehicle_singlesim.py')
    workspace_page.add_file(filename)

    asm_name = 'sim'
    workspace_page.add_library_item_to_dataflow('vehicle_singlesim.VehicleSim',
                                                asm_name)
    # show dataflow for vehicle
    workspace_page.expand_object('sim')
    workspace_page.show_dataflow('sim.vehicle')
    workspace_page.hide_left()
    vehicle = workspace_page.get_dataflow_figure('vehicle', 'sim')

    # no connections between assembly vars
    conn_page = vehicle.connections_page()
    conn_page.move(-50, -100)
    eq(conn_page.dialog_title, 'Connections: vehicle')
    eq(conn_page.source_component, '-- Assembly --')
    eq(conn_page.target_component, '-- Assembly --')
    eq(conn_page.count_variable_connections(), 36)

    # two connections between engine and chassis
    conn_page.set_source_component('engine')
    conn_page.set_target_component('chassis')
    eq(conn_page.count_variable_figures(), 21)
    eq(conn_page.count_variable_connections(), 2)
    conn_page.show_connected_variables()
    time.sleep(0.5)
    eq(conn_page.count_variable_figures(), 4)
    eq(conn_page.count_variable_connections(), 2)
    eq(sorted(conn_page.get_variable_names()),
       ['engine_torque', 'engine_weight', 'mass_engine', 'torque'])

    # one connection between transmission and engine (RPM)
    conn_page.set_source_component('transmission')
    conn_page.set_target_component('engine')
    eq(conn_page.count_variable_figures(), 2)
    eq(conn_page.count_variable_connections(), 1)
    eq(sorted(conn_page.get_variable_names()), ['RPM', 'RPM'])

    # disconnect transmission
    conn_page.close()  # Sometimes obscures dataflow.
    tranny = workspace_page.get_dataflow_figure('transmission', 'sim.vehicle')
    tranny.disconnect()
    vehicle = workspace_page.get_dataflow_figure('vehicle', 'sim')
    conn_page = vehicle.connections_page()
    conn_page.move(-50, -100)
    conn_page.show_connected_variables()

    # now there are no connections between transmission and engine
    conn_page.set_source_component('transmission')
    conn_page.set_target_component('engine')
    time.sleep(0.5)
    eq(conn_page.count_variable_figures(), 0)
    eq(conn_page.count_variable_connections(), 0)

    # reconnect transmission RPM to engine RPM
    conn_page.connect_vars('transmission.RPM', 'engine.RPM')
    time.sleep(1)
    eq(conn_page.count_variable_figures(), 2)
    eq(conn_page.count_variable_connections(), 1)
    eq(sorted(conn_page.get_variable_names()), ['RPM', 'RPM'])

    # no connections between transmission and chassis
    conn_page.set_target_component('chassis')
    time.sleep(0.5)
    eq(conn_page.count_variable_figures(), 0)
    eq(conn_page.count_variable_connections(), 0)

    # reconnect transmission torque to chassis torque by dragging
    # conn_page.connect_vars('transmission.torque_ratio', 'chassis.torque_ratio')
    conn_page.show_all_variables()
    time.sleep(0.5)
    torque_vars = conn_page.find_variable_name('torque_ratio')
    eq(len(torque_vars), 2)
    chain = ActionChains(browser)
    chain.click_and_hold(torque_vars[0])
    chain.move_to_element(torque_vars[1])
    chain.release(on_element=None).perform()
    time.sleep(1.0)
    eq(conn_page.count_variable_connections(), 1)
    conn_page.show_connected_variables()
    time.sleep(0.5)
    eq(conn_page.count_variable_figures(), 2)
    eq(sorted(conn_page.get_variable_names()),
       ['torque_ratio', 'torque_ratio'])

    # no connections between vehicle assembly and transmission
    conn_page.set_source_component('')
    conn_page.set_target_component('transmission')
    time.sleep(0.5)
    eq(conn_page.count_variable_figures(), 0)
    eq(conn_page.count_variable_connections(), 0)

    # connect assembly variable to component variable
    conn_page.connect_vars('current_gear', 'transmission.current_gear')
    eq(conn_page.count_variable_figures(), 2)
    eq(conn_page.count_variable_connections(), 1)
    eq(sorted(conn_page.get_variable_names()),
       ['current_gear', 'current_gear'])

    # one connection from chassis component to vehicle assembly
    conn_page.set_source_component('chassis')
    conn_page.set_target_component('')
    eq(conn_page.count_variable_figures(), 2)
    eq(conn_page.count_variable_connections(), 1)
    eq(sorted(conn_page.get_variable_names()),
       ['acceleration', 'acceleration'])

    conn_page.close()

    # disconnect chassis
    chassis = workspace_page.get_dataflow_figure('chassis', 'sim.vehicle')
    chassis.disconnect()
    vehicle = workspace_page.get_dataflow_figure('vehicle', 'sim')

    conn_page = vehicle.connections_page()
    conn_page.move(-50, -100)

    eq(conn_page.count_variable_connections(), 18)

    # test invalid variable
    conn_page.connect_vars('chassis.accel', 'acceleration')
    message = NotifierPage.wait(workspace_page)
    eq(message, "Invalid source variable")

    # connect component variable to assembly variable
    conn_page.set_source_component('chassis')
    conn_page.connect_vars('chassis.acceleration', 'acceleration')
    eq(conn_page.count_variable_connections(), 1)
    conn_page.show_connected_variables()
    eq(sorted(conn_page.get_variable_names()),
       ['acceleration', 'acceleration'])

    conn_page.close()

    # Clean up.
    closeout(project_dict, workspace_page)
def _test_macro(browser):
    project_dict, workspace_page = startup(browser)

    # Open code editor.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()

    # Create a file (code editor automatically indents).
    editor_page.new_file(
        'foo.py', """
from openmdao.main.api import Component
from openmdao.main.datatypes.api import Float

class Foo(Component):

a = Float(0.0, iotype='in')
b = Float(0.0, iotype='out')
""")
    # Back to workspace.
    browser.close()
    browser.switch_to_window(workspace_window)

    # Add some Foo instances.
    workspace_page.add_library_item_to_dataflow(
        'openmdao.main.assembly.Assembly', 'top')
    workspace_page.show_dataflow('top')
    time.sleep(2)  # Wait for it to get registered.
    workspace_page.set_library_filter('In Project')
    workspace_page.add_library_item_to_dataflow('foo.Foo', 'comp1')
    workspace_page.add_library_item_to_dataflow('foo.Foo', 'comp2')

    comp1 = workspace_page.get_dataflow_figure('comp1', 'top')
    comp2 = workspace_page.get_dataflow_figure('comp2', 'top')
    conn_page = workspace_page.connect(comp1, comp2)
    conn_page.connect_vars('comp1.b', 'comp2.a')
    conn_page.close()

    workspace_page.commit_project('added some Foos')

    if broken_chrome():
        raise SkipTest('Test broken for chrome/selenium combination')
    editor_page = workspace_page.open_editor()
    editor_page.edit_file('foo.py', dclick=False)
    editor_page.add_text_to_file('#just a comment\n')

    # forces a save and reload of project
    editor_page.save_document(overwrite=True, check=False)
    browser.switch_to_window(workspace_window)
    port = workspace_page.port
    workspace_page = WorkspacePage.verify(browser, port)

    workspace_page.show_dataflow('top')
    time.sleep(0.5)
    eq(sorted(workspace_page.get_dataflow_component_names()),
       ['comp1', 'comp2', 'driver', 'top'])

    # Check if running a component is recorded (it shouldn't be).
    top = workspace_page.get_dataflow_figure('top')
    top.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')
    history = workspace_page.history.split('\n')
    eq(history[-2], 'Executing...')
    eq(history[-1], 'Execution complete.')

    workspace_page.toggle_files('foo.py')
    workspace_page.expand_folder('_macros')
    editor = workspace_page.edit_file('_macros/default')
    contents = editor.get_code()
    browser.close()
    browser.switch_to_window(workspace_window)
    for line in contents.split('\n'):
        if 'run' in line:
            raise AssertionError(line)

    # Check if command errors are recorded (they shouldn't be).
    workspace_page.do_command('print xyzzy', ack=False)
    NotifierPage.wait(workspace_page, base_id='command')
    expected = "NameError: name 'xyzzy' is not defined"
    assert workspace_page.history.endswith(expected)

    editor = workspace_page.edit_file('_macros/default')
    contents = editor.get_code()
    browser.close()
    browser.switch_to_window(workspace_window)
    for line in contents.split('\n'):
        if 'xyzzy' in line:
            raise AssertionError(line)

    # Clean up.
    closeout(project_dict, workspace_page)
示例#22
0
def _test_macro(browser):
    projects_page, project_info_page, project_dict, workspace_page = startup(
        browser)

    # Open code editor.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()

    # Create a file (code editor automatically indents).
    editor_page.new_file(
        'foo.py', """
from openmdao.main.api import Component
from openmdao.lib.datatypes.api import Float

class Foo(Component):

a = Float(0.0, iotype='in')
b = Float(0.0, iotype='out')
""")
    # Back to workspace.
    browser.close()
    browser.switch_to_window(workspace_window)

    # Add some Foo instances.
    workspace_page.show_dataflow('top')
    workspace_page.set_library_filter('In Project')
    workspace_page.add_library_item_to_dataflow('foo.Foo', 'comp1')
    workspace_page.add_library_item_to_dataflow('foo.Foo', 'comp2')

    comp1 = workspace_page.get_dataflow_figure('comp1', 'top')
    comp2 = workspace_page.get_dataflow_figure('comp2', 'top')
    conn_page = workspace_page.connect(comp1, comp2)
    conn_page.connect_vars('comp1.b', 'comp2.a')
    conn_page.close()

    workspace_page.commit_project('added some Foos')

    editor_page = workspace_page.open_editor()
    editor_page.edit_file('foo.py', dclick=False)
    editor_page.add_text_to_file('#just a comment\n')

    # forces a save and reload of project
    editor_page.save_document(overwrite=True, check=False)
    browser.switch_to_window(workspace_window)
    port = workspace_page.port
    workspace_page = WorkspacePage.verify(browser, port)

    workspace_page.show_dataflow('top')
    time.sleep(0.5)
    eq(sorted(workspace_page.get_dataflow_component_names()),
       ['comp1', 'comp2', 'driver', 'top'])

    # Check if running a component is recorded (it shouldn't be).
    top = workspace_page.get_dataflow_figure('top')
    top.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')
    history = workspace_page.history.split('\n')
    eq(history[-2], 'Executing...')
    eq(history[-1], 'Execution complete.')

    workspace_page.toggle_files('foo.py')
    workspace_page.expand_folder('_macros')
    editor = workspace_page.edit_file('_macros/default')
    contents = editor.get_code()
    browser.close()
    browser.switch_to_window(workspace_window)
    for line in contents.split('\n'):
        if 'run' in line:
            raise AssertionError(line)

    # Check if command errors are recorded (they shouldn't be).
    workspace_page.do_command('print xyzzy', ack=False)
    # We expect 2 notifiers: command complete and error.
    # These will likely overlap in a manner that 'Ok' is found but
    # later is hidden by the second notifier.
    try:  # We expect 2 notifiers: command complete and error.
        msg = NotifierPage.wait(workspace_page, base_id='command')
    except WebDriverException as exc:
        if 'Element is not clickable' in str(exc):
            err = NotifierPage.wait(workspace_page)
            msg = NotifierPage.wait(workspace_page, base_id='command')
    else:
        err = NotifierPage.wait(workspace_page)
    if err != "NameError: name 'xyzzy' is not defined":
        raise AssertionError('Unexpected message: %r' % err)

    editor = workspace_page.edit_file('_macros/default')
    contents = editor.get_code()
    browser.close()
    browser.switch_to_window(workspace_window)
    for line in contents.split('\n'):
        if 'xyzzy' in line:
            raise AssertionError(line)

    # Clean up.
    closeout(projects_page, project_info_page, project_dict, workspace_page)
def _test_macro(browser):
    projects_page, project_info_page, project_dict, workspace_page = startup(browser)

    # Open code editor.
    workspace_window = browser.current_window_handle
    editor_page = workspace_page.open_editor()

    # Create a file (code editor automatically indents).
    editor_page.new_file(
        "foo.py",
        """
from openmdao.main.api import Component
from openmdao.lib.datatypes.api import Float

class Foo(Component):

a = Float(0.0, iotype='in')
b = Float(0.0, iotype='out')
""",
    )
    # Back to workspace.
    browser.close()
    browser.switch_to_window(workspace_window)

    # Add some Foo instances.
    workspace_page.show_dataflow("top")
    workspace_page.set_library_filter("In Project")
    workspace_page.add_library_item_to_dataflow("foo.Foo", "comp1")
    workspace_page.add_library_item_to_dataflow("foo.Foo", "comp2")

    comp1 = workspace_page.get_dataflow_figure("comp1", "top")
    comp2 = workspace_page.get_dataflow_figure("comp2", "top")
    conn_page = workspace_page.connect(comp1, comp2)
    conn_page.connect_vars("comp1.b", "comp2.a")
    conn_page.close()

    workspace_page.commit_project("added some Foos")

    editor_page = workspace_page.open_editor()
    editor_page.edit_file("foo.py", dclick=False)
    editor_page.add_text_to_file("#just a comment\n")

    # forces a save and reload of project
    editor_page.save_document(overwrite=True, check=False)
    browser.switch_to_window(workspace_window)
    port = workspace_page.port
    workspace_page = WorkspacePage.verify(browser, port)

    workspace_page.show_dataflow("top")
    time.sleep(0.5)
    eq(sorted(workspace_page.get_dataflow_component_names()), ["comp1", "comp2", "driver", "top"])

    # Check if running a component is recorded (it shouldn't be).
    top = workspace_page.get_dataflow_figure("top")
    top.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, "Run complete: success")
    history = workspace_page.history.split("\n")
    eq(history[-2], "Executing...")
    eq(history[-1], "Execution complete.")

    workspace_page.toggle_files("foo.py")
    workspace_page.expand_folder("_macros")
    editor = workspace_page.edit_file("_macros/default")
    contents = editor.get_code()
    browser.close()
    browser.switch_to_window(workspace_window)
    for line in contents.split("\n"):
        if "run" in line:
            raise AssertionError(line)

    # Check if command errors are recorded (they shouldn't be).
    workspace_page.do_command("print xyzzy", ack=False)
    # We expect 2 notifiers: command complete and error.
    # These will likely overlap in a manner that 'Ok' is found but
    # later is hidden by the second notifier.
    try:  # We expect 2 notifiers: command complete and error.
        msg = NotifierPage.wait(workspace_page, base_id="command")
    except WebDriverException as exc:
        if "Element is not clickable" in str(exc):
            err = NotifierPage.wait(workspace_page)
            msg = NotifierPage.wait(workspace_page, base_id="command")
    else:
        err = NotifierPage.wait(workspace_page)
    if err != "NameError: name 'xyzzy' is not defined":
        raise AssertionError("Unexpected message: %r" % err)

    editor = workspace_page.edit_file("_macros/default")
    contents = editor.get_code()
    browser.close()
    browser.switch_to_window(workspace_window)
    for line in contents.split("\n"):
        if "xyzzy" in line:
            raise AssertionError(line)

    # Clean up.
    closeout(projects_page, project_info_page, project_dict, workspace_page)
示例#24
0
def _test_slot_subclass(browser):
    # test that a slot will accept subclasses
    project_dict, workspace_page = startup(browser)

    file_path = pkg_resources.resource_filename('openmdao.gui.test.functional',
                                                'files/slot_test.py')
    workspace_page.add_file(file_path)

    name = workspace_page.put_element_on_grid("AutoAssemb")
    aa = workspace_page.get_dataflow_figure(name)
    editor = aa.editor_page(double_click=False)
    editor.move(-200, 200)

    inputs = editor.get_inputs()
    expected = [
        ['', 'input', '0', '', ''],
        [
            '', 'directory', '', '',
            'If non-blank, the directory to execute in.'
        ],
        [
            '', 'excludes', '[]', '',
            'Patterns for variables to exclude from the recorders'
            ' (only valid at top level).'
        ],
        [
            '', 'force_fd', 'False', '',
            'If True, always finite difference this component.'
        ],
        [
            '', 'includes', "['*']", '',
            'Patterns for variables to include in the recorders'
            ' (only valid at top level).'
        ],
        [
            '', 'missing_deriv_policy', 'assume_zero', '',
            'Determines behavior when some analytical derivatives are provided but'
            ' some are missing'
        ],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])

    inputs[0][2] = "10"
    aa.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')

    outputs = editor.get_outputs()
    expected = [
        ['', 'output', '80', '', ''],
        [
            '', 'derivative_exec_count', '0', '',
            "Number of times this Component's derivative function has been executed."
        ],
        [
            '', 'exec_count', '1', '',
            'Number of times this Component has been executed.'
        ],
        ['', 'itername', '', '', 'Iteration coordinates.'],
    ]
    for i, row in enumerate(outputs.value):
        eq(row, expected[i])

    editor.show_slots()
    recorders_slot = find_slot_figure(workspace_page, 'd2', prefix=name)
    workspace_page.fill_slot_from_library(recorders_slot, 'Dummy2')

    aa.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')

    outputs = editor.get_outputs()
    expected = [
        ['', 'output', '160', '', ''],
        [
            '', 'derivative_exec_count', '0', '',
            "Number of times this Component's derivative function has been executed."
        ],
        [
            '', 'exec_count', '2', '',
            'Number of times this Component has been executed.'
        ],
        ['', 'itername', '', '', 'Iteration coordinates.'],
    ]
    for i, row in enumerate(outputs.value):
        eq(row, expected[i])

    # Clean up.
    closeout(project_dict, workspace_page)
示例#25
0
def _test_MDAO_MDF(browser):
    # Build the MDF model as per the tutorial.

    project_dict, workspace_page = startup(browser)

    # Import the files that contain the disciplines
    file_path = pkg_resources.resource_filename('openmdao.lib.optproblems',
                                                'sellar.py')
    workspace_page.add_file(file_path)

    # Add Disciplines to assembly.
    workspace_page.add_library_item_to_dataflow('openmdao.main.assembly.Assembly', 'top')
    workspace_page.show_dataflow('top')
    workspace_page.add_library_item_to_dataflow('sellar.Discipline1', 'dis1')
    workspace_page.add_library_item_to_dataflow('sellar.Discipline2', 'dis2')

    # Replace Run_Once with SLSQP
    workspace_page.replace_driver('top', 'SLSQPdriver')

    # Add Solver
    workspace_page.add_library_item_to_dataflow(
        'openmdao.lib.drivers.iterate.FixedPointIterator',
        'solver')

    # One data connection
    dis1 = workspace_page.get_dataflow_figure('dis1', 'top')
    dis2 = workspace_page.get_dataflow_figure('dis2', 'top')
    conn_page = workspace_page.connect(dis1, dis2)
    conn_page.move(-100, -100)
    conn_page.connect_vars('dis1.y1', 'dis2.y1')
    conn_page.close()

    # Add solver to optimizer workflow
    workspace_page.add_object_to_workflow('top.solver', 'top')

    # Add disciplines to solver workflow
    workspace_page.expand_object('top')
    workspace_page.add_object_to_workflow('top.dis1', 'top.solver')
    workspace_page.add_object_to_workflow('top.dis2', 'top.solver')

    workspace_page('dataflow_tab').click()

    # Configure Solver
    driver = workspace_page.get_dataflow_figure('solver', 'top')
    editor = driver.editor_page(base_type='Driver')
    editor.move(-100, -100)

    editor('parameters_tab').click()
    dialog = editor.new_parameter()
    dialog.target = 'dis1.y2'
    dialog.low = '-9.e99'
    dialog.high = '9.e99'
    dialog('ok').click()

    editor('constraints_tab').click()
    dialog = editor.new_constraint()
    dialog.expr = 'dis2.y2 - dis1.y2 = 0'
    dialog('ok').click()
    editor.close()

    # Configure Optimizer
    driver = workspace_page.get_dataflow_figure('driver', 'top')
    editor = driver.editor_page(base_type='Driver')
    editor.move(-100, -100)

    editor('parameters_tab').click()
    dialog = editor.new_parameter()
    dialog.target = 'dis1.z1,dis2.z1'
    dialog.low = '-10.0'
    dialog.high = '10.0'
    dialog('ok').click()

    dialog = editor.new_parameter()
    dialog.target = 'dis1.z2,dis2.z2'
    dialog.low = '0.0'
    dialog.high = '10.0'
    dialog('ok').click()

    dialog = editor.new_parameter()
    dialog.target = "dis1.x1"
    dialog.low = '0.0'
    dialog.high = '10.0'
    dialog('ok').click()

    editor('constraints_tab').click()
    dialog = editor.new_constraint()
    dialog.expr = '3.16 < dis1.y1'
    dialog('ok').click()

    dialog = editor.new_constraint()
    dialog.expr = 'dis2.y2 < 24.0'
    dialog('ok').click()

    editor('objectives_tab').click()
    dialog = editor.new_objective()
    dialog.expr = '(dis1.x1)**2 + dis1.z2 + dis1.y1 + math.exp(-dis2.y2)'
    dialog('ok').click()
    editor.close()

    # Get an implicitly connected output before the run.
    dis1_fig = workspace_page.get_dataflow_figure('dis1', 'top')
    editor = dis1_fig.editor_page()
    outputs = editor.get_outputs()
    eq(outputs.value[0][1:3], ['y1', '0'])
    editor.close()

    # Run the model
    top = workspace_page.get_dataflow_figure('top')
    top.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')

    # Verify implicitly connected output has been updated with valid result.
    editor = dis1_fig.editor_page()
    outputs = editor.get_outputs()
    eq(outputs.value[0][1], 'y1')
    dis1_y1 = float(outputs.value[0][2])
    if abs(dis1_y1 - 3.16) > 0.01:
        raise TestCase.failureException(
            "Output dis1.y1 did not reach correct value, but instead is %s"
            % dis1_y1)
    editor.close()

    # Check the objective
    workspace_page.do_command("top.dis1.z1")
    output1 = workspace_page.history.split("\n")[-1]
    workspace_page.do_command("top.dis1.z2")
    output2 = workspace_page.history.split("\n")[-1]

    if abs(float(output1) - 1.977657) > 0.01:
        raise TestCase.failureException(
            "Parameter z1 did not reach correct value, but instead is %s"
            % output1)

    if abs(float(output2) - 0.0) > 0.0001:
        raise TestCase.failureException(
            "Parameter z2 did not reach correct value, but instead is %s"
            % output2)

    # Clean up.
    closeout(project_dict, workspace_page)
def _test_MDAO_MDF(browser):
    # Build the MDF model as per the tutorial.

    project_dict, workspace_page = startup(browser)

    # Import the files that contain the disciplines
    file_path = pkg_resources.resource_filename('openmdao.lib.optproblems',
                                                'sellar.py')
    workspace_page.add_file(file_path)

    # Add Disciplines to assembly.
    workspace_page.add_library_item_to_dataflow('openmdao.main.assembly.Assembly', 'top')
    workspace_page.show_dataflow('top')
    workspace_page.add_library_item_to_dataflow('sellar.Discipline1', 'dis1')
    workspace_page.add_library_item_to_dataflow('sellar.Discipline2', 'dis2')

    # Replace Run_Once with SLSQP
    workspace_page.replace_driver('top', 'SLSQPdriver')

    # Add Solver
    workspace_page.add_library_item_to_dataflow(
        'openmdao.lib.drivers.iterate.FixedPointIterator',
        'solver')

    # One data connection
    dis1 = workspace_page.get_dataflow_figure('dis1', 'top')
    dis2 = workspace_page.get_dataflow_figure('dis2', 'top')
    conn_page = workspace_page.connect(dis1, dis2)
    conn_page.move(-100, -100)
    conn_page.connect_vars('dis1.y1', 'dis2.y1')
    conn_page.close()

    # Add solver to optimizer workflow
    workspace_page.add_object_to_workflow('top.solver', 'top')

    # Add disciplines to solver workflow
    workspace_page.expand_object('top')
    workspace_page.add_object_to_workflow('top.dis1', 'top.solver')
    workspace_page.add_object_to_workflow('top.dis2', 'top.solver')

    workspace_page('dataflow_tab').click()

    # Configure Solver
    driver = workspace_page.get_dataflow_figure('solver', 'top')
    editor = driver.editor_page(base_type='Driver')
    editor.move(-100, -100)

    editor('inputs_tab').click()

    editor('parameters_tab').click()
    dialog = editor.new_parameter()
    dialog.target = 'dis1.y2'
    dialog.low = '-9.e99'
    dialog.high = '9.e99'
    dialog('ok').click()

    editor('constraints_tab').click()
    dialog = editor.new_constraint()
    dialog.expr = 'dis2.y2 = dis1.y2'
    dialog('ok').click()
    editor.close()

    # Configure Optimizer
    driver = workspace_page.get_dataflow_figure('driver', 'top')
    editor = driver.editor_page(base_type='Driver')
    editor.move(-100, -100)

    editor('parameters_tab').click()
    dialog = editor.new_parameter()
    dialog.target = 'dis1.z1,dis2.z1'
    dialog.low = '-10.0'
    dialog.high = '10.0'
    dialog('ok').click()

    dialog = editor.new_parameter()
    dialog.target = 'dis1.z2,dis2.z2'
    dialog.low = '0.0'
    dialog.high = '10.0'
    dialog('ok').click()

    dialog = editor.new_parameter()
    dialog.target = "dis1.x1"
    dialog.low = '0.0'
    dialog.high = '10.0'
    dialog('ok').click()

    editor('constraints_tab').click()
    dialog = editor.new_constraint()
    dialog.expr = '3.16 < dis1.y1'
    dialog('ok').click()

    dialog = editor.new_constraint()
    dialog.expr = 'dis2.y2 < 24.0'
    dialog('ok').click()

    editor('objectives_tab').click()
    dialog = editor.new_objective()
    dialog.expr = '(dis1.x1)**2 + dis1.z2 + dis1.y1 + math.exp(-dis2.y2)'
    dialog('ok').click()
    editor.close()

    # Set Initial Conditions
    workspace_page.do_command("top.dis1.z1 = top.dis2.z1 = 5.0")
    workspace_page.do_command("top.dis1.z2 = top.dis2.z2 = 2.0")
    workspace_page.do_command("top.dis1.x1 = 1.0")
    workspace_page.do_command("top.solver.tolerance = .00001")

    # Get an implicitly connected output before the run.
    dis1_fig = workspace_page.get_dataflow_figure('dis1', 'top')
    editor = dis1_fig.editor_page()
    outputs = editor.get_outputs()
    eq(outputs.value[0][1:3], ['y1', '0'])
    editor.close()

    # Run the model
    top = workspace_page.get_dataflow_figure('top')
    top.run()
    message = NotifierPage.wait(workspace_page)
    eq(message, 'Run complete: success')

    # Verify implicitly connected output has been updated with valid result.
    editor = dis1_fig.editor_page()
    outputs = editor.get_outputs()
    eq(outputs.value[0][1], 'y1')
    dis1_y1 = float(outputs.value[0][2])
    if abs(dis1_y1 - 3.16) > 0.01:
        raise TestCase.failureException(
            "Output dis1.y1 did not reach correct value, but instead is %s"
            % dis1_y1)
    editor.close()

    # Check the objective
    workspace_page.do_command("top.dis1.z1")
    output1 = workspace_page.history.split("\n")[-1]
    workspace_page.do_command("top.dis1.z2")
    output2 = workspace_page.history.split("\n")[-1]

    if abs(float(output1) - 1.977657) > 0.01:
        raise TestCase.failureException(
            "Parameter z1 did not reach correct value, but instead is %s"
            % output1)

    if abs(float(output2) - 0.0) > 0.0001:
        raise TestCase.failureException(
            "Parameter z2 did not reach correct value, but instead is %s"
            % output2)

    # Clean up.
    closeout(project_dict, workspace_page)
示例#27
0
def _test_replace(browser):
    # Replaces various connected components.
    project_dict, workspace_page = startup(browser)

    filename = pkg_resources.resource_filename('openmdao.gui.test.functional',
                                               'files/rosen_suzuki.py')
    workspace_page.add_file(filename)

    # Replace 'top' with Simulation.
    top = workspace_page.get_dataflow_figure('top')
    top.remove()
    workspace_page.add_library_item_to_dataflow('rosen_suzuki.Simulation', 'top')

    # Show dataflow for Simulation.
    workspace_page.show_dataflow('top')
    workspace_page.hide_left()

    # Verify preproc is a PreProc.
    preproc = workspace_page.get_dataflow_figure('preproc', 'top')
    editor = preproc.editor_page()
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    expected = [
        ['directory',     'str',  '',      '',  'true',
         'If non-blank, the directory to execute in.', '', ''],
        ['force_execute', 'bool', 'False', '',  'true',
         'If True, always execute even if all IO traits are valid.', '', ''],
        ['x_in', 'ndarray', '[ 1. 1. 1. 1.]', '',  'true', '', '', ''],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])
    editor.close()

    # Replace preproc with a ScalingPreProc.
    workspace_page.replace('preproc', 'rosen_suzuki.ScalingPreProc')
    preproc = workspace_page.get_dataflow_figure('preproc', 'top')
    editor = preproc.editor_page()
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    expected = [
        ['directory',     'str',  '',      '',  'true',
         'If non-blank, the directory to execute in.', '', ''],
        ['force_execute', 'bool', 'False', '',  'true',
         'If True, always execute even if all IO traits are valid.', '', ''],
        ['scaler', 'float', '1', '', 'true', '', '', ''],
        ['x_in', 'ndarray', '[ 1. 1. 1. 1.]', '', 'true', '', '', ''],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])
    editor.close()

    # Verify postproc is a PostProc.
    postproc = workspace_page.get_dataflow_figure('postproc', 'top')
    editor = postproc.editor_page()
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    expected = [
        ['directory',     'str',  '',      '',  'true',
         'If non-blank, the directory to execute in.', '', ''],
        ['force_execute', 'bool', 'False', '',  'true',
         'If True, always execute even if all IO traits are valid.', '', ''],
        ['result_in', 'float', '0', '', 'false', '', "['parent.comp.result']", ''],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])
    editor.close()

    # Replace postproc with a ScalingPostProc.
    workspace_page.replace('postproc', 'rosen_suzuki.ScalingPostProc')
    postproc = workspace_page.get_dataflow_figure('postproc', 'top')
    editor = postproc.editor_page()
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    expected = [
        ['directory',     'str',  '',      '',  'true',
         'If non-blank, the directory to execute in.', '', ''],
        ['force_execute', 'bool', 'False', '',  'true',
         'If True, always execute even if all IO traits are valid.', '', ''],
        ['result_in', 'float', '0', '', 'false', '', "['parent.comp.result']", ''],
        ['scaler', 'float', '1', '', 'true', '', '', ''],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])
    editor.close()

    # Verify driver is a CONMINdriver.
    driver = workspace_page.get_dataflow_figure('driver', 'top')
    editor = driver.editor_page(base_type='Driver')
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    eq(inputs.value[0],
       ['cons_is_linear', 'ndarray', '[]', '', 'true',
        'Array designating whether each constraint is linear.', '', ''])
    editor.close()

    # Replace driver with an SLSQPdriver.
    workspace_page.replace('driver',
                           'openmdao.lib.drivers.slsqpdriver.SLSQPdriver')
    driver = workspace_page.get_dataflow_figure('driver', 'top')
    editor = driver.editor_page(base_type='Driver')
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    eq(inputs.value[0],
       ['accuracy', 'float', '0.000001', '', 'true', 'Convergence accuracy', '', ''])
    editor.close()

    # Verify comp is a OptRosenSuzukiComponent.
    comp = workspace_page.get_dataflow_figure('comp', 'top')
    editor = comp.editor_page()
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    expected = [
        ['directory',     'str',  '',      '',  'true',
         'If non-blank, the directory to execute in.', '', ''],
        ['force_execute', 'bool', 'False', '',  'true',
         'If True, always execute even if all IO traits are valid.', '', ''],
        ['x', 'ndarray', '[]', '', 'false', '', "['parent.preproc.x_out']", "['driver']"],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])
    editor.close()

    # Replace comp with an Assembly.
    workspace_page.replace('comp', 'openmdao.main.assembly.Assembly')
    args_page = ArgsPrompt(workspace_page.browser, workspace_page.port)
    args_page.click_ok()
    message = NotifierPage.wait(workspace_page)
    eq(message, "RuntimeError: top: Can't connect 'comp.result' to"
                " 'postproc.result_in': top: Can't find 'comp.result'")
    comp = workspace_page.get_dataflow_figure('comp', 'top')
    editor = comp.editor_page()
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    expected = [
        ['directory',     'str',  '',      '',  'true',
         'If non-blank, the directory to execute in.', '', ''],
        ['force_execute', 'bool', 'False', '',  'true',
         'If True, always execute even if all IO traits are valid.', '', ''],
    ]
    for i, row in enumerate(inputs.value):
        eq(row, expected[i])
    editor.close()

    # Verify new figure.
    comp = workspace_page.get_dataflow_figure('comp', 'top')
    background = comp('top_right').value_of_css_property('background')
    assert background.find('circle-plus.png') >= 0

    # Clean up.
    closeout(project_dict, workspace_page)