Пример #1
0
    def fit(self, tthmin=0, tthmax=180):
        """ Apply simplex to improve fit of obs/calc tth """
        tthmin = float(tthmin)
        tthmax = float(tthmax)
        import simplex
        if self.theoryds == None:
            self.addcellpeaks()
        # Assign observed peaks to rings
        self.wavelength = None
        self.indices = []  # which peaks used
        self.tthc = []  # computed two theta values
        self.fitds = []  # hmm?
        self.fit_tolerance = 1.
        pars = self.parameterobj.get_parameters()
        w = float(pars['wavelength'])
        self.wavelength = w
        self.fit_tolerance = float(pars['fit_tolerance'])
        print "Tolerance for assigning peaks to rings", \
            self.fit_tolerance, ", min tth", tthmin, ", max tth", tthmax
        tth, eta = self.compute_tth_eta()
        for i in range(len(self.theoryds)):
            dsc = self.theoryds[i]
            tthcalc = math.asin(dsc * w / 2) * 360. / math.pi  # degrees
            if tthcalc > tthmax:
                break
            elif tthcalc < tthmin:
                continue
            logicals = numpy.logical_and(
                numpy.greater(tth, tthcalc - self.fit_tolerance),
                numpy.less(tth, tthcalc + self.fit_tolerance))

            if sum(logicals) > 0:
                self.tthc.append(tthcalc)
                self.fitds.append(dsc)
                ind = numpy.compress(logicals, range(len(tth)))
                self.indices.append(ind)
        guess = self.parameterobj.get_variable_values()
        inc = self.parameterobj.get_variable_stepsizes()
        if len(guess) == 0:
            # There is nothing to fit.
            logging.warning("You try to fit with no variables!?")
            return None
        s = simplex.Simplex(self.gof, guess, inc)
        newguess, error, niter = s.minimize()
        inc = [v / 10 for v in inc]
        guess = newguess
        s = simplex.Simplex(self.gof, guess, inc)
        newguess, error, niter = s.minimize()
        self.parameterobj.set_variable_values(newguess)
        self.wavelength = self.parameterobj.get("wavelength")
        self.gof(newguess)
        print newguess
Пример #2
0
    def refinepositions(self, quiet=True, maxiters=100):
        self.assignlabels()
        ks = self.grains.keys()
        ks.sort()
        # assignments are now fixed
        tolcache = self.tolerance
        self.tolerance = 1.0
        for key in ks:
            g = key[0]
            self.grains_to_refine = [key]
            self.parameterobj.varylist = ['t_x', 't_y', 't_z']
            self.set_translation(key[0], key[1])
            guess = self.parameterobj.get_variable_values()
            inc = self.parameterobj.get_variable_stepsizes()

            s = simplex.Simplex(self.gof, guess, inc)

            newguess, error, iter = s.minimize(maxiters=maxiters, monitor=1)

            self.grains[key].translation[0] = self.parameterobj.parameters[
                't_x']
            self.grains[key].translation[1] = self.parameterobj.parameters[
                't_y']
            self.grains[key].translation[2] = self.parameterobj.parameters[
                't_z']
            print key, self.grains[key].translation,
            self.refine(self.grains[key].ubi, quiet=False)
        self.tolerance = tolcache
Пример #3
0
 def test_result(self):
     A = np.array([[1, 2, 2], [2, 1, 2], [2, 2, 1]])
     b = np.array([0, 20, 20, 20])
     c = np.array([-10, -12, -12])
     s = my.Simplex(A, b, c, "MIN")
     result = s.simplex(4)
     self.assertTrue(np.array_equiv(result, np.array([4., 4., 4.])))
