Changeset 25726
- Timestamp:
- 10/29/20 17:06:23 (4 years ago)
- Location:
- issm/trunk-jpl/src/m
- Files:
-
- 13 edited
Legend:
- Unmodified
- Added
- Removed
-
issm/trunk-jpl/src/m/classes/results.py
r25698 r25726 1 from copy import deepcopy 2 3 import numpy as np 4 1 5 from fielddisplay import fielddisplay 2 6 … … 7 11 Usage: 8 12 md.results = results() 13 14 TODO: 15 - Rework so that a solution of arbitrary length (normal or transient) can 16 initialized from one call to the results class constructor. 17 """ 18 19 def __init__(self): #{{{ 20 pass 21 #}}} 22 23 def __repr__(self): #{{{ 24 s = '' 25 for key, value in self.__dict__.items(): 26 if isinstance(value, resultsdakota): 27 lengthvalue = 1 28 else: 29 lengthvalue = len(value) 30 s += ' {}: [1x{} struct]\n'.format(key, lengthvalue) 31 32 return s 33 #}}} 34 35 def setdefaultparameters(self): #{{{ 36 #do nothing 37 return self 38 #}}} 39 40 def checkconsistency(self, md, solution, analyses): #{{{ 41 return md 42 #}}} 43 44 def marshall(self, prefix, md, fid): #{{{ 45 pass 46 #}}} 47 #}}} 48 49 class resultsdakota(object): #{{{ 50 """RESULTSDAKOTA class definition - Used to store results from a run of 51 Dakota. 52 53 Usage: 54 md.results.dakota = resultsdakota() 55 56 NOTE: Values of attributes can themselves be instances of solution class. 57 """ 58 59 def __init__(self): #{{{ 60 pass 61 #}}} 62 63 def __repr__(self): #{{{ 64 s = '' 65 for key, value in self.__dict__.items(): 66 s += ' {}: '.format(key) 67 if isinstance(value, list): 68 s += '[{} element list]'.format(len(value)) 69 else: 70 s += '{}'.format(value) 71 s += '\n' 72 return s 73 #}}} 74 75 def __len__(self): #{{{ 76 return len(self.__dict__.keys()) 77 #}}} 78 79 def setdefaultparameters(self): #{{{ 80 #do nothing 81 return self 82 #}}} 83 84 def checkconsistency(self, md, solution, analyses): #{{{ 85 return md 86 #}}} 87 88 def marshall(self, prefix, md, fid): #{{{ 89 pass 90 #}}} 91 #}}} 92 93 class solution(object): #{{{ 94 """SOLUTION class definition - Value of an attribute (which should be 95 a string representing a solution type) of an instance of results class 96 97 Elements of self.steps should be instances of solutionstep. 98 99 Usage: 100 setattr(md.results, 'SolutionType', solution()) 101 102 NOTE: 103 - Under MATLAB, this is implemented as a structure array 104 - Only when this instance of solution represents a transient solution 105 should self.steps have more than one element 9 106 """ 10 107 11 108 def __init__(self, *args): #{{{ 12 pass 13 #}}} 14 15 def __repr__(self): #{{{ 16 s = '' 17 if 'step' in self.__dict__: 18 s += '{}\n'.format(fielddisplay(self, 'step', "step number")) 19 if 'time' in self.__dict__: 20 s += '{}\n'.format(fielddisplay(self, 'time', "time value")) 21 if 'SolutionType' in self.__dict__: 22 s += '{}\n'.format(fielddisplay(self, 'SolutionType', "solution type")) 23 24 for name in list(self.__dict__.keys()): 25 if name not in ['step', 'time', 'SolutionType', 'errlog', 'outlog']: 26 if isinstance(getattr(self, name), list): 27 s += '{}\n'.format(fielddisplay(self, name, "model results list")) 28 elif isinstance(getattr(self, name), results): 29 s += '{}\n'.format(fielddisplay(self, name, "model results case")) 30 else: 31 s += '{}\n'.format(fielddisplay(self, name, "")) 32 33 if 'errlog' in self.__dict__: 34 s += '{}\n'.format(fielddisplay(self, 'errlog', "error log file")) 35 if 'outlog' in self.__dict__: 36 s += '{}\n'.format(fielddisplay(self, 'outlog', "output log file")) 37 38 return s 39 #}}} 40 41 def setdefaultparameters(self): #{{{ 42 #do nothing 43 return self 44 #}}} 45 46 def checkconsistency(self, md, solution, analyses): #{{{ 47 return md 48 #}}} 49 50 def marshall(self, prefix, md, fid): #{{{ 51 pass 52 #}}} 53 #}}} 54 55 class resultselement(object): #{{{ 56 """RESULTSELEMENT class definition - Value of attribute of results 57 58 Usage: 59 setattr(md.results, '<solution_type>', resultselement()) 60 """ 61 62 def __init__(self, *args): #{{{ 63 self.elements = [result()] 64 #}}} 65 66 def __repr__(self): #{{{ 67 s = ' 1x{} struct array with fields:\n'.format(len(self.elements)) 68 s += '\n' 69 70 if len(self.elements) >= 1: 71 for name in list(self.elements[0].__dict__.keys()): 72 s += ' {}\n'.format(name) 109 if len(args) == 1: 110 arg = args[0] 111 if isinstance(arg, list): 112 self.steps = arg 113 else: 114 raise Exception('solution class error: if initializing with an argument, that argument should be an empty list or a list of instances of solutionstep') 115 else: 116 self.steps = [solutionstep()] 117 #}}} 118 119 def __deepcopy__(self, memo): #{{{ 120 return solution(deepcopy(self.steps, memo)) 121 #}}} 122 123 def __repr__(self): #{{{ 124 s = '' 125 numsteps = len(self.steps) 126 if numsteps == 1: 127 for key, value in self.steps[0].__dict__.items(): 128 s += ' {}: {}\n'.format(key, value) 129 else: 130 s = ' 1x{} struct array with fields:\n'.format(numsteps) 131 s += '\n' 132 for fieldname in self.steps[0].getfieldnames(): 133 s += ' {}\n'.format(fieldname) 73 134 74 135 return s … … 76 137 77 138 def __len__(self): #{{{ 78 return len(self.elements) 139 return len(self.steps) 140 #}}} 141 142 def __getattr__(self, key): #{{{ 143 if len(self.steps) == 1: 144 return getattr(self.steps[0], key) 145 else: 146 raise Exception('<results>.<solution> error: Currently, can only get a field if we are not working with a transient solution.') 79 147 #}}} 80 148 … … 82 150 while True: 83 151 try: 84 return self. elements[index]152 return self.steps[index] 85 153 except: 86 self.elements.append(result()) 87 #}}} 88 89 def __setitem__(self, index, value): #{{{ 90 while True: 91 try: 92 self.elements[index] = value 93 break 94 except: 95 self.elements.append(result()) 96 #}}} 97 98 def setdefaultparameters(self): #{{{ 99 return self 100 #}}} 101 102 def checkconsistency(self, md, solution, analyses): #{{{ 103 return md 104 #}}} 105 106 def marshall(self, prefix, md, fid): #{{{ 107 pass 108 #}}} 109 #}}} 110 111 class result(object): #{{{ 112 """RESULT class definition - Element of resultselement::elements 113 114 Usage: 115 resultselement.elements.append(result()) 154 self.steps.append(solutionstep()) 155 else: 156 raise Exception('<results>.<solution>: either request a specific result by index or make sure that there is only a single result for this solution (cannot be a transient solution)') 157 #}}} 158 159 def setdefaultparameters(self): #{{{ 160 return self 161 #}}} 162 163 def checkconsistency(self, md, solution, analyses): #{{{ 164 return md 165 #}}} 166 167 def marshall(self, prefix, md, fid): #{{{ 168 pass 169 #}}} 170 #}}} 171 172 class solutionstep(object): #{{{ 173 """SOLUTIONSTEP class definition - Single element of <solution>.steps 174 175 Usage: 176 <solution>.steps.append(solutionstep()) 116 177 """ 117 178 … … 120 181 #}}} 121 182 122 def setdefaultparameters(self): #{{{ 123 return self 124 #}}} 125 126 def checkconsistency(self, md, solution, analyses): #{{{ 127 return md 128 #}}} 129 130 def marshall(self, prefix, md, fid): #{{{ 131 pass 132 #}}} 133 #}}} 183 def __repr__(self): #{{{ 184 s = '' 185 width = self.getlongestfieldname() 186 for key, value in self.__dict__.items(): 187 s += ' {:{width}s}: {}\n'.format(key, value, width=width) 188 189 return s 190 #}}} 191 192 def getfieldnames(self): #{{{ 193 return self.__dict__.keys() 194 #}}} 195 196 def getlongestfieldname(self): #{{{ 197 maxlength = 0 198 for key in self.__dict__.keys(): 199 length = len(key) 200 if length > maxlength: 201 maxlength = length 202 203 return maxlength 204 #}}} 205 206 def setdefaultparameters(self): #{{{ 207 return self 208 #}}} 209 210 def checkconsistency(self, md, solution, analyses): #{{{ 211 return md 212 #}}} 213 214 def marshall(self, prefix, md, fid): #{{{ 215 pass 216 #}}} 217 #}}} -
issm/trunk-jpl/src/m/miscellaneous/fielddisplay.py
r25157 r25726 22 22 #string 23 23 if isinstance(field, str): 24 25 24 if len(field) > 30: 26 25 string = displayunit(offset, name, "not displayed", comment) -
issm/trunk-jpl/src/m/miscellaneous/prctile_issm.py
r24261 r25726 3 3 4 4 5 # wrapper for prctile to avoid using the matlab statistics toolbox.6 5 def prctile_issm(x, p, dim): 6 # NumPy has no interpolation method that matches MATLAB's percentile function 7 #y = np.percentile(x, p, dim, interpolation = 'higher') 7 8 8 try:9 raise RuntimeError(' hello world')9 if len(np.shape(x)) > 2: 10 raise RuntimeError('Number of dimensions {} not implemented.'.format(len(np.shape(x)))) 10 11 11 # numpy has no interpolation method that matches matlab's percentile function12 # y = np.percentile(x, p, dim, interpolation = 'higher')13 except:14 if len(np.shape(x)) > 2:15 raise RuntimeError('Number of dimensions #d not implemented.' + str(len(np.shape(x))))12 # presumably at least 1 input value has been given 13 # np.shape(integer) -> (), must be at least (1, ) 14 psize = np.shape(p) or (1, ) 15 if len(psize) > 1 and np.size(p, 1) > 1: 16 p = p.T 16 17 17 # presumably at least 1 input value has been given 18 # np.shape(integer) -> (), must be at least (1, ) 19 psize = np.shape(p) or (1, ) 20 if len(psize) > 1 and np.size(p, 1) > 1: 21 p = p.T 18 xsize = np.shape(x) or (1, ) 19 if dim == 2: 20 x = x.T 22 21 23 xsize = np.shape(x) or (1, ) 24 if dim == 2: 25 x = x.T 22 # check for any NaN in any columns 23 if not np.isnan(x).any(): 24 x = np.sort(x, axis=0) 25 n = np.size(x, 0) 26 26 27 # check for any NaN in any columns 28 if not np.isnan(x).any(): 29 x = np.sort(x, axis=0) 30 n = np.size(x, 0) 27 # branch based on number of elements 28 if n > 1: 29 # set up percent values and interpolate 30 xi = [((i + 0.5) * 100 / n) for i in range(n)] 31 # scipy's interp1d returns a function 32 y = interp1d(xi, x, axis=dim, bounds_error=False) 33 y = y(p) 31 34 32 # branch based on number of elements 33 if n > 1: 34 # set up percent values and interpolate 35 xi = [((i + 0.5) * 100 / n) for i in range(n)] 36 # scipy's interp1d returns a function 37 y = interp1d(xi, x, axis=dim, bounds_error=False) 38 y = y(p) 35 # fill in high and low values outside of interp range 36 if p > xi[n - 1]: 37 y = np.tile(x[n - 1, :], 1) 38 if p < xi[0]: 39 y = np.tile(x[0, :], 1) 39 40 40 # fill in high and low values outside of interp range 41 if p > xi[n - 1]: 42 y = np.tile(x[n - 1, :], 1) 43 if p < xi[0]: 44 y = np.tile(x[0, :], 1) 41 # if one value, just copy it 42 elif n == 1: 43 y = np.tile(x[0, :], (len(p), 1)) 45 44 46 # if one value, just copy it 47 elif n == 1: 48 y = np.tile(x[0, :], (len(p), 1)) 45 # if no values, use NaN 46 else: 47 y = np.tile(float('NaN'), (np.size(p, 0), np.size(x, 0))) 48 else: 49 # must loop over columns, since number of elements could be different 50 y = np.zeros((np.size(p, 0), np.size(x, 1))) 51 for j in range(np.size(x, 1)): 52 # remove any NaN and recursively call column 53 y[:, j] = prctile_issm(x[np.where(not np.isnan(x[:, j]), j)], p) 49 54 50 # if no values, use NaN 51 else: 52 y = np.tile(float('NaN'), (np.size(p, 0), np.size(x, 0))) 53 else: 54 # must loop over columns, since number of elements could be different 55 y = np.zeros((np.size(p, 0), np.size(x, 1))) 56 for j in range(np.size(x, 1)): 57 # remove any NaN and recursively call column 58 y[:, j] = prctile_issm(x[np.where(not np.isnan(x[:, j]), j)], p) 59 60 if (np.min(xsize) == 1 and len(xsize) > 1 and xsize[dim] > 1 and len(p) > 1 and psize[1] > 1) or (np.min(xsize) > 1 and dim == 2): 61 y = y.T 55 if (np.min(xsize) == 1 and len(xsize) > 1 and xsize[dim] > 1 and len(p) > 1 and psize[1] > 1) or (np.min(xsize) > 1 and dim == 2): 56 y = y.T 62 57 63 58 return y -
issm/trunk-jpl/src/m/qmu/dakota_in_write.m
r25041 r25726 1 %2 % write a Dakota .in input file.3 %4 % []=dakota_in_write(method,dvar,dresp,params,filei,varargin)5 % []=dakota_in_write(dmeth ,dvar,dresp,params,filei,varargin)6 %7 % where the required input is:8 % method (character, dakota method name)9 % dmeth (dakota_method, method class object)10 % dvar (structure array, variable class objects)11 % dresp (structure array, response class objects)12 % params (structure array, method-independent parameters)13 % filei (character, name of .in file)14 %15 % the method and filei will be prompted if empty. params16 % may be empty, in which case defaults will be used.17 %18 % the optional varargin are not yet used.19 %20 % this function writes a dakota .in input file to be used21 % by dakota. this file is independent of the particular22 % analysis package.23 %24 % this data would typically be generated by a matlab script25 % for a specific model, using the method, variable, and26 % response class objects. this function may be called by27 % dakota_in_data.28 %29 % "Copyright 2009, by the California Institute of Technology.30 % ALL RIGHTS RESERVED. United States Government Sponsorship31 % acknowledged. Any commercial use must be negotiated with32 % the Office of Technology Transfer at the California Institute33 % of Technology. (J. Schiermeier, NTR 47078)34 %35 % This software may be subject to U.S. export control laws.36 % By accepting this software, the user agrees to comply with37 % all applicable U.S. export laws and regulations. User has the38 % responsibility to obtain export licenses, or other export39 % authority as may be required before exporting such information40 % to foreign countries or providing access to foreign persons."41 %42 1 function []=dakota_in_write(method,dvar,dresp,params,filei,corrin,varargin) 43 2 %DAKOTA_IN_WRITE - Write a Dakota .in input file. 3 % 4 % Usage: 5 % []=dakota_in_write(method,dvar,dresp,params,filei,varargin) 6 % []=dakota_in_write(dmeth ,dvar,dresp,params,filei,varargin) 7 % 8 % where the required input is, 9 % method (character, dakota method name) 10 % dmeth (dakota_method, method class object) 11 % dvar (structure array, variable class objects) 12 % dresp (structure array, response class objects) 13 % params (structure array, method-independent parameters) 14 % filei (character, name of .in file) 15 % 16 % The method and filei will be prompted for if empty. params may be empty, in 17 % which case defaults will be used. 18 % 19 % The optional varargin are not yet used. 20 % 21 % This function writes a Dakota .in input file to be used by Dakota. This 22 % file is independent of the particular analysis package. 23 % 24 % This data would typically be generated by a MATLAB script for a specific 25 % model, using the method, variable, and response class objects. This 26 % function may be called by dakota_in_data. 27 % 28 % "Copyright 2009, by the California Institute of Technology. ALL RIGHTS 29 % RESERVED. United States Government Sponsorship acknowledged. Any commercial 30 % use must be negotiated with the Office of Technology Transfer at the 31 % California Institute of Technology. (NTR 47078) 32 % 33 % This software may be subject to U.S. export control laws. By accepting this 34 % software, the user agrees to comply with all applicable U.S. export laws 35 % and regulations. User has the responsibility to obtain export licenses, or 36 % other export authority as may be required before exporting such information 37 % to foreign countries or providing access to foreign persons." 38 % 44 39 if ~nargin 45 40 help dakota_in_write … … 57 52 dmeth=method; 58 53 else 59 error(['Method ''' inputname(1) ''' is unrecognized class ''' class(method) ''' .']);54 error(['Method ''' inputname(1) ''' is unrecognized class ''' class(method) '''']); 60 55 end 61 56 … … 70 65 filei2=fullfile(pathstr,[name ext]); 71 66 72 display(sprintf('Opening Dakota input file ''%s'' .',filei2));67 display(sprintf('Opening Dakota input file ''%s''',filei2)); 73 68 fidi=fopen(sprintf('%s',filei2),'w'); 74 69 if (fidi < 0) 75 error('''%s'' could not be opened .',filei2);70 error('''%s'' could not be opened',filei2); 76 71 end 77 72 … … 110 105 111 106 fclose(fidi); 112 display('End of file successfully written .');107 display('End of file successfully written'); 113 108 114 109 % Uncomment to print contents of Dakota input file (for debugging) … … 121 116 function []=strategy_write(fidi,params) 122 117 123 display('Writing strategy section of Dakota input file .');118 display('Writing strategy section of Dakota input file'); 124 119 125 120 fprintf(fidi,'strategy,\n'); … … 136 131 function []=environment_write(fidi,params) 137 132 138 display('Writing environment section of Dakota input file .');133 display('Writing environment section of Dakota input file'); 139 134 140 135 fprintf(fidi,'environment,\n'); … … 150 145 function []=method_write(fidi,dmeth,dresp,params) 151 146 152 display('Writing method section of Dakota input file .');147 display('Writing method section of Dakota input file'); 153 148 154 149 fprintf(fidi,'method,\n'); … … 172 167 function []=model_write(fidi) 173 168 174 display('Writing model section of Dakota input file .');169 display('Writing model section of Dakota input file'); 175 170 176 171 fprintf(fidi,'model,\n'); … … 183 178 function []=variables_write(fidi,dmeth,dvar,corrin) 184 179 185 display('Writing variables section of Dakota input file .');180 display('Writing variables section of Dakota input file'); 186 181 187 182 fprintf(fidi,'variables,\n'); … … 219 214 function []=interface_write(fidi,params) 220 215 221 display('Writing interface section of Dakota input file .');216 display('Writing interface section of Dakota input file'); 222 217 223 218 fprintf(fidi,'interface,\n'); … … 226 221 params.fork=true; 227 222 elseif (params.system+params.fork+params.direct > 1) 228 error('Too many interfaces selected .')223 error('Too many interfaces selected') 229 224 end 230 225 … … 296 291 function []=responses_write(fidi,dmeth,dresp,params) 297 292 298 display('Writing responses section of Dakota input file .');293 display('Writing responses section of Dakota input file'); 299 294 300 295 fprintf(fidi,'responses,\n'); … … 333 328 params.numerical_gradients=true; 334 329 elseif (params.numerical_gradients+params.analytic_gradients > 1) 335 error('Too many gradients selected .')330 error('Too many gradients selected') 336 331 end 337 332 … … 352 347 353 348 if ismember('hess',ghspec) 354 error('Hessians needed by method but not provided .');349 error('Hessians needed by method but not provided'); 355 350 else 356 351 fprintf(fidi,'\tno_hessians\n'); -
issm/trunk-jpl/src/m/qmu/dakota_in_write.py
r25455 r25726 13 13 14 14 def dakota_in_write(method, dvar, dresp, params, filei, *args): 15 ''' 16 write a Dakota .in input file. 17 18 [] = dakota_in_write(method, dvar, dresp, params, filei, args) 19 [] = dakota_in_write(dmeth , dvar, dresp, params, filei, args) 20 21 where the required input is: 22 method (character, dakota method name) 23 dmeth (dakota_method, method class object) 24 dvar (structure array, variable class objects) 25 dresp (structure array, response class objects) 26 params (structure array, method - indepent parameters) 27 filei (character, name of .in file) 28 29 the method and filei will be prompted if empty. params 30 may be empty, in which case defaults will be used. 31 32 the optional args are not yet used. 33 34 this function writes a dakota .in input file to be used 35 by dakota. this file is indepent of the particular 36 analysis package. 37 38 this data would typically be generated by a matlab script 39 for a specific model, using the method, variable, and 40 response class objects. this function may be called by 41 dakota_in_data. 42 ''' 15 """DAKOTA_IN_WRITE - Write a Dakota .in input file. 16 17 Usage: 18 [] = dakota_in_write(method, dvar, dresp, params, filei, args) 19 [] = dakota_in_write(dmeth , dvar, dresp, params, filei, args) 20 21 where the required input is, 22 method (character, Dakota method name) 23 dmeth (dakota_method, method class object) 24 dvar (structure array, variable class objects) 25 dresp (structure array, response class objects) 26 params (structure array, method-independent parameters) 27 filei (character, name of .in file) 28 29 The method and filei will be prompted for if empty. params may be empty, in 30 which case defaults will be used. 31 32 The optional args are not yet used. 33 34 This function writes a Dakota .in input file to be used by Dakota. This 35 file is indepent of the particular analysis package. 36 37 This data would typically be generated by a matlab script for a specific 38 model, using the method, variable, and response class objects. This 39 function may be called by dakota_in_data. 40 41 "Copyright 2009, by the California Institute of Technology. ALL RIGHTS 42 RESERVED. United States Government Sponsorship acknowledged. Any commercial 43 use must be negotiated with the Office of Technology Transfer at the 44 California Institute of Technology. (NTR 47078) 45 46 This software may be subject to U.S. export control laws. By accepting this 47 software, the user agrees to comply with all applicable U.S. export laws 48 and regulations. User has the responsibility to obtain export licenses, or 49 other export authority as may be required before exporting such information 50 to foreign countries or providing access to foreign persons." 51 """ 43 52 44 53 # process the input parameters … … 63 72 filei2 = fullfile(pathstr, name + ext) 64 73 65 print('Opening Dakota input file \'' + filei2 + '\' .')74 print('Opening Dakota input file \'' + filei2 + '\'') 66 75 try: 67 76 with open(filei2, 'w+') as fidi: … … 90 99 91 100 except IOError: 92 print(filei2 + ' could not be opened .')93 94 print('End of file successfully written .')101 print(filei2 + ' could not be opened') 102 103 print('End of file successfully written') 95 104 96 105 # Uncomment to print contents of Dakota input file (for debugging) … … 101 110 def strategy_write(fidi, params): 102 111 103 print('Writing strategy section of Dakota input file .')112 print('Writing strategy section of Dakota input file') 104 113 105 114 fidi.write('strategy, \n') … … 114 123 def environment_write(fidi, params): 115 124 116 print('Writing environment section of Dakota input file .')125 print('Writing environment section of Dakota input file') 117 126 118 127 fidi.write('environment, \n') … … 126 135 def method_write(fidi, dmeth, dresp, params): 127 136 128 print('Writing method section of Dakota input file .')137 print('Writing method section of Dakota input file') 129 138 130 139 fidi.write('method, \n') … … 147 156 def model_write(fidi): 148 157 149 print('Writing model section of Dakota input file .')158 print('Writing model section of Dakota input file') 150 159 151 160 fidi.write('model, \n') … … 156 165 def variables_write(fidi, dmeth, dvar): 157 166 158 # print('Writing variables section of Dakota input file .')167 # print('Writing variables section of Dakota input file') 159 168 160 169 # fidi.write('variables, \n') … … 195 204 # fidi.write('\n') 196 205 197 print('Writing variables section of Dakota input file .')206 print('Writing variables section of Dakota input file') 198 207 199 208 fidi.write('variables, \n') … … 218 227 def interface_write(fidi, params): 219 228 220 print('Writing interface section of Dakota input file .')229 print('Writing interface section of Dakota input file') 221 230 222 231 fidi.write('interface, \n') … … 225 234 params.fork = True 226 235 elif params.system + params.fork + params.direct > 1: 227 raise RuntimeError('Too many interfaces selected .')236 raise RuntimeError('Too many interfaces selected') 228 237 if params.system or params.fork: 229 238 param_write(fidi, '\t', 'asynchronous', '', '\n', params) … … 289 298 def responses_write(fidi, dmeth, dresp, params): 290 299 291 print('Writing responses section of Dakota input file .')300 print('Writing responses section of Dakota input file') 292 301 293 302 fidi.write('responses, \n') … … 320 329 params.numerical_gradients = True 321 330 elif (params.numerical_gradients + params.analytic_gradients > 1): 322 raise RuntimeError('Too many gradients selected .')331 raise RuntimeError('Too many gradients selected') 323 332 324 333 if params.numerical_gradients: … … 335 344 # hessians (no implemented methods use them yet) 336 345 if 'hess' in ghspec: 337 raise RuntimeError('Hessians needed by method but not provided .')346 raise RuntimeError('Hessians needed by method but not provided') 338 347 else: 339 348 fidi.write('\tno_hessians\n') -
issm/trunk-jpl/src/m/qmu/dakota_m_write.m
r15771 r25726 1 %2 % write a Matlab .m function file to be called by Dakota for3 % the Matlab direct or external driver.4 %5 % []=dakota_m_write(method,dmeth,dvar,dresp,params,filem,package,varargin)6 %7 % where the required input is:8 % method (character, dakota method name)9 % dmeth (dakota_method, method class object)10 % dvar (structure array, variable class objects)11 % dresp (structure array, response class objects)12 % params (structure array, method-independent parameters)13 % filem (character, name of .m file)14 % package (character, analysis package)15 %16 % the method, dmeth, and filem will be prompted if empty.17 % params may be empty, in which case defaults will be used.18 %19 % the optional varargin are passed directly through to the20 % QmuUpdateFunctions brancher to be used by the analysis21 % package. for example, this could be model information.22 %23 % this function writes a matlab .m function file to be called24 % by dakota for the matlab direct or external driver. for25 % the direct driver, dakota is linked with matlab and26 % automatically starts a matlab session, passing the variables27 % and responses through the function; for the external driver,28 % dakota calls a shell script to start the matlab session,29 % passing the variables and responses through text files.30 % this function must be tailored to the particular analysis31 % package.32 %33 % this data would typically be generated by a matlab script34 % for a specific model, using the method, variable, and35 % response class objects. this function may be called by36 % dakota_in_data.37 %38 % "Copyright 2009, by the California Institute of Technology.39 % ALL RIGHTS RESERVED. United States Government Sponsorship40 % acknowledged. Any commercial use must be negotiated with41 % the Office of Technology Transfer at the California Institute42 % of Technology. (NTR 47078)43 %44 % This software may be subject to U.S. export control laws.45 % By accepting this software, the user agrees to comply with46 % all applicable U.S. export laws and regulations. User has the47 % responsibility to obtain export licenses, or other export48 % authority as may be required before exporting such information49 % to foreign countries or providing access to foreign persons."50 %51 1 function []=dakota_m_write(method,dmeth,dvar,dresp,params,filem,package,varargin) 52 2 %DAKOTA_M_WRITE - Write a Matlab .m function file to be called by Dakota for 3 % the MATLAB direct or external driver. 4 % 5 % Usage: 6 % []=dakota_m_write(method,dmeth,dvar,dresp,params,filem,package,varargin) 7 % 8 % where the required input is, 9 % method (character, Dakota method name) 10 % dmeth (dakota_method, method class object) 11 % dvar (structure array, variable class objects) 12 % dresp (structure array, response class objects) 13 % params (structure array, method-independent parameters) 14 % filem (character, name of .m file) 15 % package (character, analysis package) 16 % 17 % The method, dmeth, and filem will be prompted for if empty. params may be 18 % empty, in which case defaults will be used. 19 % 20 % The optional varargin are passed directly through to the QmuUpdateFunctions 21 % brancher to be used by the analysis package. For example, this could be 22 % model information. 23 % 24 % This function writes a MATLAB .m function file to be called by Dakota for 25 % the MATLAB direct or external driver. For the direct driver, Dakota is 26 % linked with MATLAB and automatically starts a MATLAB session, passing the 27 % variables and responses through the function; for the external driver, 28 % Dakota calls a shell script to start the MATLAB session, passing the 29 % variables and responses through text files. This function must be tailored 30 % to the particular analysis package. 31 % 32 % This data would typically be generated by a MATLAB script for a specific 33 % model, using the method, variable, and response class objects. This 34 % function may be called by dakota_in_data. 35 % 36 % "Copyright 2009, by the California Institute of Technology. ALL RIGHTS 37 % RESERVED. United States Government Sponsorship acknowledged. Any commercial 38 % use must be negotiated with the Office of Technology Transfer at the 39 % California Institute of Technology. (NTR 47078) 40 % 41 % This software may be subject to U.S. export control laws. By accepting this 42 % software, the user agrees to comply with all applicable U.S. export laws 43 % and regulations. User has the responsibility to obtain export licenses, or 44 % other export authority as may be required before exporting such information 45 % to foreign countries or providing access to foreign persons." 46 % 53 47 if ~nargin 54 48 help dakota_m_write … … 79 73 filem2=fullfile(pathstr,[name ext versn]); 80 74 81 display(sprintf('Opening Matlab m-file ''%s'' .',filem2));75 display(sprintf('Opening Matlab m-file ''%s''',filem2)); 82 76 fidm=fopen(sprintf('%s',filem2),'w'); 83 77 if (fidm < 0) 84 error('''%s'' could not be opened .',filem2);78 error('''%s'' could not be opened',filem2); 85 79 end 86 80 … … 106 100 107 101 fclose(fidm); 108 display('End of file successfully written .');102 display('End of file successfully written'); 109 103 110 104 end … … 114 108 function []=begin_write(fidm,name,params) 115 109 116 display('Writing beginning of Matlab m-file .');110 display('Writing beginning of Matlab m-file'); 117 111 118 112 fprintf(fidm,'%%\n'); … … 147 141 function []=variables_write(fidm,dmeth,dvar,params,varargin) 148 142 149 display('Writing variables for Matlab m-file .');143 display('Writing variables for Matlab m-file'); 150 144 151 145 fprintf(fidm,'%% Apply the variables.\n\n'); … … 174 168 function [ixc]=vlist_write(fidm,ixc,vtype,dvar,params,varargin) 175 169 176 disp(sprintf(' Writing %d %s variables .',length(dvar),class(dvar)));170 disp(sprintf(' Writing %d %s variables',length(dvar),class(dvar))); 177 171 178 172 for i=1:length(dvar) … … 204 198 function []=solution_write(fidm,package) 205 199 206 display('Writing solution for Matlab m-file .');200 display('Writing solution for Matlab m-file'); 207 201 fprintf(fidm,'%% Run the solution.\n\n'); 208 202 … … 215 209 function []=responses_write(fidm,dmeth,params,dresp) 216 210 217 display('Writing responses for Matlab m-file .');211 display('Writing responses for Matlab m-file'); 218 212 219 213 fprintf(fidm,'%% Calculate the responses.\n\n'); … … 251 245 function [ifnvals]=rlist_write(fidm,ifnvals,params,rtype,dresp) 252 246 253 disp(sprintf(' Writing %d %s responses .',length(dresp),class(dresp)));247 disp(sprintf(' Writing %d %s responses',length(dresp),class(dresp))); 254 248 for i=1:length(dresp) 255 249 ifnvals=ifnvals+1; … … 267 261 function []=end_write(fidm,name,params) 268 262 269 display('Writing end of Matlab m-file .');263 display('Writing end of Matlab m-file'); 270 264 271 265 fprintf(fidm,'%% Error condition.\n\n'); -
issm/trunk-jpl/src/m/qmu/dakota_out_parse.m
r25688 r25726 1 1 function [method,dresp,scm,pcm,srcm,prcm]=dakota_out_parse(filei) % {{{ 2 %DAKOTA_OUT_PARSE - Read a Dakota .out or .dat output file and parse it. 2 3 % 3 % read a Dakota .out or .dat output file and parse it. 4 % Usage: 5 % [method,dresp,scm,pcm,srcm,prcm]=dakota_out_parse(filei) 4 6 % 5 % [method,dresp,scm,pcm,srcm,prcm]=dakota_out_parse(filei) 7 % where the required input is, 8 % filei (character, name of .out file) 6 9 % 7 % where the required input is: 8 % filei (character, name of .out file) 10 % the required output is, 11 % method (character, dakota method name) 12 % dresp (structure array, responses) 9 13 % 10 % the required output is: 11 % method (character, dakota method name) 12 % dresp (structure array, responses) 14 % and the optional output is, 15 % scm (double array, simple correlation matrix) 16 % pcm (double array, partial correlation matrix) 17 % srcm (double array, simple rank correlation matrix) 18 % prcm (double array, partial rank correlation matrix) 13 19 % 14 % and the optional output is: 15 % scm (double array, simple correlation matrix) 16 % pcm (double array, partial correlation matrix) 17 % srcm (double array, simple rank correlation matrix) 18 % prcm (double array, partial rank correlation matrix) 20 % The filei will be prompted for if empty. The fields of dresp are particular 21 % to the data contained within the file. The scm, pcm, srcm, and prcm are 22 % output by dakota only for the sampling methods. 19 23 % 20 % the filei will be prompted if empty. the fields of dresp 21 % are particular to the data contained within the file. the 22 % scm, pcm, srcm, and prcm are output by dakota only for the 23 % sampling methods. 24 % This function reads a dakota .out output file and parses it into the MATLAB 25 % workspace. It operates in a content-driven fashion: it skips the 26 % intermediate data and then parses whatever output data it encounters in the 27 % order in which it exists in the file, rather than searching for data based 28 % on the particular method (this makes it independent of method). It also can 29 % read and parse the .dat tabular_output file. 24 30 % 25 % this function reads a dakota .out output file and parses it 26 % into the matlab workspace. it operates in a content-driven 27 % fashion, where it skips the intermediate data and then parses 28 % whatever output data it encounters in the order in which it 29 % exists in the file, rather than searching for data based on 30 % the particular method. (this makes it independent of method.) 31 % it also can read and parse the .dat tabular_output file. 31 % This data would typically be used for plotting and other postprocessing 32 % within MATLAB or Excel. 32 33 % 33 % this data would typically be used for plotting and other 34 % post-processing within matlab or excel. 34 % "Copyright 2009, by the California Institute of Technology. ALL RIGHTS 35 % RESERVED. United States Government Sponsorship acknowledged. Any commercial 36 % use must be negotiated with the Office of Technology Transfer at the 37 % California Institute of Technology. (NTR 47078) 35 38 % 36 % "Copyright 2009, by the California Institute of Technology.37 % ALL RIGHTS RESERVED. United States Government Sponsorship38 % acknowledged. Any commercial use must be negotiated with39 % the Office of Technology Transfer at the California Institute40 % of Technology. (NTR 47078)39 % This software may be subject to U.S. export control laws. By accepting this 40 % software, the user agrees to comply with all applicable U.S. export laws 41 % and regulations. User has the responsibility to obtain export licenses, or 42 % other export authority as may be required before exporting such information 43 % to foreign countries or providing access to foreign persons." 41 44 % 42 % This software may be subject to U.S. export control laws.43 % By accepting this software, the user agrees to comply with44 % all applicable U.S. export laws and regulations. User has the45 % responsibility to obtain export licenses, or other export46 % authority as may be required before exporting such information47 % to foreign countries or providing access to foreign persons."48 %49 50 45 if ~nargin 51 46 help dakota_out_parse … … 58 53 fidi=fopen(sprintf('%s',filei),'r'); 59 54 if (fidi < 0) 60 error('''%s'' could not be opened .',filei);55 error('''%s'' could not be opened',filei); 61 56 end 62 57 … … 66 61 fline=fgetl(fidi); 67 62 if ~ischar(fline) 68 error('File ''%s'' is empty .',filei);63 error('File ''%s'' is empty',filei); 69 64 end 70 65 … … 90 85 [ntokens,tokens]=fltokens(fline); 91 86 method=tokens{1}{1}; 92 display(sprintf('Dakota method = ''%s'' .',method));87 display(sprintf('Dakota method = ''%s''',method)); 93 88 elseif strcmp(tokens{1}{1}(7),'N') 94 89 [fline]=findline(fidi,'methodName = '); 95 90 [ntokens,tokens]=fltokens(fline); 96 91 method=tokens{1}{3}; 97 display(sprintf('Dakota methodName = ''%s'' .',method));92 display(sprintf('Dakota methodName = ''%s''',method)); 98 93 end 99 94 end … … 165 160 % return 166 161 % end 167 display('End of file successfully reached .');162 display('End of file successfully reached'); 168 163 fclose(fidi); 169 164 … … 172 167 %% function to parse the dakota tabular output file 173 168 174 display('Reading Dakota tabular output file .');169 display('Reading Dakota tabular output file'); 175 170 176 171 % process column headings of matrix (skipping eval_id) … … 178 173 [ntokens,tokens]=fltokens(fline); 179 174 180 % New file DAKOTA versions>6 181 if strncmpi(fline,'%eval_id interface',18) 175 if strncmpi(fline,'%eval_id interface',18) % Dakota versions >= 6 182 176 offset=2; 183 else % DAKOTA versions<6177 else % Dakota versions < 6 184 178 offset=1; 185 179 end 186 desc=cell 180 desc=cell(1,ntokens-offset); 187 181 data=zeros(1,ntokens-offset); 188 182 … … 190 184 desc(1,i)=cellstr(tokens{1}{i+offset}); 191 185 end 192 display(sprintf('Number of columns (Dakota V +R)=%d.',ntokens-2));186 display(sprintf('Number of columns (Dakota V + R) = %d',ntokens-2)); 193 187 194 188 % process rows of matrix … … 197 191 while 1 198 192 fline=fgetl(fidi); 193 199 194 if ~ischar(fline) || isempty(fline) 200 195 break; … … 209 204 end 210 205 end 211 display(sprintf('Number of rows (Dakota func evals) =%d.',nrow));206 display(sprintf('Number of rows (Dakota func evals) = %d',nrow)); 212 207 213 208 % calculate statistics … … 231 226 end 232 227 233 dmin =min 228 dmin =min(data,[],1); 234 229 dquart1=prctile_issm(data,25,1); 235 dmedian=median 230 dmedian=median(data,1); 236 231 dquart3=prctile_issm(data,75,1); 237 dmax =max 238 dmin95 =prctile_issm(data,5,1);239 dmax95 =prctile_issm(data,95,1);232 dmax =max(data,[],1); 233 dmin95 =prctile_issm(data,5,1); 234 dmax95 =prctile_issm(data,95,1); 240 235 241 236 % same as Dakota scm, Excel correl … … 285 280 [ntokens,tokens]=fltokens(fline); 286 281 nfeval=tokens{1}{5}; 287 display(sprintf(' Dakota function evaluations =%d.',nfeval));282 display(sprintf(' Dakota function evaluations = %d',nfeval)); 288 283 289 284 end % }}} … … 300 295 [ntokens,tokens]=fltokens(fline); 301 296 nsamp=tokens{1}{4}; 302 display(sprintf(' Dakota samples =%d.',nsamp));297 display(sprintf(' Dakota samples = %d',nsamp)); 303 298 304 299 end % }}} … … 331 326 end 332 327 333 display(sprintf(' Number of Dakota response functions =%d.',...328 display(sprintf(' Number of Dakota response functions = %d',... 334 329 length(dresp))); 335 330 … … 368 363 end 369 364 370 display(sprintf(' Number of Dakota response functions =%d.',...365 display(sprintf(' Number of Dakota response functions = %d',... 371 366 length(dresp))); 372 367 … … 432 427 end 433 428 434 display(sprintf(' Number of Dakota response functions =%d.',...429 display(sprintf(' Number of Dakota response functions = %d',... 435 430 length(dresp))); 436 431 … … 504 499 end 505 500 506 display(sprintf(' Number of Dakota response functions =%d.',...501 display(sprintf(' Number of Dakota response functions = %d',... 507 502 length(dresp))); 508 503 … … 568 563 end 569 564 570 display(sprintf(' Number of Dakota response functions =%d.',...565 display(sprintf(' Number of Dakota response functions = %d',... 571 566 length(dresp))); 572 567 … … 583 578 end 584 579 585 display(['Reading ''' fline ''' .']);580 display(['Reading ''' fline '''']); 586 581 587 582 cmat.title=fline; … … 682 677 683 678 if ~idvar 684 display(' Importance Factors not available .');679 display(' Importance Factors not available'); 685 680 dresp(end).var ={}; 686 681 dresp(end).impfac=[]; … … 746 741 747 742 if ~icdf 748 display(' Cumulative Distribution Function not available .');743 display(' Cumulative Distribution Function not available'); 749 744 dresp(ndresp).cdf=[]; 750 745 while ischar(fline) && ... … … 757 752 end 758 753 759 display(sprintf(' Number of Dakota response functions =%d.',...754 display(sprintf(' Number of Dakota response functions = %d',... 760 755 length(dresp))); 761 756 … … 902 897 dresp(end+1).vum=[]; 903 898 end 904 display('Reading measures for volumetric uniformity .');899 display('Reading measures for volumetric uniformity'); 905 900 906 901 fline=fgetl(fidi); … … 941 936 [ntokens,tokens]=fltokens(fline); 942 937 method=tokens{1}{3}; 943 display(sprintf('Dakota iterator ''%s'' completed .',method));938 display(sprintf('Dakota iterator ''%s'' completed',method)); 944 939 945 940 end % }}} … … 963 958 964 959 warning('findline:str_not_found',... 965 'String ''%s'' not found in file .',string);960 'String ''%s'' not found in file',string); 966 961 fseek(fidi,ipos,'bof'); 967 962 -
issm/trunk-jpl/src/m/qmu/dakota_out_parse.py
r25688 r25726 8 8 from helpers import * 9 9 10 # Note: this may be re-written later to take advantage of Python's file i / o mechanics11 # as it is written now it is often difficult to work with, but is analagous to12 # the Matlab version of dakota_out_parse10 # NOTE: May be rewritten later to take advantage of Python's file I/O 11 # mechanics. As it is written now, it is often difficult to work with, but is 12 # analagous to the MATLAB version of dakota_out_parse. 13 13 14 14 15 15 def dakota_out_parse(filei): # {{{ 16 ''' 17 read a Dakota .out or .dat output file and parse it. 18 19 [method, dresp, scm, pcm, srcm, prcm] = dakota_out_parse(filei) 20 21 where the required input is: 22 filei (character, name of .out file) 23 24 the required output is: 25 method (character, dakota method name) 26 dresp (structure array, responses) 27 28 and the optional output is: 29 scm (double array, simple correlation matrix) 30 pcm (double array, partial correlation matrix) 31 srcm (double array, simple rank correlation matrix) 32 prcm (double array, partial rank correlation matrix) 33 34 the filei will be prompted if empty. the fields of dresp 35 are particular to the data contained within the file. the 36 scm, pcm, srcm, and prcm are output by dakota only for the 37 sampling methods. 38 39 this function reads a dakota .out output file and parses it 40 into the matlab workspace. it operates in a content - driven 41 fashion, where it skips the intermediate data and then parses 42 whatever output data it encounters in the order in which it 43 exists in the file, rather than searching for data based on 44 the particular method. (this makes it independent of method.) 45 it also can read and parse the .dat tabular_output file. 46 47 this data would typically be used for plotting and other 48 post - processing within matlab or excel. 49 ''' 16 """DAKOTA_OUT_PARSE - read a Dakota .out or .dat output file and parse it. 17 18 Usage: 19 [method, dresp, scm, pcm, srcm, prcm] = dakota_out_parse(filei) 20 21 where the required input is, 22 filei (character, name of .out file) 23 24 the required output is, 25 method (character, Dakota method name) 26 dresp (structure array, responses) 27 28 and the optional output is, 29 scm (double array, simple correlation matrix) 30 pcm (double array, partial correlation matrix) 31 srcm (double array, simple rank correlation matrix) 32 prcm (double array, partial rank correlation matrix) 33 34 The filei will be prompted for if empty. The fields of dresp are particular 35 to the data contained within the file. The scm, pcm, srcm, and prcm are 36 output by Dakota only for the sampling methods. 37 38 This function reads a Dakota .out output file and parses it into the Python 39 runtime. It operates in a content-driven fashion, where it skips the 40 intermediate data and then parses whatever output data it encounters in the 41 order in which it exists in the file, rather than searching for data based 42 on the particular method (this makes it independent of method). It also can 43 read and parse the .dat tabular_output file. 44 45 This data would typically be used for plotting and other postprocessing 46 within MATLAB or Excel. 47 48 TODO: 49 - Figure out why output from Dakota is different under MATLAB and Python 50 (is it the input file that we write?) 51 52 "Copyright 2009, by the California Institute of Technology. ALL RIGHTS 53 RESERVED. United States Government Sponsorship acknowledged. Any commercial 54 use must be negotiated with the Office of Technology Transfer at the 55 California Institute of Technology. (NTR 47078) 56 57 This software may be subject to U.S. export control laws. By accepting this 58 software, the user agrees to comply with all applicable U.S. export laws 59 and regulations. User has the responsibility to obtain export licenses, or 60 other export authority as may be required before exporting such information 61 to foreign countries or providing access to foreign persons." 62 """ 63 50 64 if filei is None: 51 65 help(dakota_out_parse) … … 53 67 54 68 if not isfile(filei) or getsize(filei) == 0: 55 filei = str(eval(input('Input file? 69 filei = str(eval(input('Input file? '))) 56 70 57 71 #fidi = fopen(sprintf('%s', filei), 'r') … … 62 76 fline = fidi.readline() 63 77 if getsize(filei) == 0 or fline == '': 64 raise RuntimeError('File ' + filei + ' is empty .')65 66 dresp = [] 78 raise RuntimeError('File ' + filei + ' is empty') 79 80 dresp = [] # of struct() 67 81 scm = struct() 68 82 pcm = struct() … … 77 91 fidi.seek(0, 0) 78 92 79 #loop through the file to find the Dakota method name93 # loop through the file to find the Dakota method name 80 94 fline = findline(fidi, 'method', True) 81 95 if fline is None: … … 87 101 [ntokens, tokens] = fltokens(fline) 88 102 method = tokens[0].strip() 89 print('Dakota method = \'' + method + '\' .')103 print('Dakota method = \'' + method + '\'') 90 104 elif fline[6] in ['N', 'n']: 91 105 fline = findline(fidi, 'methodName = ') 92 106 [ntokens, tokens] = fltokens(fline) 93 107 method = tokens[2].strip() 94 print('Dakota methodName = \'' + method + '\' .')95 96 #loop through the file to find the function evaluation summary108 print('Dakota methodName = \'' + method + '\'') 109 110 # loop through the file to find the function evaluation summary 97 111 counter = 0 98 112 fline = '' 99 113 nfeval = nfeval_read(fidi, fline) 100 114 101 # 115 # process each results section based on content of the file 102 116 while counter < 10: 103 # because python makes file i / odifficult117 # because python makes file I/O difficult 104 118 # if we see 10 + blank lines in a row then we have reached EOF 105 119 # (tests show actual maximum number of blank lines is around 5) … … 108 122 else: 109 123 counter = 0 110 #ipos = ftell(fidi)124 # ipos = ftell(fidi) 111 125 fline = fidi.readline() 112 126 if fline == '' or fline.isspace(): … … 147 161 'Unexpected line: ' + str(fline) 148 162 149 #fidi.seek(ipos, 0)150 151 # 163 # fidi.seek(ipos, 0) 164 165 # loop through the file to verify the end 152 166 153 167 # fline = findline(fidi, '<<<<< Single Method Strategy completed') … … 155 169 # return 156 170 # 157 print('End of file successfully reached .')171 print('End of file successfully reached') 158 172 #close(fidi) 159 173 #except Exception as err: 160 174 #print "ERROR in dakota_out_parse: " + err 161 175 #raise err 162 #raise RuntimeError(filei + ' could not be opened .')176 #raise RuntimeError(filei + ' could not be opened') 163 177 164 178 return [method, dresp, scm, pcm, srcm, prcm] … … 167 181 168 182 def dak_tab_out(fidi, fline): # {{{ 169 # function to parse the dakota tabular output file 170 171 print('Reading Dakota tabular output file.') 172 173 # process column headings of matrix (skipping eval_id) 183 """DAK_TAB_OUT - function to parse the Dakota tabular output file 184 """ 185 186 print('Reading Dakota tabular output file') 187 188 # Process column headings of matrix (skipping eval_id) 174 189 [ntokens, tokens] = fltokens(fline) 175 190 176 # New file DAKOTA versions > 6 177 if strncmpi(fline, '%eval_id interface', 18): 191 if strncmpi(fline, '%eval_id interface', 18): # Dakota versions >= 6 178 192 offset = 2 179 else: # DAKOTAversions < 6193 else: # Dakota versions < 6 180 194 offset = 1 181 195 182 desc = [ ['' for i in range(ntokens - offset)]]196 desc = ['' for i in range(ntokens - offset)] 183 197 data = np.zeros((1, ntokens - offset)) 184 198 185 199 for i in range(ntokens - offset): 186 desc[ 0][i] = str(tokens[i + offset])187 188 print( "Number of columns (Dakota V + R)=" + str(ntokens - 2) + '.')189 190 # process rows of matrix200 desc[i] = str(tokens[i + offset]) 201 202 print('Number of columns (Dakota V + R) = {}'.format(ntokens - 2)) 203 204 # Process rows of matrix 191 205 nrow = 0 192 206 while True: 193 194 207 fline = fidi.readline() 195 208 … … 202 215 [ntokens, tokens] = fltokens(fline) 203 216 204 # add row values to matrix (skipping eval_id) 205 217 # Add row values to matrix (skipping eval_id) 206 218 for i in range(ntokens - offset): 207 219 data[nrow, i] = tokens[i + offset] … … 209 221 nrow = nrow + 1 210 222 211 print('Number of rows (Dakota func evals) = ' + str(nrow) + '.') 212 213 # calculate statistics 214 215 # since normfit doesn't have a dim argument, and matlab isvector is True 216 # for a 1xn matrix, handle the case of one row explicitly 217 218 # Update: normfit_issm.py does handle this case 223 print('Number of rows (Dakota func evals) = ' + str(nrow)) 224 225 # Calculate statistics 219 226 if (np.size(data, 0) > 1): 220 #dmean =mean(data)221 #dstddev = std 227 #dmean = mean(data) 228 #dstddev = std(data, 0) 222 229 [dmean, dstddev, dmeanci, dstddevci] = normfit_issm(data, 0.05) 223 230 else: … … 229 236 [dmean[0, i], dstddev[0, i], dmeanci[:, i], dstddevci[:, i]] = normfit_issm(data[:, i], 0.05) 230 237 231 dmin = data.min( 0)238 dmin = data.min(axis=0) 232 239 dquart1 = prctile_issm(data, 25, 0) 233 dmedian = np.median(data, 0)240 dmedian = np.median(data, axis=0) 234 241 dquart3 = prctile_issm(data, 75, 0) 235 dmax = data.max( 0)242 dmax = data.max(axis=0) 236 243 dmin95 = prctile_issm(data, 5, 0) 237 244 dmax95 = prctile_issm(data, 95, 0) 238 245 239 # N ote: the following line may cause the following warning240 # (should not crash or invalidate results) when one of241 # the inputs does not change with respect to the242 # other / s causing an internal divide-by - zero error243 244 # / usr / local / lib / python2.7 / dist - packages / numpy / lib / function_base.py:3163:245 # RuntimeWarning: invalid value encountered in true_divide246 # c / = stddev[:, None]247 248 # (and / or the same but with "c / = stddev[None, :]") 249 246 # NOTE: The following line may cause the following warning (should not 247 # crash or invalidate results) when one of the inputs does not change with 248 # respect to the other(s), causing an internal divide-by-zero error, 249 # 250 # /usr/local/lib/python2.7/dist-packages/numpy/lib/function_base.py:3163: 251 # RuntimeWarning: invalid value encountered in true_divide 252 # c /= stddev[:, None] 253 # 254 # (and/or the same but with "c /= stddev[None, :]") 255 256 # Equivalent to Dakota scm, MATLAB corrcoef, and Excel correl 250 257 dcorrel = np.corrcoef(data.T) 251 258 252 # divide the data into structures for consistency259 # Divide the data into structures for consistency 253 260 dresp = [] 254 255 261 for i in range(len(desc)): 256 262 dresp.append(struct()) 257 dresp[i].descriptor = str(desc[i])263 dresp[i].descriptor = desc[i] 258 264 dresp[i].sample = data[:, i] 259 265 dresp[i].mean = dmean[i] … … 294 300 [ntokens, tokens] = fltokens(fline) 295 301 nfeval = tokens[4] 296 print(' Dakota function evaluations = ' + str(int(nfeval)) + '.')302 print(' Dakota function evaluations = ' + str(int(nfeval))) 297 303 298 304 return nfeval … … 309 315 [ntokens, tokens] = fltokens(fline) 310 316 nsamp = tokens[3] 311 print(' Dakota samples = ' + str(int(nsamp)) + '.')317 print(' Dakota samples = ' + str(int(nsamp))) 312 318 313 319 return nsamp … … 340 346 dresp[-1].coefvar = tokens[12] 341 347 342 print(' Number of Dakota response functions = ' + str(len(dresp)) + '.')348 print(' Number of Dakota response functions = ' + str(len(dresp))) 343 349 344 350 return dresp … … 350 356 351 357 if fline is None or fline == '' or fline.isspace(): 352 fline = findline(fidi, 'Moment -based statistics for each response function')358 fline = findline(fidi, 'Moment-based statistics for each response function') 353 359 return 354 360 355 print('Reading moment -based statistics for response functions:')361 print('Reading moment-based statistics for response functions:') 356 362 357 363 # skip column headings of moment - based statistics … … 376 382 dresp[-1].kurtosis = tokens[4] 377 383 378 print(' Number of Dakota response functions = ' + str(len(dresp)) + '.')384 print(' Number of Dakota response functions = ' + str(len(dresp))) 379 385 380 386 return dresp … … 433 439 dresp[i].stddevci[1, 0] = tokens[4] 434 440 435 print(' Number of Dakota response functions = ' + str(len(dresp)) + '.')441 print(' Number of Dakota response functions = ' + str(len(dresp))) 436 442 437 443 return dresp … … 495 501 fline = fidi.readline() 496 502 497 print(' Number of Dakota response functions = ' + str(len(dresp)) + '.')503 print(' Number of Dakota response functions = ' + str(len(dresp))) 498 504 499 505 return dresp … … 550 556 fline = fidi.readline() 551 557 552 print(' Number of Dakota response functions = ' + str(len(dresp)) + '.')558 print(' Number of Dakota response functions = ' + str(len(dresp))) 553 559 554 560 return dresp … … 565 571 return 566 572 567 print('Reading ' + fline + '.')573 print('Reading ' + fline) 568 574 569 575 cmat.title = fline … … 657 663 # if importance factors missing, skip to cdf 658 664 if not idvar: 659 print(' Importance Factors not available .')665 print(' Importance Factors not available') 660 666 dresp[-1].var = [] 661 667 dresp[-1].impfac = [] … … 716 722 # if cdf missing, skip to end of response function 717 723 if not icdf: 718 print(' Cumulative Distribution Function not available .')724 print(' Cumulative Distribution Function not available') 719 725 dresp[ndresp].cdf = [] 720 726 while (fline != '' and not fline.isspace()) and not strncmpi(fline, 'MV Statistics for ', 18) and not strncmp(fline, ' - ', 1): 721 727 fline = fidi.readline() 722 728 723 print(' Number of Dakota response functions = ' + str(len(dresp)) + '.')729 print(' Number of Dakota response functions = ' + str(len(dresp))) 724 730 725 731 return dresp … … 845 851 dresp[-1].vum = [] 846 852 847 print('Reading measures for volumetric uniformity .')853 print('Reading measures for volumetric uniformity') 848 854 fline = fidi.readline() 849 855 fline = fidi.readline() … … 881 887 [ntokens, tokens] = fltokens(fline) 882 888 method = tokens[2] 883 print('Dakota iterator \'' + str(method) + '\' completed .')889 print('Dakota iterator \'' + str(method) + '\' completed') 884 890 885 891 return method … … 905 911 906 912 # issue warning and reset file position 907 print('Warning: findline:str_not_found: String ' + str(string) + ' not found in file .')913 print('Warning: findline:str_not_found: String ' + str(string) + ' not found in file') 908 914 fidi.seek(ipos, 0) 909 915 return None -
issm/trunk-jpl/src/m/qmu/helpers.py
r25492 r25726 1 1 from collections import OrderedDict 2 from copy import deepcopy 3 2 4 import numpy as np 3 from copy import deepcopy4 5 5 6 6 7 class struct(object): 7 """An empty struct that can be assigned arbitrary attributes""" 8 pass 8 """STRUCT class definition - An empty struct that can be assigned arbitrary 9 attributes 10 """ 11 def __init__(self): #{{{ 12 pass 13 #}}} 14 15 def __repr__(self): #{{{ 16 s = '' 17 for key, value in self.__dict__.items(): 18 s += ' {}: '.format(key) 19 if isinstance(value, list): 20 s += '[{} element list]'.format(len(value)) 21 elif isinstance(value, np.ndarray): 22 if len(value.shape) == 1: 23 s += '[{} element numpy.ndarray]'.format(value.shape[0]) 24 else: 25 s += '[{}x{} numpy.ndarray]'.format(value.shape[0], value.shape[1]) 26 else: 27 s += '{}'.format(value) 28 s += '\n' 29 return s 30 #}}} 31 32 def __len__(self): #{{{ 33 return len(self.__dict__.keys()) 34 #}}} 9 35 10 36 11 37 class Lstruct(list): 12 """ 13 An empty struct that can be assigned arbitrary attributes but can also be 38 """An empty struct that can be assigned arbitrary attributes but can also be 14 39 accesed as a list. Eg. x.y = 'hello', x[:] = ['w', 'o', 'r', 'l', 'd'] 15 40 -
issm/trunk-jpl/src/m/qmu/postqmu.m
r25627 r25726 39 39 if strcmpi(md.qmu.method.method,'nond_sampling'), 40 40 dakotaresults.modelresults={}; 41 md2=md; md2.qmu.isdakota=0; 41 md2=md; 42 md2.qmu.isdakota=0; 42 43 for i=1:md2.qmu.method.params.samples, 43 disp([' reading qmu file ' md2.miscellaneous.name '.outbin.' num2str(i)]);44 disp(['Reading qmu file ' md2.miscellaneous.name '.outbin.' num2str(i)]); 44 45 md2=loadresultsfromdisk(md2,[md2.miscellaneous.name '.outbin.' num2str(i)]); 45 46 dakotaresults.modelresults{end+1}=md2.results; -
issm/trunk-jpl/src/m/qmu/postqmu.py
r25688 r25726 6 6 from dakota_out_parse import * 7 7 from helpers import * 8 import loadresultsfromdisk as loadresults 8 import loadresultsfromdisk as loadresultsfromdisk # There is a name conflict somewhere 9 from results import results, resultsdakota, solution 9 10 10 11 … … 16 17 17 18 TODO: 18 - Run Dakota test to check that updates from 6/26 are working19 19 - Add checks to Popen 20 20 """ … … 34 34 qmuoutfile = str(md.miscellaneous.name) + '.qmu.out' 35 35 [method, dresp_out, scm, pcm, srcm, prcm] = dakota_out_parse(qmuoutfile) 36 dakotaresults = struct()36 dakotaresults = resultsdakota() 37 37 dakotaresults.dresp_out = dresp_out 38 dakotaresults.scm = scm39 dakotaresults.pcm = pcm40 dakotaresults.srcm = srcm41 dakotaresults.prcm = prcm38 dakotaresults.scm = scm 39 dakotaresults.pcm = pcm 40 dakotaresults.srcm = srcm 41 dakotaresults.prcm = prcm 42 42 43 43 if isfile('dakota_tabular.dat'): … … 50 50 dakotaresults.modelresults = [] 51 51 md2 = deepcopy(md) 52 md2.results = results() 52 53 md2.qmu.isdakota = 0 53 54 for i in range(md2.qmu.method.params.samples): 54 55 outbin_name = '{}.outbin.{}'.format(md2.miscellaneous.name, (i + 1)) 55 print('reading qmu file {}'.format(outbin_name)) 56 md2 = loadresults.loadresultsfromdisk(md2, outbin_name) 57 dakotaresults.modelresults.append(md2.results) 56 print('Reading qmu file {}'.format(outbin_name)) 57 md2 = loadresultsfromdisk.loadresultsfromdisk(md2, outbin_name) 58 dakotaresults.modelresults.append(deepcopy(md2.results)) 59 del md2 58 60 59 61 if md.qmu.statistics.method[0]['name'] != 'None': 60 62 md.qmu.isdakota = 0 61 md = loadresults .loadresultsfromdisk(md, '{}.stats'.format(md.miscellaneous.name))63 md = loadresultsfromdisk.loadresultsfromdisk(md, '{}.stats'.format(md.miscellaneous.name)) 62 64 md.qmu.isdakota = 1 63 65 64 66 # put dakotaresults in their right location. 65 md.results.dakota = d akotaresults67 md.results.dakota = deepcopy(dakotaresults) 66 68 67 69 # move all the individual function evalutations into zip files -
issm/trunk-jpl/src/m/solve/loadresultsfromdisk.py
r25712 r25726 1 1 import os 2 3 import numpy as np # Remove: used temporarily for debugging4 2 5 3 from helpers import fieldnames, struct … … 31 29 err_msg += ' Please check for error messages above or in the outlog \n' 32 30 err_msg += '============================================================\n' 31 print(err_msg) 32 return 33 33 34 raise OSError(err_msg) 35 36 # Initialize md.results if not a results structure yet 34 # Initialize md.results if not a structure yet 37 35 if not isinstance(md.results, results): 38 36 md.results = results() -
issm/trunk-jpl/src/m/solve/parseresultsfromdisk.py
r25714 r25726 4 4 import numpy as np 5 5 6 from results import resultselement6 from results import solution 7 7 8 8 … … 29 29 loadres = ReadDataDimensions(fid) 30 30 while loadres: 31 32 #Get time and step 31 # Get time and step 33 32 if loadres['step'] > len(saveres): 34 33 for i in range(len(saveres), loadres['step'] - 1): … … 38 37 setattr(saveres[loadres['step'] - 1], 'time', loadres['time']) 39 38 40 #Add result39 # Add result 41 40 setattr(saveres[loadres['step'] - 1], loadres['fieldname'], float('NaN')) 42 41 43 #read next result42 # Read next result 44 43 loadres = ReadDataDimensions(fid) 45 44 … … 65 64 setattr(saveres[loadres['step'] - 1], 'time', loadres['time']) 66 65 67 #Add result66 # Add result 68 67 setattr(saveres[loadres['step'] - 1], loadres['fieldname'], loadres['field']) 69 68 70 #read next result69 # Read next result 71 70 loadres = ReadData(fid, md) 72 71 73 # close file72 # Close file 74 73 fid.close() 75 74 … … 108 107 109 108 # Ok, now construct structure 110 results = resultselement() 109 results = solution() 110 111 111 for i in range(numresults): 112 112 result = allresults[i] … … 118 118 setattr(results[index], 'time', result['time']) 119 119 setattr(results[index], result['fieldname'], result['field']) 120 121 120 return results 122 121 # }}} … … 322 321 return saveres 323 322 # }}} 323 324 def addfieldtorecord(a, descr): #{{{ 325 if a.dtype.fields is None: 326 raise ValueError('\'a\' must be a structured numpy array') 327 b = np.empty(a.shape, dtype=a.dtype.descr + descr) 328 for name in a.dtype.names: 329 b[name] = a[name] 330 331 return b 332 #}}}
Note:
See TracChangeset
for help on using the changeset viewer.