def _add_variable(self, name, val, **kwargs): """ Contruct metadata for new variable. Args ---- name : string Name of the variable. val : float or ndarray or object Initial value for the variable. **kwargs Arbitrary keyword arguments to be added to metadata. Raises ------ RuntimeError If name is already in use or if setup has already been performed. NameError If name is not valid. ValueError If a valid value or shape is not specified. """ shape = kwargs.get('shape') self._check_name(name) meta = kwargs.copy() if isinstance(val, FileRef): val._set_meta(kwargs) meta['val'] = val = self._get_initial_val(val, shape) if is_differentiable(val) and not meta.get('pass_by_obj'): if isinstance(val, np.ndarray): meta['size'] = val.size meta['shape'] = val.shape else: meta['size'] = 1 meta['shape'] = 1 else: if not meta.get('pass_by_obj'): self._pbo_warns.append((name, val)) meta['size'] = 0 meta['pass_by_obj'] = True if isinstance(shape, int) and shape > 1: meta['shape'] = (shape, ) return meta
def _add_variable(self, name, val, **kwargs): """ Contruct metadata for new variable. Args ---- name : string Name of the variable. val : float or ndarray or object Initial value for the variable. **kwargs Arbitrary keyword arguments to be added to metadata. Raises ------ RuntimeError If name is already in use or if setup has already been performed. NameError If name is not valid. ValueError If a valid value or shape is not specified. """ shape = kwargs.get('shape') self._check_varname(name) meta = kwargs.copy() if isinstance(val, FileRef): val._set_meta(kwargs) meta['val'] = val = self._get_initial_val(val, shape) if is_differentiable(val) and not meta.get('pass_by_obj'): if isinstance(val, np.ndarray): meta['size'] = val.size meta['shape'] = val.shape else: meta['size'] = 1 meta['shape'] = 1 else: if not meta.get('pass_by_obj'): self._pbo_warns.append((name, val)) meta['size'] = 0 meta['pass_by_obj'] = True if isinstance(shape, int) and shape > 1: meta['shape'] = (shape,) return meta
def _add_variable(self, name, val, var_type, **kwargs): """ Contruct metadata for new variable. Args ---- name : string Name of the variable. val : float or ndarray or object Initial value for the variable. var_type : 'param' or 'output' Type of variable. **kwargs Arbitrary keyword arguments to be added to metadata. Raises ------ RuntimeError If name is already in use or if setup has already been performed. NameError If name is not valid. ValueError If a valid value or shape is not specified. """ shape = kwargs.get("shape") self._check_val(name, var_type, val, shape) self._check_name(name) meta = kwargs.copy() meta["promoted_name"] = name meta["val"] = val = self._get_initial_val(val, shape) if is_differentiable(val) and not meta.get("pass_by_obj"): if isinstance(val, np.ndarray): meta["size"] = val.size meta["shape"] = val.shape else: meta["size"] = 1 meta["shape"] = 1 else: meta["size"] = 0 meta["pass_by_obj"] = True if isinstance(shape, int) and shape > 1: meta["shape"] = (shape,) return meta
def _setup_var_meta(self, name, meta): """ Populate the metadata dict for the named variable. Args ---- name : str The name of the variable to add. meta : dict Starting metadata for the variable, collected from components in an earlier stage of setup. """ vmeta = meta.copy() val = meta['val'] if not is_differentiable(val) or meta.get('pass_by_obj'): vmeta['val'] = _ByObjWrapper(val) return vmeta
def _add_variable(self, name, val, **kwargs): """ Contruct metadata for new variable. Args ---- name : string Name of the variable. val : float or ndarray or object Initial value for the variable. **kwargs Arbitrary keyword arguments to be added to metadata. Raises ------ RuntimeError If name is already in use or if setup has already been performed. NameError If name is not valid. ValueError If a valid value or shape is not specified. """ shape = kwargs.get('shape') self._check_varname(name) meta = kwargs.copy() # Check for bad unit here unit = meta.get('unit') if unit: try: pq = PhysicalQuantity(1.0, unit) except: msg = "Unit '{}' is not a valid unit or combination of units." raise RuntimeError(msg.format(unit)) if isinstance(val, FileRef): val._set_meta(kwargs) meta['val'] = val = self._get_initial_val(val, shape) if is_differentiable(val) and not meta.get('pass_by_obj'): if isinstance(val, np.ndarray): meta['size'] = val.size meta['shape'] = val.shape else: meta['size'] = 1 meta['shape'] = 1 else: if not meta.get('pass_by_obj'): self._pbo_warns.append((name, val)) meta['size'] = 0 meta['pass_by_obj'] = True if isinstance(shape, int) and shape > 1: meta['shape'] = (shape,) if 'low' in kwargs: raise TypeError("Used arg 'low' when adding variable '%s'. " "Use 'lower' instead." % name) if 'high' in kwargs: raise TypeError("Used arg 'high' when adding variable '%s'. " "Use 'upper' instead." % name) return meta
def _add_variable(self, name, val, **kwargs): """ Contruct metadata for new variable. Args ---- name : string Name of the variable. val : float or ndarray or object Initial value for the variable. **kwargs Arbitrary keyword arguments to be added to metadata. Raises ------ RuntimeError If name is already in use or if setup has already been performed. NameError If name is not valid. ValueError If a valid value or shape is not specified. """ shape = kwargs.get('shape') self._check_varname(name) meta = kwargs.copy() # Check for bad unit here unit = meta.get('unit') if unit: try: pq = PhysicalQuantity(1.0, unit) except: msg = "Unit '{}' is not a valid unit or combination of units." raise RuntimeError(msg.format(unit)) if isinstance(val, FileRef): val._set_meta(kwargs) meta['val'] = val = self._get_initial_val(val, shape) if is_differentiable(val) and not meta.get('pass_by_obj'): if isinstance(val, np.ndarray): meta['size'] = val.size meta['shape'] = val.shape else: meta['size'] = 1 meta['shape'] = 1 else: if not meta.get('pass_by_obj'): self._pbo_warns.append((name, val)) meta['size'] = 0 meta['pass_by_obj'] = True if isinstance(shape, int) and shape > 1: meta['shape'] = (shape, ) if 'low' in kwargs: raise TypeError("Used arg 'low' when adding variable '%s'. " "Use 'lower' instead." % name) if 'high' in kwargs: raise TypeError("Used arg 'high' when adding variable '%s'. " "Use 'upper' instead." % name) return meta
def __init__(self, name, mdao_config, root, subproblem_output_meta): super(TestBenchComponent, self).__init__() self.name = name self.mdao_config = mdao_config self.__directory = mdao_config['components'][name]['details'][ 'directory'] self.original_testbench_manifest = self._read_testbench_manifest() self.manifest_params = { param['Name']: param for param in self.original_testbench_manifest['Parameters'] } self.manifest_fileinputs = { param['Name']: param for param in self.original_testbench_manifest.get( 'FileInputs', []) } self.manifest_metrics = { param['Name']: param for param in self.original_testbench_manifest['Metrics'] } self.manifest_fileoutputs = { param['Name']: param for param in self.original_testbench_manifest.get( 'FileOutputs', {}) } self.deriv_options['type'] = 'fd' def get_meta(param): units = param.get('units') if units: return {'units': str(units)} else: return {} for param_name, param in six.iteritems( mdao_config['components'][name].get('parameters', {})): pass_by_obj = source_is_not_driver = param.get( 'source', [''])[0] not in mdao_config['drivers'] val = 0.0 manifest_fileinput = self.manifest_fileinputs.get(param_name) if manifest_fileinput is not None: val = FileRef( os.path.join( self.__directory, manifest_fileinput.get('FileName', param_name))) self.add_param(_get_param_name(param_name), val=val, binary=True, pass_by_obj=True) continue elif source_is_not_driver and 'source' in param: if len(param['source']) == 1: # TODO: Single-element source must be a ProblemInput problemInput = mdao_config['problemInputs'][param['source'] [0]] if 'innerSource' in problemInput and problemInput[ 'innerSource'][0] in mdao_config['drivers']: source_type = mdao_config['drivers'][ problemInput['innerSource'][0]]['designVariables'][ problemInput['innerSource'][1]].get('type') if source_type == 'enum': val = mdao_config['drivers'][problemInput[ 'innerSource'][0]]['designVariables'][ problemInput['innerSource'][1]]['items'][0] pass_by_obj = True elif source_type == "int": val = 0 else: (val, pass_by_obj) = get_problem_input_value(problemInput) else: if param['source'][0] in mdao_config.get( 'subProblems', {}): # Source is a subproblem output; look up its real path, value, and pass_by_obj-ness source_component = { c.name: c for c in root.components() }[param['source'][0]] output_name = subproblem_output_meta[ param['source'][0]][param['source'][1]] meta = source_component._problem.root.unknowns._dat[ output_name].meta val = meta['val'] pass_by_obj = meta.get('pass_by_obj', False) else: # Source is not a subproblem output; must be a component source_component = { c.name: c for c in root.components() }[param['source'][0]] val = source_component._init_unknowns_dict[ param['source'][-1]]['val'] pass_by_obj = source_component._init_unknowns_dict[ param['source'][-1]].get('pass_by_obj', False) elif 'source' in param: source_type = mdao_config['drivers'][param['source'][0]][ 'designVariables'][param['source'][-1]].get('type') if source_type == 'enum': val = mdao_config['drivers'][param['source'][0]][ 'designVariables'][param['source'][-1]]['items'][0] pass_by_obj = True elif source_type == "int": val = 0 else: manifest_param = self.manifest_params.get(param_name) if manifest_param is not None: val = manifest_param['Value'] pass_by_obj = True else: raise ValueError( 'Could not find parameter or input file named {} in testbench_manifest.json' .format(param_name)) self.add_param(_get_param_name(param_name), val=val, pass_by_obj=pass_by_obj, **get_meta(param)) for metric_name, metric in six.iteritems( mdao_config['components'][name].get('unknowns', {})): manifest_metric = self.manifest_metrics.get(metric_name) if manifest_metric is not None: pass_by_obj = True for driver in mdao_config['drivers'].values(): if driver.get('type') != 'optimizer': continue for objective in driver['objectives'].values(): if objective['source'][0] == name and objective[ 'source'][1] == metric_name: pass_by_obj = False metric_meta = get_meta(metric) metric_meta['val'] = 0.0 for mdao_component in root.components(): # TODO: metric is possibly connected to a subproblem problemOutput. We should handle this case (root.components() does not contain the desired component, nor is it created yet) destination_component = mdao_config['components'].get( mdao_component.name) if destination_component is None: # TODO: possibly connected to an input to a component in a subproblem. We should handle this case # destination_component should possibly be an IndepVarComp from a ProblemInput. We don't need to handle this case # destination_component should possibly be an IndepVarComp designVariable. We don't need to handle this case continue for parameter_name, parameter in six.iteritems( destination_component['parameters']): if parameter['source'] == [self.name, metric_name]: mdao_parameter = mdao_component._init_params_dict[ _get_param_name( parameter_name, destination_component.get('type'))] for key in ('val', 'shape'): next_val = mdao_parameter.get(key, None) if next_val is not None: metric_meta.pop('val', None) metric_meta[key] = next_val if key == 'val': pass_by_obj = pass_by_obj or not is_differentiable( next_val) break self.add_output(metric_name, pass_by_obj=pass_by_obj, **metric_meta) else: manifest_fileoutput = self.manifest_fileoutputs.get( metric_name) if manifest_fileoutput is None: raise ValueError(metric_name) self.add_output(metric_name, val=FileRef( os.path.join( self.__directory, manifest_fileoutput.get( 'FileName', metric_name))), binary=True, pass_by_obj=True) self.add_output('_ret_code', val=0, pass_by_obj=True)