Пример #4
0
	def start(self, c, b, A, arr_col, arr_row, F=0, level=0):
	
		lvl = level + 1
		step = simplex.Simplex(c, b, A, arr_col, arr_row, F)

		# Проверка ошибки в Simplex
		if step.brake:

			_count = np.size(c) + np.size(b)

			temp_value, index_value = self.fillValue(step)

			index_branch = self.findFloat(temp_value)

			# Все X - целочисленные, сравниваем с рекордом
			if index_branch < 0:
				self.match(temp_value)

			# Если значение f(x) < рекордного, нет смысла идти дальше
			elif temp_value[-1] < self.record_value[-1]:
				pass

			# Выполняем ветвление
			else:
				left = int(temp_value[index_branch])
				print ("\n\tУровень:", lvl, "\tВЕТВЛЕНИЕ ВЛЕВО ПО", self.arr_col[index_branch], "<=", left)
				self.addLimit(lvl, left, index_value[index_branch], _count, step, -1)

				right = left + 1
				print ("\n\tУровень:", lvl, "\tВЕТВЛЕНИЕ ВПРАВО ПО", self.arr_col[index_branch], ">=", right)
				self.addLimit(lvl, right, index_value[index_branch], _count, step, 1)

		pass
Пример #5
0
 def test_feasible_start(self):
     A = [[1, 1, 3], [2, 2, 5], [4, 1, 2]]
     b = [30, 24, 36]
     c = [3, 1, 2]
     n = 3
     m = 3
     s = simplex.Simplex(A, b, c, n, m)
     opt, ass = s.solve()
     self.assertEqual(s.optimum, 28)
Пример #6
0
 def test_infeasible_start(self):
     A = [[2, -1], [1, -5]]
     b = [2, -4]
     c = [2, -1]
     n = 2
     m = 2
     s = simplex.Simplex(A, b, c, n, m)
     opt, ass = s.solve()
     self.assertEqual(s.optimum, 2.0)
Пример #7
0
 def test_time(self):
     A = np.array([[1, 2, 2], [2, 1, 2], [2, 2, 1]])
     b = np.array([0, 20, 20, 20])
     c = np.array([-10, -12, -12])
     s = my.Simplex(A, b, c, "MIN")
     start = time.perf_counter()
     _ = s.simplex(4)
     stop = time.perf_counter()
     self.assertGreater(0.005, stop - start)
Пример #8
0
 def test_01(self):
     debug = True
     A = [[-1, -1], [1, 0], [0, 1]]
     b = [-1, 2, 2]
     c = [-1, 2]
     n = 3
     m = 2
     s = simplex.Simplex(A, b, c, n, m)
     opt, ass = s.solve()
     self.assertEqual(s.optimum, 4.0)
Пример #9
0
 def test_iter1(self):
     A = np.array([[1, 2, 2], [2, 1, 2], [2, 2, 1]])
     b = np.array([0, 20, 20, 20])
     c = np.array([-10, -12, -12])
     test_itr_1 = np.array([[120.0, -4.0, 0.0, 0.0, 6.0, 0.0, 0.0],
                            [10.0, 0.5, 1.0, 1.0, 0.5, 0.0, 0.0],
                            [10.0, 1.5, 0.0, 1.0, -0.5, 1.0, 0.0],
                            [0.0, 1.0, 0.0, -1.0, -1.0, 0.0, 1.0]])
     s = my.Simplex(A, b, c, "MIN")
     pass1 = s.optimize()
     self.assertTrue(np.array_equiv(pass1, test_itr_1))
Пример #10
0
    def setup_model(self, ):
        """ Simple function for providing test data """
        A = [[1, 1, -1, 0, 0, 1, 0], [2, -1, 0, -1, 0, 0, 1],
             [0, 3, 0, 0, 1, 0, 0]]
        b = [1, 1, 2]
        c = [3, 0, -1, -1, 0, 0, 0, 2]

        model = simplex.Simplex()
        model.add_constraints(A, b)
        model.add_objective(c, False)

        return model
Пример #11
0
    def test_iter2(self):
        A = np.array([[1, 2, 2], [2, 1, 2], [2, 2, 1]])
        b = np.array([0, 20, 20, 20])
        c = np.array([-10, -12, -12])

        test_itr_2 = np.array([
            [120.0, 0.0, 0.0, -4.0, 2.0, 0.0, 4.0],
            [10.0, 0.0, 1.0, 1.5, 1.0, 0.0, -0.5],
            [10.0, 0.0, 0.0, 2.5, 1.0, 1.0, -1.5],
            [0.0, 1.0, 0.0, -1.0, -1.0, 0.0, 1.0],
        ])
        s = my.Simplex(A, b, c, "MIN")
        s.optimize()
        pass2 = s.optimize()
        self.assertTrue(np.array_equiv(pass2, test_itr_2))
