def test_genhighD(setup, runsize, nkeep=2, outpath=None): """ For some testing of function gen_highD(). """ maxfact = np.max(setup.factor_levels) minfact = np.min(setup.factor_levels) if runsize % np.lcm(minfact, maxfact) > 0: print( "Number of Experiments (Runsize) must be lowest common multiple of factor levels!" ) else: arrayclass = oapackage.arraydata_t(setup.factor_levels, runsize, 2, setup.number_of_factors) Asel, effs = gen_highD(setup, arrayclass, nkeep=nkeep, outpath=outpath) if outpath is not None: os.makedirs(outpath, exist_ok=True) fname = ("Oarray_" + str(setup.factor_levels) + "_Nrun" + str(runsize) + ".csv") np.savetxt(outpath + fname, np.asarray(Asel), delimiter=",", fmt="%i") fname = ("Efficiencies_" + str(setup.factor_levels) + "_Nrun" + str(runsize) + ".csv") np.savetxt(outpath + fname, effs, delimiter=",") return Asel, effs
def genOA(nruns, n4lvl, n2lvl, strength=2): """ Generate a list of OA of the array_link class. Parameters ---------- nruns : int Number of runs. n4lvl : int Number of four-level factors. n2lvl : int Number of two-level factors. strength : int, optional Strength of the OA. The default is 2. Returns ------- arrays : list List of the OA with runsize nruns. """ number_of_factors = n4lvl + n2lvl factor_levels = np.repeat(np.array([4, 2]), [n4lvl, n2lvl], axis=0).tolist() arrayclass = oa.arraydata_t(factor_levels, nruns, strength, number_of_factors) ll2 = [arrayclass.create_root()] arrays = ll2 for extension_column in range(3, number_of_factors + 1): extensions = oa.extend_arraylist(arrays, arrayclass) #print('extended to %d arrays with %d columns' % (len(extensions), extension_column)) arrays = extensions return arrays
def build_oa(levels, factors, strength, index): arrayclass = oapackage.arraydata_t(levels, index * (levels ** strength), strength, factors) arrayclass.complete_arraydata() al = arrayclass.create_root() for i in range(factors - strength): al = oapackage.extend_array(al, arrayclass)[0] return al.getarray()
def setUp(self): self.arrayclass = oapackage.arraydata_t(2, 16, 0, 6) self.dds = np.random.rand(20, 3) self.dds2 = np.array([[1, 1, 1], [1, 2, 1], [1, 2, 3], [2, 0, 1]]) self.guitest = True try: import matplotlib.pyplot except: self.guitest = False
def test_Doptimize_nonzero_strength(self): arrayclass = oapackage.arraydata_t(2, 16, 2, 6) with self.assertWarns(UserWarning): scores, dds, sols, _ = oapackage.Doptim.Doptimize( arrayclass, nrestarts=1, verbose=0, maxtime=9, selectpareto=False, nout=None, niter=1000, dverbose=0)
def generate_orthogonal_array(): """ Example usage from: https://www.guru99.com/orthogonal-array-testing.html A Web page has three distinct sections (Top, Middle, Bottom) that can be individually shown or hidden from user No of Factors = 3 (Top, Middle, Bottom) No of Levels (Visibility) = 2 (Hidden or Shown) Array Type = L4(23) Test Cases TOP Middle Bottom Test #1 Hidden Hidden Hidden Test #2 Hidden Visible Visible Test #3 Visible Hidden Visible Test #4 Visible Visible Hidden Generate the test array (0-Hidden; 1-Visible) >> python orthogonalArray.py 2 4 3 0 0 0 0 1 1 1 0 0 1 1 1 """ # Levels (V) - Maximum number of values that can be taken on any single # factor. levels = int(sys.argv[1]) # Value range 0 till N # Runs (N) - Number of rows in the array, which translates into a number of # test cases that will be generated. runs = int(sys.argv[2]) # Rows # Factors (K) - Number of columns in the array, which translates into a # maximum number of variables that can be handled. factors = int(sys.argv[3]) # Columns print print('The Orthogonal array generated: L{}({}{})'.format( runs, levels, factors)) print arrayclass = oapackage.arraydata_t(levels, runs, factors, factors) al = arrayclass.create_root() myarray = al.getarray() space = ' ' for r in range(0, runs): row_data = "" for c in range(0, factors): val = myarray[r][c] row_data += '{}{}'.format(val, space * (4 - len(str(val)))) print(row_data) print
def test_arraydata_t_oaindex(self): for ii in range(1, 4): arrayclass = oapackage.arraydata_t([2, 2, 2], 4 * ii, 2, 3) self.assertEqual(arrayclass.oaindex, ii) with mock.patch('sys.stdout', new_callable=io.StringIO) as mock_stdout: arrayclass = oapackage.arraydata_t([4, 3, 3], 20, 2, 3) std_output = mock_stdout.getvalue() self.assertIn( 'arraydata_t: warning: no orthogonal arrays exist with the specified strength', std_output) self.assertEqual(arrayclass.oaindex, 0) with mock.patch('sys.stdout', new_callable=io.StringIO) as mock_stdout: arrayclass = oapackage.arraydata_t([2, 3, 4], 20, 2, 3) std_output = mock_stdout.getvalue() self.assertIn( 'the factor levels of the structure are not sorted, this can lead to undefined behaviour', std_output) with mock.patch('sys.stdout', new_callable=io.StringIO) as mock_stdout: arrayclass = oapackage.arraydata_t([6, 5], 10, 1, 2) self.assertEqual(arrayclass.oaindex, 0) std_output = mock_stdout.getvalue()
import numpy as np import oapackage print(800%25) exit() run_size = 20 strength = 2 number_of_factors= 10 factor_levels = 2 arrayclass=oapackage.arraydata_t(factor_levels, run_size, strength, number_of_factors) print(arrayclass) ll2=[arrayclass.create_root()] ll2[0].showarraycompact() test = np.array(ll2[0]) test_T = np.transpose(test) print(test) print(test_T) print(np.dot(test_T,test)) ary = ll2 for i in range(8): ary = oapackage.extend_arraylist(ary, arrayclass) print(f'extended to {len(ary)} arrays with {i+2} columns') """for L in ary : array = np.array(L) print(array)""" final_ary = np.array(ary[0],dtype = np.int) print(final_ary)
def optimize_design( setup, runsize, outpath_nrun=None, runtime=100, printopt=True, nrestarts=10, niter=None, ): """ Optimizes design for given design specification and array length (runsize) This optimization leverages part of the the oapackage.Doptimize package. See for more details https://oapackage.readthedocs.io/en/latest/index.html Parameters for oapackage have been finetuned through testing various design setups. The oapackage returns multiple designs and the best design is selected based on center balance effciency, orthogonality, and two-level balance (see function evaluate_design2) INPUT setup: ExperimentalSetup runsize: Number of experiments outpath_nrun: path for output directory (If None, no files are saved nor plotted) runtime: Maximum time for optimization (Default 100 seconds) printopt: (Default True) Prints status messages nrestart: Number of restrats for optimization (Default 10) niter: (Default None) Number of iterations for optimization. If None are given iterations are approximated by runtime """ # Setting for oapackage optimisation weighting for D, Ds, D1 efficiencies: alpha = [5, 5, 15] arrayclass = oapackage.arraydata_t(setup.factor_levels, runsize, 0, setup.number_of_factors) # First estimate time if niter is None: # First caculate number of iterations for given time start_time = time.time() devnull = open(os.devnull, "w") with redirect_stdout(devnull): scores, design_efficiencies, designs, ngenerated = oapackage.Doptimize( arrayclass, nrestarts=10, niter=100, optimfunc=alpha) delta_time1 = time.time() - start_time # in seconds start_time = time.time() with redirect_stdout(devnull): scores, design_efficiencies, designs, ngenerated = oapackage.Doptimize( arrayclass, nrestarts=10, niter=200, optimfunc=alpha) delta_time2 = time.time() - start_time # in seconds delta_time = delta_time2 - delta_time1 fac_time = runtime / delta_time # print("delta_time: ", delta_time) niter = np.int(100 * fac_time) print("Niteration:", niter) with redirect_stdout(devnull): scores, design_efficiencies, designs, ngenerated = oapackage.Doptimize( arrayclass, nrestarts=nrestarts, niter=niter, optimfunc=alpha, nabort=3000, maxtime=runtime, ) # Evaluate D efficiencies as weighted mean over D, Ds and D1 with weights alpha # Deff=[np.sum(d.Defficiencies() * np.asarray(alpha) / np.asarray(alpha).sum()) for d in designs] # Make evaluation based on center balance, orthogonality, and two-levelbaldance score = [] for i in range(len(designs)): effs = evaluate_design2(setup, np.asarray(designs[i]), printopt=False) # score = centereff + orthoeff + 0.5 * twoleveleff score.append(effs[0] + effs[2] + 0.5 * effs[3]) best = np.argmax(score) # design_efficiencies[~np.isfinite(design_efficiencies)] = 0. # Deffm_list = np.nansum(design_efficiencies * np.asarray(alpha), axis =1) / np.asarray(alpha).sum() # best=np.argmax(Deffm_list) Asel = designs[best] A = np.asarray(Asel) # Calculate efficiencies: efficiencies = evaluate_design2(setup, np.asarray(A), dir_out=outpath_nrun, printopt=True) # Save results if outpath_nrun is not None if outpath_nrun is not None: os.makedirs(outpath_nrun, exist_ok=True) fname = "EDarray_" + str( setup.factor_levels) + "_Nrun" + str(runsize) + ".csv" np.savetxt(outpath_nrun + fname, A, delimiter=",", fmt="%i") fname = ("Efficiencies_" + str(setup.factor_levels) + "_Nrun" + str(runsize) + ".csv") np.savetxt(outpath_nrun + fname, efficiencies, delimiter=",") return Asel, efficiencies