Example #1
0
 def elem_model_driver(self):
     # type: () -> Union[_Element, None]
     """:obj:`etree._Element`: The XML element of the super driver."""
     uid = self.driver_uid
     if uid:
         elem = get_element_by_uid(self.elem_cmdows, uid)
         if isinstance(elem, _Element):
             return elem
         else:
             raise InvalidCMDOWSFileError(
                 'does not contain element with UID {}'.format(uid))
     else:
         return None
Example #2
0
 def doe_runs(self):
     # type: () -> Dict[str,float]
     """Dictionary containing mapping between DOE UID and number of runs."""
     _doe_runs_dict = {}
     for doe_uid in self.doe_uids:
         doe_elem = get_element_by_uid(self.elem_cmdows, doe_uid)
         # Load settings from CMDOWS file
         doe_method = get_doe_setting_safe(doe_elem, 'method',
                                           'Uniform design')  # type: str
         doe_runs = get_doe_setting_safe(doe_elem,
                                         'runs',
                                         None,
                                         expected_type='int',
                                         doe_method=doe_method,
                                         required_for_doe_methods=[
                                             'Latin hypercube design',
                                             'Uniform design',
                                             'Monte Carlo design'
                                         ])
         _doe_runs_dict.update({doe_uid: doe_runs})
     return _doe_runs_dict
Example #3
0
    def driver(self):
        # type: () -> Driver
        """Method to return a preconfigured driver.

        Returns
        -------
            Driver
                A preconfigured driver element to be used for the Problem instance.

        Raises
        ------
            ValueError
                Value error are raised if unsupported settings are encountered.
        """
        if self.driver_type == 'optimizer':
            # Find optimizer element in CMDOWS file
            opt_uid = self.driver_uid
            opt_elem = get_element_by_uid(self.elem_cmdows, opt_uid)
            # Load settings from CMDOWS file
            opt_package = get_opt_setting_safe(opt_elem, 'package', 'SciPy')
            opt_algo = get_opt_setting_safe(opt_elem, 'algorithm', 'SLSQP')
            opt_maxiter = get_opt_setting_safe(opt_elem,
                                               'maximumIterations',
                                               50,
                                               expected_type='int')
            opt_convtol = get_opt_setting_safe(opt_elem,
                                               'convergenceTolerance',
                                               1e-6,
                                               expected_type='float')

            # Apply settings to the driver
            # driver
            if opt_package == 'SciPy':
                driver = ScipyOptimizeDriver()
            elif opt_package == 'pyOptSparse':
                try:
                    from openmdao.api import pyOptSparseDriver
                except ImportError:
                    raise PyOptSparseImportError()
                driver = pyOptSparseDriver()
            else:
                raise ValueError(
                    'Unsupported package {} encountered in CMDOWS file for "{}".'
                    .format(opt_package, opt_uid))

            # optimization algorithm
            if opt_algo == 'SLSQP':
                driver.options['optimizer'] = 'SLSQP'
            elif opt_algo == 'COBYLA':
                driver.options['optimizer'] = 'COBYLA'
            elif opt_algo == 'L-BFGS-B':
                driver.options['optimizer'] = 'L-BFGS-B'
            else:
                raise ValueError(
                    'Unsupported algorithm {} encountered in CMDOWS file for "{}".'
                    .format(opt_algo, opt_uid))

            # maximum iterations and tolerance
            if isinstance(driver, ScipyOptimizeDriver):
                driver.options['maxiter'] = opt_maxiter
                driver.options['tol'] = opt_convtol
            elif isinstance(driver, pyOptSparseDriver):
                driver.opt_settings['MAXIT'] = opt_maxiter
                driver.opt_settings['ACC'] = opt_convtol

            # Set default display and output settings
            if isinstance(driver, ScipyOptimizeDriver):
                driver.options['disp'] = False  # Print the result
            return driver
        elif self.driver_type == 'doe':
            # Find DOE element in CMDOWS file
            doe_uid = self.driver_uid
            doe_elem = get_element_by_uid(self.elem_cmdows, doe_uid)
            # Load settings from CMDOWS file
            doe_method = get_doe_setting_safe(doe_elem, 'method',
                                              'Uniform design')  # type: str
            doe_runs = get_doe_setting_safe(doe_elem,
                                            'runs',
                                            5,
                                            expected_type='int',
                                            doe_method=doe_method,
                                            required_for_doe_methods=[
                                                'Latin hypercube design',
                                                'Uniform design',
                                                'Monte Carlo design'
                                            ])
            doe_center_runs = get_doe_setting_safe(
                doe_elem,
                'centerRuns',
                2,
                expected_type='int',
                doe_method=doe_method,
                required_for_doe_methods=['Box-Behnken design'])
            doe_seed = get_doe_setting_safe(doe_elem,
                                            'seed',
                                            None,
                                            expected_type='int',
                                            doe_method=doe_method,
                                            required_for_doe_methods=[
                                                'Latin hypercube design',
                                                'Uniform design',
                                                'Monte Carlo design'
                                            ])
            doe_levels = get_doe_setting_safe(
                doe_elem,
                'levels',
                2,
                expected_type='int',
                doe_method=doe_method,
                required_for_doe_methods=['Full factorial design'])

            # table
            doe_data = []
            if isinstance(doe_elem.find('settings/table'), _Element):
                doe_table = doe_elem.find('settings/table')
                doe_table_rows = [row for row in doe_table.iterchildren()]
                n_samples = len(
                    [exp for exp in doe_table_rows[0].iterchildren()])
                for idx in range(n_samples):
                    data_sample = []
                    for row_elem in doe_table_rows:
                        value = float(
                            row_elem.find(
                                'tableElement[@experimentID="{}"]'.format(
                                    idx)).text)
                        data_sample.append(
                            [row_elem.attrib['relatedParameterUID'], value])
                    doe_data.append(data_sample)
            else:
                if doe_method in ['Custom design table']:
                    raise ValueError(
                        'Table element with data for custom design table missing in '
                        'CMDOWS file.')

            # Apply settings to the driver
            # define driver
            driver = DOEDriver()

            # define generator
            if doe_method in ['Uniform design', 'Monte Carlo design']:
                driver.options['generator'] = UniformGenerator(
                    num_samples=doe_runs, seed=doe_seed)
            elif doe_method == 'Full factorial design':
                driver.options['generator'] = FullFactorialGenerator(
                    levels=doe_levels)
            elif doe_method == 'Box-Behnken design':
                driver.options['generator'] = BoxBehnkenGenerator(
                    center=doe_center_runs)
            elif doe_method == 'Latin hypercube design':
                driver.options['generator'] = LatinHypercubeGenerator(
                    samples=doe_runs, criterion='maximin', seed=doe_seed)
            elif doe_method == 'Custom design table':
                driver.options['generator'] = ListGenerator(data=doe_data)
            else:
                raise ValueError(
                    'Could not match the doe_method {} with methods from OpenMDAO.'
                    .format(doe_method))
            return driver
        else:
            return Driver()