Пример #12
0
def main():
    try:
        logname = 'best_{}.log'.format(fit_type)
        with open(logname, 'rb') as best_file:
            reader = csv.reader(best_file, dialect='excel-tab')
            p0 = []
            for val in reader.next():
                p0.append(np.float(val))
        p0 = np.array(p0)
        ranges = p0 * 0.02
        s = simplex.Simplex(evaluate, p0, ranges)
        p, err, iter = s.minimize(epsilon=0.00001, maxiters=2000, monitor=0)
        with open(logname, 'a') as save_file:
            writer = csv.writer(save_file, dialect='excel-tab')
            writer.writerow(p)
            writer.writerow([ssn, err])
    except Exception as e:
        print(e)
Пример #13
0
 def fit(self, maxiters=100):
     """
     Fit the global parameters
     """
     self.assignlabels()
     guess = self.parameterobj.get_variable_values()
     inc = self.parameterobj.get_variable_stepsizes()
     names = self.parameterobj.varylist
     self.printresult(guess)
     self.grains_to_refine = self.grains.keys()
     self.recompute_xlylzl = False
     for n in names:
         if n not in ['t_x', 't_y', 't_z']:
             self.recompute_xlylzl = True
     inc = self.estimate_steps(self.gof, guess, inc)
     s = simplex.Simplex(self.gof, guess, inc)
     newguess, error, iter = s.minimize(maxiters=maxiters, monitor=1)
     print
     print "names", names
     print "ng", newguess
     for p, v in zip(names, newguess):
         # record results
         self.parameterobj.set(p, v)
         print "Setting parameter", p, v
     trans = ["t_x", "t_y", "t_z"]
     for t in trans:
         if t in names:
             i = trans.index(t)
             # imply that we are using this translation value, not the
             # per grain values
             # This is a f*cking mess - translations should never have been
             # diffractometer parameters
             for g in self.getgrains():
                 self.grains[g].translation[i] = newguess[names.index(t)]
                 print g, t, i, newguess[names.index(t)]
     print
     self.printresult(newguess)
Пример #14
0
    def initBasicSet(self):
        m, n = self.A.shape
        auxiliary = simplex.Simplex(
            list(np.sum(self.A, axis=0)) + [0] * m + [sum(self.b)])
        MI = [0] * m
        for i in range(m):
            MI[i] = 1
            auxiliary.add_constraint(list(self.A[i]) + MI, self.b[i])
            MI[i] = 0
        auxiliary.set_index(list(range(n + 1, n + m + 1)))
        print("<----- Begin The Auxiliary LP ----->")
        auxiliary.solveStandard(10)
        auxiliary.print_info()
        print("<----- Finish The Auxiliary LP ----->")

        obj = auxiliary.table[0, -1]
        if obj > simplex.eps:
            print("It is not feasible!")
        else:
            j = 1
            for i in range(m):
                if auxiliary.index[i] > n:
                    while auxiliary.map_index[j]:
                        j += 1
                    auxiliary.pivot(auxiliary.index[i], j)
            self.table = np.hstack(
                (auxiliary.table[:, :n + 1], auxiliary.table[:, -1:]))
            self.table[0] = np.array([[1] + list(self.cT * -1) + [0.0]
                                      ]).astype(np.float)
            self.set_index(auxiliary.index[1:])
            for i in range(1, n):
                if self.map_index[i] > 0:
                    self.table[0] -= self.table[
                        self.map_index[i]] * self.table[0, i]

        return
Пример #15
0
    def run_loop_input(self, lines, score=None):
        lines_iterator = iter(lines)
        while True:
            try:
                line = next(lines_iterator)
            except StopIteration:
                return self.ff
            cols = line.split()
            if cols[0] == 'DIR':
                self.direc = cols[1]
            if cols[0] == 'FFLD':
                # Import FF data.
                if cols[1] == 'read':
                    if cols[2] == 'mm3.fld':
                        self.ff = datatypes.MM3(
                            os.path.join(self.direc, cols[2]))
                    if 'prm' in line:
                        self.ff = datatypes.TinkerFF(
                            os.path.join(self.direc, cols[2]))
                    if 'frcmod' in line:
                        self.ff = datatypes.AmberFF(
                            os.path.join(self.direc, cols[2]))
                    self.ff.import_ff()
                    self.ff.method = 'READ'
                    with open(os.path.join(self.direc, cols[2]), 'r') as f:
                        self.ff.lines = f.readlines()
                # Export FF data.
                if cols[1] == 'write':
                    self.ff.export_ff(os.path.join(self.direc, cols[2]))
            # Trim parameters.
            if cols[0] == 'PARM':
                logger.log(20, '~~ SELECTING PARAMETERS ~~'.rjust(79, '~'))
                self.ff.params = parameters.trim_params_by_file(
                    self.ff.params, os.path.join(self.direc, cols[1]))
            if cols[0] == 'LOOP':
                # Read lines that will be looped over.
                inner_loop_lines = []
                line = next(lines_iterator)
                while line.split()[0] != 'END':
                    inner_loop_lines.append(line)
                    line = next(lines_iterator)
                # Make loop object and populate attributes.
                loop = Loop()
                loop.convergence = float(cols[1])
                loop.direc = self.direc
                loop.ff = self.ff
                loop.args_ff = self.args_ff
                loop.args_ref = self.args_ref
                loop.ref_data = self.ref_data
                loop.loop_lines = inner_loop_lines
                # Log commands.
                pretty_loop_input(inner_loop_lines,
                                  name='OPTIMIZATION LOOP',
                                  score=self.ff.score)
                # Run inner loop.
                self.ff = loop.opt_loop()
            # Note: Probably want to update this to append the directory given
            #       by the new DIR command.
            if cols[0] == 'RDAT':
                logger.log(20,
                           '~~ CALCULATING REFERENCE DATA ~~'.rjust(79, '~'))
                if len(cols) > 1:
                    self.args_ref = ' '.join(cols[1:]).split()
                self.ref_data = opt.return_ref_data(self.args_ref)
            if cols[0] == 'CDAT':
                logger.log(20, '~~ CALCULATING FF DATA ~~'.rjust(79, '~'))
                if len(cols) > 1:
                    self.args_ff = ' '.join(cols[1:]).split()
                self.ff.data = calculate.main(self.args_ff)

            if cols[0] == 'COMP':
                # Deprecated
                #    self.ff.score = compare.compare_data(
                #        self.ref_data, self.ff.data)
                #    if '-o' in cols:
                #        compare.pretty_data_comp(
                #            self.ref_data,
                #            self.ff.data,
                #            os.path.join(self.direc, cols[cols.index('-o') + 1]))
                #    if '-p' in cols:
                #        compare.pretty_data_comp(
                #            self.ref_data,
                #            self.ff.data,
                #            doprint=True)
                output = False
                doprint = False
                r_dict = compare.data_by_type(self.ref_data)
                c_dict = compare.data_by_type(self.ff.data)
                r_dict, c_dict = compare.trim_data(r_dict, c_dict)
                if '-o' in cols:
                    output = os.path.join(self.direc,
                                          cols[cols.index('-o') + 1])
                if '-p' in cols:
                    doprint = True
                self.ff.score = compare.compare_data(r_dict,
                                                     c_dict,
                                                     output=output,
                                                     doprint=doprint)
            if cols[0] == 'GRAD':
                grad = gradient.Gradient(direc=self.direc,
                                         ff=self.ff,
                                         ff_lines=self.ff.lines,
                                         args_ff=self.args_ff)
                #### Should probably just write a function instead of looping
                #### this for every gradient method. This includes everything
                #### between the two lines of #. TR 20180112
                ##############################################################
                for col in cols[1:]:
                    if "lstsq" in col:
                        g_args = col.split('=')[1].split(',')
                        for arg in g_args:
                            if arg == "True":
                                grad.do_lstsq = True
                            elif arg == False:
                                grad.do_lstsq = False
                            if 'radii' in arg:
                                grad.lstsq_radii = []
                                radii_vals = re.search(r"\[(.+)\]",
                                                       arg).group(1).split('/')
                                if radii_vals == "None":
                                    grad.lstsq_radii = None
                                else:
                                    for val in radii_vals:
                                        grad.lstsq_radii.append(float(val))
                            if 'cutoff' in arg:
                                grad.lstsq_cutoff = []
                                cutoff_vals = re.search(
                                    r"\[(.+)\]", arg).group(1).split('/')
                                if cutoff_vals == "None":
                                    grad.lstsq_cutoff = None
                                else:
                                    if len(cutoff_vals) > 2 or \
                                        len(cutoff_vals) < 2:
                                        raise Exception("Cutoff values must " \
                                            "be between two numbers.")
                                    for val in cutoff_vals:
                                        grad.lstsq_cutoff.append(float(val))
                    elif "newton" in col:
                        g_args = col.split('=')[1].split(',')
                        for arg in g_args:
                            if arg == "True":
                                grad.do_newton = True
                            elif arg == False:
                                grad.do_newton = False
                            if 'radii' in arg:
                                grad.newton_radii = []
                                radii_vals = re.search(r"\[(.+)\]",
                                                       arg).group(1).split('/')
                                if radii_vals == 'None':
                                    grad.newton_radii = None
                                else:
                                    for val in radii_vals:
                                        grad.newton_radii.append(float(val))
                            if 'cutoff' in arg:
                                grad.newton_cutoff = []
                                cutoff_vals = re.search(
                                    r"\[(.+)\]", arg).group(1).split('/')
                                if cutoff_vals == 'None':
                                    grad.newton_cutoff = None
                                else:
                                    if len(cutoff_vals) > 2 or \
                                        len(cutoff_vals) < 2:
                                        raise Exception("Cutoff values must " \
                                            "be between two numbers.")
                                    for val in cutoff_vals:
                                        grad.newton_cutoff.append(float(val))
                    elif "levenberg" in col:
                        g_args = col.split('=')[1].split(',')
                        for arg in g_args:
                            if arg == "True":
                                grad.do_levenberg = True
                            elif arg == False:
                                grad.do_levenberg = False
                            if 'radii' in arg:
                                grad.levenberg_radii = []
                                radii_vals = re.search(r"\[(.+)\]",
                                                       arg).group(1).split('/')
                                if radii_vals == 'None':
                                    grad.levenberg_radii = None
                                else:
                                    for val in radii_vals:
                                        grad.levenberg_radii.append(float(val))
                            if 'cutoff' in arg:
                                grad.levenberg_cutoff = []
                                cutoff_vals = re.search(
                                    r"\[(.+)\]", arg).group(1).split('/')
                                if cutoff_vals == 'None':
                                    grad.levenberg_cutoff = None
                                else:
                                    if len(cutoff_vals) > 2 or \
                                        len(cutoff_vals) < 2:
                                        raise Exception("Cutoff values must " \
                                            "be between two numbers.")
                                    for val in cutoff_vals:
                                        grad.levenberg_cutoff.append(
                                            float(val))
                            if 'factor' in arg:
                                grad.levenberg_cutoff = []
                                factor_vals = re.search(
                                    r"\[(.+)\]", arg).group(1).split('/')
                                if factor_vals == 'None':
                                    grad.levenberg_factor = None
                                else:
                                    for val in factor_vals:
                                        grad.levenberg_factor.append(
                                            float(val))
                    elif "lagrange" in col:
                        g_args = col.split('=')[1].split(',')
                        for arg in g_args:
                            if arg == "True":
                                grad.do_lagrange = True
                            elif arg == False:
                                grad.do_lagrange = False
                            if 'radii' in arg:
                                grad.lagrange_radii = []
                                radii_vals = re.search(r"\[(.+)\]",
                                                       arg).group(1).split('/')
                                if radii_vals == 'None':
                                    grad.lagrange_radii = None
                                else:
                                    for val in radii_vals:
                                        grad.lagrange_radii.append(float(val))
                            if 'cutoff' in arg:
                                grad.lagrange_cutoff = []
                                cutoff_vals = re.search(
                                    r"\[(.+)\]", arg).group(1).split('/')
                                if cutoff_vals == 'None':
                                    grad.lagrange_cutoff = None
                                else:
                                    if len(cutoff_vals) > 2 or \
                                        len(cutoff_vals) < 2:
                                        raise Exception("Cutoff values must " \
                                            "be between two numbers.")
                                    for val in cutoff_vals:
                                        grad.lagrange_cutoff.append(float(val))
                            if 'factor' in arg:
                                grad.lagrange_factors = []
                                factor_vals = re.search(
                                    r"\[(.+)\]", arg).group(1).split('/')
                                if factor_vals == 'None':
                                    grad.lagrange_factors = None
                                else:
                                    for val in factor_vals:
                                        grad.lagrange_factors.append(
                                            float(val))
                    elif "svd" in col:
                        g_args = col.split('=')[1].split(',')
                        for arg in g_args:
                            if arg == "True":
                                grad.do_svd = True
                            elif arg == False:
                                grad.do_svd = False
                            if 'radii' in arg:
                                grad.svd_radii = []
                                radii_vals = re.search(r"\[(.+)\]",
                                                       arg).group(1).split('/')
                                if radii_vals == 'None':
                                    grad.svd_radii = None
                                else:
                                    for val in radii_vals:
                                        grad.svd_radii.append(float(val))
                            if 'cutoff' in arg:
                                grad.svd_cutoff = []
                                cutoff_vals = re.search(
                                    r"\[(.+)\]", arg).group(1).split('/')
                                if cutoff_vals == 'None':
                                    grad.svd_cutoff = None
                                else:
                                    if len(cutoff_vals) > 2 or \
                                        len(cutoff_vals) < 2:
                                        raise Exception("Cutoff values must " \
                                            "be between two numbers.")
                                    for val in cutoff_vals:
                                        grad.svd_cutoff.append(float(val))
                            if 'factor' in arg:
                                grad.svd_cutoff = []
                                factor_vals = re.search(
                                    r"\[(.+)\]", arg).group(1).split('/')
                                if factor_vals == 'None':
                                    grad.svd_factor = None
                                else:
                                    for val in factor_vals:
                                        grad.svd_factor.append(float(val))
                    else:
                        raise Exception("'{}' : Not Recognized".format(col))
                ##############################################################
                self.ff = grad.run(ref_data=self.ref_data)
            if cols[0] == 'SIMP':
                simp = simplex.Simplex(direc=self.direc,
                                       ff=self.ff,
                                       ff_lines=self.ff.lines,
                                       args_ff=self.args_ff)
                for col in cols[1:]:
                    if "max_params" in col:
                        simp.max_params = col.split('=')[1]
                    else:
                        raise Exception("'{}' : Not Recognized".format(col))
                self.ff = simp.run(r_data=self.ref_data)
            if cols[0] == 'WGHT':
                data_type = cols[1]
                co.WEIGHTS[data_type] = float(cols[2])
            if cols[0] == 'STEP':
                param_type = cols[1]
                co.STEPS[param_type] = float(cols[2])
Пример #16
0
# MAIN

import numpy as np
import create
import simplex
import gomory
import output

# Вариант 18
c = np.array([7, 7, 6])
b = np.array([8, 2, 6])

A = np.array([[2, 1, 1], [1, 2, 0], [0, 0.5, 4]])

print("\nИсходная simplex-таблица\n")
obj = create.Create(c, b, A)
output.show(obj)

while (obj.gomory):
    print("\nПреобразованная simplex-таблица\n")
    simplex.Simplex(obj)
    output.show(obj)

    print("\nВызываем метод Гомори\n")
    gomory.Gomory(obj)
    output.show(obj)
    pass

print("\nЦелосчисленное решение")
output.result(obj)
Пример #17
0
 def run_loop_input(self, lines, score=None):
     lines_iterator = iter(lines)
     while True:
         try:
             line = lines_iterator.next()
         except StopIteration:
             return self.ff
         cols = line.split()
         if cols[0] == 'DIR':
             self.direc = cols[1]
         if cols[0] == 'FFLD':
             # Import FF data.
             if cols[1] == 'read':
                 self.ff = datatypes.MM3(os.path.join(self.direc, cols[2]))
                 self.ff.import_ff()
                 self.ff.method = 'READ'
                 with open(os.path.join(self.direc, cols[2]), 'r') as f:
                     self.ff.lines = f.readlines()
             # Export FF data.
             if cols[1] == 'write':
                 self.ff.export_ff(os.path.join(self.direc, cols[2]))
         # Trim parameters.
         if cols[0] == 'PARM':
             logger.log(20, '~~ SELECTING PARAMETERS ~~'.rjust(79, '~'))
             self.ff.params = parameters.trim_params_by_file(
                 self.ff.params, os.path.join(self.direc, cols[1]))
         if cols[0] == 'LOOP':
             # Read lines that will be looped over.
             inner_loop_lines = []
             line = lines_iterator.next()
             while line.split()[0] != 'END':
                 inner_loop_lines.append(line)
                 line = lines_iterator.next()
             # Make loop object and populate attributes.
             loop = Loop()
             loop.convergence = float(cols[1])
             loop.direc = self.direc
             loop.ff = self.ff
             loop.args_ff = self.args_ff
             loop.args_ref = self.args_ref
             loop.ref_data = self.ref_data
             loop.loop_lines = inner_loop_lines
             # Log commands.
             pretty_loop_input(inner_loop_lines,
                               name='OPTIMIZATION LOOP',
                               score=self.ff.score)
             # Run inner loop.
             self.ff = loop.opt_loop()
         # Note: Probably want to update this to append the directory given
         #       by the new DIR command.
         if cols[0] == 'RDAT':
             logger.log(20,
                        '~~ CALCULATING REFERENCE DATA ~~'.rjust(79, '~'))
             if len(cols) > 1:
                 self.args_ref = ' '.join(cols[1:]).split()
             self.ref_data = opt.return_ref_data(self.args_ref)
         if cols[0] == 'CDAT':
             logger.log(20, '~~ CALCULATING FF DATA ~~'.rjust(79, '~'))
             if len(cols) > 1:
                 self.args_ff = ' '.join(cols[1:]).split()
             self.ff.data = calculate.main(self.args_ff)
         if cols[0] == 'COMP':
             self.ff.score = compare.compare_data(self.ref_data,
                                                  self.ff.data)
             if '-o' in cols:
                 compare.pretty_data_comp(
                     self.ref_data, self.ff.data,
                     os.path.join(self.direc, cols[cols.index('-o') + 1]))
             if '-p' in cols:
                 compare.pretty_data_comp(self.ref_data, self.ff.data)
         if cols[0] == 'GRAD':
             grad = gradient.Gradient(direc=self.direc,
                                      ff=self.ff,
                                      ff_lines=self.ff.lines,
                                      args_ff=self.args_ff)
             self.ff = grad.run(ref_data=self.ref_data)
         if cols[0] == 'SIMP':
             simp = simplex.Simplex(direc=self.direc,
                                    ff=self.ff,
                                    ff_lines=self.ff.lines,
                                    args_ff=self.args_ff)
             self.ff = simp.run(r_data=self.ref_data)
         if cols[0] == 'WGHT':
             data_type = cols[1]
             co.WEIGHTS[data_type] = float(cols[2])
pygame.init()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption('Biome Generation')

# We will see 50x50 blocks at any given time.
grid = [[0] * 50] * 50

# There will be three biomes in the terrain: desert, grass, and snowy. Each one is represented by its own color.
biome_colors = {
    0: (255, 255, 0),  # Yellow
    1: (38, 108, 46),  # Forest green
    2: (255, 255, 255)  # White
}

# Import an instance of our Perlin noise generator.
noise = simplex.Simplex()

# Ask the user what seed to use for the simulation.
seed = float(input('Enter the numerical seed: '))

screen.fill((255, 255, 255))
pygame.display.flip()
# Game loop
running = True
while running:
    # Iterate through the biome list and determine the biome.
    for x in range(left, 50 + left):
        for y in range(top, 50 + top):
            ans = noise.noise(x * .5 * seed, y * .5 * seed)
            if ans < -0.3:  # Deserts should be relatively uncommon
                color = biome_colors[0]
Пример #19
0
def evaluate(p, ssn):
    dummy_x = np.zeros(10)
    dummy_y = np.zeros([10, 10])
    data = [[dummy_x, dummy_y, dummy_y], [dummy_x, dummy_y, dummy_y]]
    if fit_type is 'global' or fit_type is 20:  # 20 MHz data
        sim = PSim.DecaySim(reprate=20000000, tolerance=0.005, step=5e-12)
        sim.trap = p[0]
        sim.EHdecay = p[1] * sim.step
        sim.Etrap = p[2] * sim.step
        sim.FHloss = p[3] * sim.step
        sim.Gdecay = p[4] * sim.step
        sim.G2decay = p[5] * sim.step
        sim.G3decay = p[6] * sim.step
        sim.GHdecay = p[7] * sim.step
        sim.Gescape = p[8] * sim.step
        sim.Gform = p[9] * sim.step
        sim.G3loss = p[10] * sim.step
        sim.scalar = 1
        for power in powers:
            sim.addPower(power)
        sim.runSim()
        interp_signals = []
        for this_run in sim.signal:
            interp_this = np.interp(xarray, sim.xdata, this_run)
            interp_signals.append(interp_this)
        interp_signals = np.array(interp_signals)
        data[0] = [xarray, yarrays, interp_signals]
    if fit_type is 'global' or fit_type is 250:  # 250 kHz data
        sim_250 = PSim.DecaySim(reprate=250000, tolerance=0.005, step=5e-12)
        sim_250.trap = p[0]
        sim_250.EHdecay = p[1] * sim_250.step
        sim_250.Etrap = p[2] * sim_250.step
        sim_250.FHloss = p[3] * sim_250.step
        sim_250.Gdecay = p[4] * sim_250.step
        sim_250.G2decay = p[5] * sim_250.step
        sim_250.G3decay = p[6] * sim_250.step
        sim_250.GHdecay = p[7] * sim_250.step
        sim_250.Gescape = p[8] * sim_250.step
        sim_250.Gform = p[9] * sim_250.step
        sim_250.G3loss = p[10] * sim_250.step
        sim_250.scalar = 1
        for power in powers_250:
            sim_250.addPower(power)
        sim_250.runSim()
        interp_signals_250 = []
        for this_run in sim_250.signal:
            interp_this = np.interp(xarray_250, sim_250.xdata, this_run)
            interp_signals_250.append(interp_this)
        interp_signals_250 = np.array(interp_signals_250)
        data[1] = [xarray_250, yarrays_250, interp_signals_250]
    # Use a simplex minimization to find the best scalar
    scalar0 = np.array([8e-21])
    ranges = scalar0*0.1
    s = simplex.Simplex(scalar_min, scalar0, ranges)
    values, fitness, iter = s.minimize(epsilon=0.00001, maxiters=500,
                                       monitor=0, data=data)
    scalar = values[0]
    p[-1] = scalar
    if scalar < 0:
        fitness = 1e30
    with open(filename, 'a') as log_file:
        writer = csv.writer(log_file, dialect="excel-tab")
        row = [ssn, '{:.4e}'.format(fitness)]
        for var in p:
            row.append('{:.4e}'.format(var))
        writer.writerow(row)
    return fitness, scalar
Пример #20
0
print("ДАННЫЕ ВАРИАНТ №18")

print("c =", c)
print("b =", b)
print("A =", A)

# Программа

# Шаг 0 (Создаем массивы обозначений X для графического вывода)

x_col, x_row = marking.fillMarks(c, b)
F = 0

# Шаг 1 (Получаем значения F и Х-ов)

step_1 = simplex.Simplex(c, b, A, x_col, x_row)

default_param = np.array(x_col)
default_param = np.append(default_param, x_row)
default_value = np.zeros(np.size(default_param))

for i in range(np.size(step_1.arr_row)):
    for j in range(np.size(default_param)):
        if step_1.arr_row[i] == default_param[j]:
            default_value[j] = step_1.table[i][0]

F = abs(default_value[-1])

default_table = PrettyTable()
default_table.field_names = [item for item in default_param]
default_table.add_row([item for item in default_value])
Пример #21
0
# ...........: Trabalho Pratico 1 :...........
# ...: Disciplina de Pesquisa Operacional :...
# .Autora: Fernanda Aparecida Rodrigues Silva.
# ............................................
# ...:Departamento de Ciencia da Computacao:..
# ...:Universidade Federal de Minas Gerais:...
# ............................................


# External Imports
import sys

# Internal Imports
import simplex
import input_treatment

if __name__ == '__main__':
    file = input_treatment.InputTreatment()

    verbose_mode = False
    if(len(sys.argv) == 4):
        if(sys.argv[3] == "--verbose"):
            verbose_mode = True

    lp = file.read_file(sys.argv[1], verbose_mode)
    lp.turn_into_FPI(verbose_mode)
    s = simplex.Simplex(lp)
    s.solve_LP(verbose_mode)
    file.write_file(sys.argv[2], lp)