示例#1
0
 def __init__(self, f, ecn_params, ls_params, rec_params, zeta, m, output_level, mode = "cd", tol = 1e-8):
     """
     @param ecn_params: tuple of ECNoise parameters (h, breadth, max_iter)
     @param ls_params: tuple of line search parameters (c1, c2, max_iter)
     @param rec_params: tuple of recovery parameters (gamma_1, gamma_2)
     @param m: length of L-BFGS history
     """
     self.f = f
     self.zeta = zeta
     self.eval_counter = 0
     self.ls_counter = 0
     self.rec_counter = 0
     self.noise_f = ECNoise(f, *ecn_params)
     self.ls = LineSearch(f, *ls_params)
     self.rec = Recovery(f, *rec_params, self.noise_f, self.ls)
     self.lbfgs = LBFGS(m)
     self.output_level = output_level
     self.mode = mode
     self.tol = tol
    def recovery_robot(self):
        # Preparing
        self.recovery = Recovery()
        # Recovery Robot
        sleep_time = 0.1

        self.recovery_staus_led.on()
        print("Waiting for BUTTON1 press (recovery section)")
        self.first_button.wait_for_press()
        press_button_time = 0
        while self.first_button.is_pressed:
            press_button_time += 1
            if press_button_time >= 2.0 / sleep_time:
                self.recovery_staus_led.off()
            sleep(sleep_time)
        if press_button_time < 2 / sleep_time:
            print("recovery_robot start")
            self.recovery_staus_led.blink(on_time=1, off_time=2)
            self.recovery.main()
            print("recovery_robot end")
            self.recovery_staus_led.off()
        else:
            print("recovery was skipped")
示例#3
0
    def __init__(self, atomic_action, recovery=None):
        self.id = str(uuid4())
        self.atomic_action = atomic_action
        self.places = []
        self.transitions = []
        self.recovery = recovery if recovery is not None else Recovery()

        self.start_place = Place(name=atomic_action.name + ".P.start")
        self.exec_place = Place(name=atomic_action.name + ".P.exec",
                                atomic_action=atomic_action)
        self.end_place = Place(name=atomic_action.name + ".P.finished")
        self.places = [self.start_place, self.exec_place, self.end_place]

        self.transitions = [
            Transition(name=atomic_action.name + ".T.start",
                       atomic_action=atomic_action,
                       incoming_arcs=[Arc(place=self.start_place)],
                       outgoing_arcs=[Arc(place=self.exec_place)])
        ]
示例#4
0
def password_recovery():
    # Восстанавливаем пароль пользователя.
    form = Password_recovery()
    if form.validate_on_submit():  # Обрабатываем метод POST
        site_user = User.query.filter_by(
            email=form.address.data).first()  # Делаем запрос к базе дыннх.
        # Если такого email адреса НЕзарегистрировано в базе,сообщаем об этом.
        if site_user is None:
            # Сообщаем об ошибке.
            flash('Введенный адрес электронной почты не зарегистрирован.')
            return redirect(url_for('password_recovery'))
        else:
            Recovery(form)
            flash(
                f'Мы отправии инструкцию по восановлению пароля на указаный почтовый адрес.'
            )
            return redirect(url_for('password_recovery'))
    else:
        return render_template('password recovery.html',
                               title='Восстановление пароля ',
                               form=form)
示例#5
0
        if not (kcauto.conduct_scheduled_sleep() or kcauto.conduct_pause()):

            kcauto.run_receive_expedition_cycle()

            kcauto.run_quest_cycle()

            kcauto.run_expedition_cycle()

            kcauto.run_pvp_cycle()

            kcauto.run_combat_cycle()

            kcauto.run_repair_cycle()

            kcauto.run_ship_switch_cycle()

            kcauto.run_resupply_cycle()

            kcauto.run_quest_cycle()

            kcauto.conduct_module_sleeps()

            kcauto.conduct_scheduled_stops()

            kcauto.print_cycle_stats()

        sleep(Globals.LOOP_SLEEP_LENGTH)
    except FindFailed as e:
        Recovery.recover(kcauto, config, e)
示例#6
0
        kcauto_kai.refresh_config()

        if not (kcauto_kai.conduct_scheduled_sleep()
                or kcauto_kai.conduct_pause()):

            kcauto_kai.run_receive_expedition_cycle()

            kcauto_kai.run_quest_cycle()

            kcauto_kai.run_expedition_cycle()

            kcauto_kai.run_pvp_cycle()

            kcauto_kai.run_combat_cycle()

            kcauto_kai.run_repair_cycle()

            kcauto_kai.run_ship_switch_cycle()

            kcauto_kai.run_resupply_cycle()

            kcauto_kai.run_quest_cycle()

            kcauto_kai.conduct_module_sleeps()

            kcauto_kai.print_cycle_stats()

        sleep(Globals.LOOP_SLEEP_LENGTH)
    except FindFailed as e:
        Recovery.recover(kcauto_kai, e)
示例#7
0
        return x_0_lo, x_0_up


# test
if __name__ == "__main__":
    from recovery import Recovery
    Ad = np.array([[0.818727296278566, 0.017757312092950],
                   [-3.551462418590050e-04, 0.960785793022168]])
    Bd = np.array([[3.695886905026150e-04], [0.039210511090927]])

    # Ad = np.array([[1,2],[3,4]])
    # Bd = np.array([[5,6],[7,8]])

    initial_set_lo = [7.999902067622, 79.998780693465]
    initial_set_up = [7.999902067622887, 79.998780693465960]
    target_set_lo = [3.9, -100]
    target_set_up = [4.1, 100]
    safe_set_lo = [1, -150]
    safe_set_up = [8, 150]
    control_lo = [-150]
    control_up = [150]
    t = Recovery(Ad, Bd)
    control_lst = t.poll(10, initial_set_lo, initial_set_up, target_set_lo,
                         target_set_up, safe_set_lo, safe_set_up, control_lo,
                         control_up)

    t = Estimator(Ad, Bd, 20, 1e-7)
    x0_lo, x0_up = t.estimate(
        np.array([[7.999902067622887], [79.998780693465960]]), control_lst)
    print(x0_lo, x0_up)
示例#8
0
def test():

    from recovery import Recovery
    from testing import Testing

    df = pd.DataFrame()
    with CSVWriter('output.csv') as writer:

        for entry in process_probands('maximalkraft_daten'):

            row = Row()

            proband, hand, filename = entry
            row.add('', {'proband': proband, 'hand': hand})
            print(row)

            try:
                nirs_data, nirs_event, nirs_baseline = load_nirs_data(filename)
                f_max, f_avg = get_maxkraft(filename)
                kraftausdauer = get_kraftausdauer(filename, f_max)
            except Exception as exx:
                print('Failed to load file: %r : %r' % (filename, exx))
                continue

            row.add('', {'peak force': f_max, 'max force': f_avg})

            # print("== processing recovery ==")

            recovery = Recovery(nirs_data, nirs_event, nirs_baseline)

            row.add('RecoveryHalftime', recovery.get_timetohalf_recovery())
            row.add('RecoveryDepletion', recovery.get_dept())
            row.add('RecoveryDeltaprozent', recovery.get_deltaprozent())

            testing = Testing(nirs_data, nirs_event, nirs_baseline)

            for item in kraftausdauer:

                citeria = list(item.keys())[0]
                valid_intervals = item[citeria]['valid']

                row.add('Testing_' + citeria, {'valid': valid_intervals})

                try:
                    row.add('TestingMeanMin_' + citeria,
                            testing.get_mean_minima(valid_intervals)[0])
                except Exception as exx:
                    testing.get_mean_minima(valid_intervals)[0]

                try:
                    row.add('TestingMeanMinDiff_' + citeria,
                            testing.get_mean_minima(valid_intervals)[1])
                except Exception as exx:
                    testing.get_mean_minima(valid_intervals)[1]

                row.add('TestingMin_' + citeria,
                        testing.get_minima(valid_intervals)[0])
                row.add('TestingMinDiff_' + citeria,
                        testing.get_minima(valid_intervals)[1])

                row.add('TestingAll_' + citeria,
                        testing.get_avg_delta_relaxation_all(valid_intervals))
                row.add('TestingAll_' + citeria,
                        testing.get_avg_delta_contraction_all(valid_intervals))

                row.add(
                    'TestingFirst_' + citeria,
                    testing.get_avg_delta_relaxation_first(valid_intervals))
                row.add(
                    'TestingFirst_' + citeria,
                    testing.get_avg_delta_contraction_first(valid_intervals))

                row.add('TestingMid_' + citeria,
                        testing.get_avg_delta_relaxation_mid(valid_intervals))
                row.add('TestingMid_' + citeria,
                        testing.get_avg_delta_contraction_mid(valid_intervals))

                row.add('TestingLast_' + citeria,
                        testing.get_avg_delta_relaxation_last(valid_intervals))
                row.add(
                    'TestingLast_' + citeria,
                    testing.get_avg_delta_contraction_last(valid_intervals))

            writer.writerow(row)

            serie = pd.Series(row.get_data(), index=row.get_header())
            new_df = pd.DataFrame(columns=row.get_header())
            new_df = new_df.append(serie, ignore_index=True)
            df = df.append(new_df)

    # print(df)
    df.to_excel("output.xlsx")
    def setup(self):
        constraints = []
        components = self.components = []

        ####### components #########

        # payload
        payload = self.payload = Payload()

        # avionics
        avionics = self.avionics = Avionics()

        # recovery
        recovery = self.recovery = Recovery()

        # main engine
        engine = self.engine = SimpleEngine()

        # boosters
        boosters = self.boosters = Boosters()

        # structures
        structures = self.structures = Structures()

        components += [
            payload, avionics, recovery, engine, boosters, structures
        ]

        m = self.m = Variable("m", "kg", "Mass of Rocket")
        constraints += [Tight([m >= sum(comp.m for comp in components)])]

        ########## constraints ######

        # total impulse of main engine
        # main_impulse = Variable("I_t", 20000, "N s", "Total impulse of main engine")

        # constraints += [engine.c * engine.m_prop >= main_impulse]
        pmf = self.pmf = Variable('PMF', 0.20, '',
                                  'Propellant Mass Fraction required')
        constraints += [engine.m_prop >= pmf * m]

        # launch rail requirements

        launch_accel = Variable("a_{launch}", "m/s^2",
                                "Acceleration off launch rail")
        g = Variable("g", 9.81, "m/s^2", "Acceleration due to gravity")
        min_a = Variable("min_a", "m/s^2", "minimum launch acceleration")

        launch_rail_v = Variable("v_{launch}", 30, "m/s",
                                 "Velocity off launch rail")
        launch_rail_l = Variable("L_{launch}", 5, "m", "Length of launch rail")

        constraints += [min_a >= launch_rail_v**2 / (2 * launch_rail_l)]

        constraints += [
            Tight([launch_accel <= (engine.F + boosters.F - m * g) / m])
        ]

        constraints += [Tight([launch_accel >= min_a])]

        constraints += [
            0.5 * launch_accel * boosters.t_burn**2 >= launch_rail_l
        ]

        constraints += [Loose([boosters.m_prop >= 0.2 * ureg.kg])
                        ]  # from estimate of propellant mass required
        constraints += [
            boosters.m_prop * boosters.c >= boosters.F * boosters.t_burn
        ]  # from estimate of propellant mass required

        constraints += [Loose([m <= 100 * ureg.kg, m >= 10 * ureg.kg])]

        TW_main = self.TW_main = Variable(
            "TW_{main, min}", 2, "", "Main engine thrust to take off weight")
        constraints += [Loose([engine.F >= TW_main * m * g])]

        return [components, constraints]
示例#10
0
class MP2_A2:
    def __init__(self):
        # Preparing
        self.audiodir = path.expanduser('~/Git/MP2_A2_audiofiles/AudioFiles')
        self.fire = Fire("Arduino")
        self.first_button = Button(pin_fig.first_button)
        self.second_button = Button(pin_fig.second_button)
        self.main_status_led = LED(pin_fig.status_led_2)
        self.recovery_staus_led = LED(pin_fig.status_led_1)

        self.get_option()

    def get_option(self):
        argparser = ArgumentParser()
        argparser.add_argument('-t', '--finishtime', action='store_true',
                               help='Measure finish time')
                                # default is False
        argparser.add_argument('-e', '--waitforenter', action='store_true',
                               help=('Wait for ENTER key '
                                     'instead of button press'))
                                # default is False
        argparser.add_argument('-nl', '--no-loop', action='store_true',
                               help='Loop this script')
                                # default is False
        self.option = argparser.parse_args()

    def move_robot(self):
        # Preparing
        self.fc = FireAndConveyor(audiofiles_dir=self.audiodir)
        self.ee = ExplodeAndEscape(audiofiles_dir=self.audiodir)
        # Move Robot
        self.main_status_led.on()

        if self.option.waitforenter:
            input("Waiting for ENTER key instead of BUTTON1 (first section): ")
        else:
            print("Waiting for BUTTON1 press (first section)")
            self.first_button.wait_for_press()

        print("move_robot start")
        self.main_status_led.blink(on_time=1, off_time=2)
        init_time = time()
        self.fire.on()
        self.fc.main(init_time)

        self.main_status_led.blink(on_time=0.5, off_time=0.5)
        if self.option.waitforenter:
            input("Waiting for ENTER key instead of BUTTON2 (second section): ")
        else:
            print("Waiting for BUTTON2 press (second section)")
            self.second_button.wait_for_press()

        self.main_status_led.blink(on_time=1, off_time=2)
        self.ee.main(init_time)
        sleep(1)
        self.fire.off()
        print("move_robot end")

        if self.option.finishtime:
            input("Press ENTER key to measure finish time: ")
            print("{:.3f} sec: ".format(time() - init_time), end="")
        self.main_status_led.off()

    def recovery_robot(self):
        # Preparing
        self.recovery = Recovery()
        # Recovery Robot
        sleep_time = 0.1

        self.recovery_staus_led.on()
        print("Waiting for BUTTON1 press (recovery section)")
        self.first_button.wait_for_press()
        press_button_time = 0
        while self.first_button.is_pressed:
            press_button_time += 1
            if press_button_time >= 2.0 / sleep_time:
                self.recovery_staus_led.off()
            sleep(sleep_time)
        if press_button_time < 2 / sleep_time:
            print("recovery_robot start")
            self.recovery_staus_led.blink(on_time=1, off_time=2)
            self.recovery.main()
            print("recovery_robot end")
            self.recovery_staus_led.off()
        else:
            print("recovery was skipped")

    def main(self):
        self.move_robot()
        self.recovery_robot()
        # Start main() again for loop
        if not self.option.no_loop:
            self.main()
示例#11
0
class FDLM(object):
    """
    The class of Finite Difference L-BFGS Method(FDLM)
    algorithm to minimize a noisy function
    """
    def __init__(self, f, ecn_params, ls_params, rec_params, zeta, m, output_level, mode = "cd", tol = 1e-8):
        """
        @param ecn_params: tuple of ECNoise parameters (h, breadth, max_iter)
        @param ls_params: tuple of line search parameters (c1, c2, max_iter)
        @param rec_params: tuple of recovery parameters (gamma_1, gamma_2)
        @param m: length of L-BFGS history
        """
        self.f = f
        self.zeta = zeta
        self.eval_counter = 0
        self.ls_counter = 0
        self.rec_counter = 0
        self.noise_f = ECNoise(f, *ecn_params)
        self.ls = LineSearch(f, *ls_params)
        self.rec = Recovery(f, *rec_params, self.noise_f, self.ls)
        self.lbfgs = LBFGS(m)
        self.output_level = output_level
        self.mode = mode
        self.tol = tol

    def get_stencil_pt(self, x, h):
        """
        Compute and store the best point on the stencil

        @param x: current point
        @param h: current finite-difference interval 

        @return: (x_s, f_s): best point on the stencil S = {x_i: x_i = x + h * e_i, i = 1,...,n} and its function value
        """
        stencil_pts = []
        dim = len(x)
        for i in range(dim): #evaluate the stencil points
            basis = np.zeros(len(x))
            basis[i] = h
            stencil = x + basis
            val = self.f(stencil)
            stencil_pts.append((stencil, val))
        return min(stencil_pts, key=lambda t:t[1])

    def run(self, x):
        """
        the FDLM method

        @param: x current iterate

        @print: current iteration, current iterate, current function value, current gradient
        """
        f_val = self.f(x) #evaluate the function value at initial iterate
        noise = self.noise_f.estimate(x) #estimate noise level at initial iterate
        grad, h = fd_gradient(f, x, noise, mode=self.mode) #compute finite difference interval and the corresponding finite gradient estimate
        norm_grad_k = np.max(np.abs(grad))
        stencil_pt, stencil_val = self.get_stencil_pt(x, h) #calculate the best stencil points and its function value
        k, fval_history = 0, [f_val] #set iteration counter and function value history
        
        num_func_it = 0
        num_func_evals = 0
        step = 0
        if self.output_level >= 2:
            output_header = '%6s %23s %9s %6s %9s' % \
            ('iter', 'f',  'alpha', '#func', '||grad_f||')
            print(output_header)
            print('%6i %23.16e  %9.2e %6i %9.2e' %
              (k, f_val, step, num_func_it, norm_grad_k))

        while not self.is_convergence(f_val, fval_history, norm_grad_k, 5, self.tol) and k <= 200: #while convergence test is not satisfied
        #while not self.is_convergence(grad, f_val, 1e-5):
            #print("k", k)
            d = self.lbfgs.calculate_direction(grad) #calculate LBFGS direction
            #d = -grad
            new_pt, step, flag = self.ls.search((x, f_val, grad), d, noise=noise, mode=self.mode) #conduct linesearch to find the next iterate
            if not flag: #if linesearch failed 
                new_pt, h, noise = self.rec.recover((x, f_val, grad), h, d, (stencil_pt, stencil_val)) #call recovery mechanism
            x_new, f_val_new = new_pt 
            grad_new, _ = fd_gradient(f, x_new, noise, h, mode=self.mode) #calculate the finite-difference gradient estimator for the next iterate
            stencil_pt, stencil_val = self.get_stencil_pt(x_new, h) #calculate the new best stencil point
            s, y = x_new - x, grad_new - grad #calculate LBFGS parameter
            if self.curvature_satisfied(s, y): #if the curvature condition is satisfied
                self.lbfgs.update_history(s, y) #store new (s,y) pair
            x, f_val, grad = x_new, f_val_new, grad_new #update iterates
            norm_grad_k = np.max(np.abs(grad))
            fval_history.append(f_val) #append new function evaluations 
            k += 1 #increase iteration counter
            if self.output_level >= 2:
                if k % 10 == 0:
                    print(output_header)
                print('%6i %23.16e  %9.2e %6i %9.2e' %
              (k, f_val, step, num_func_it, norm_grad_k))
            #print("x: {}, grad: {}".format(x, grad)) 
        stats = {}
        stats['num_iter'] = k
        stats['norm_grad'] = norm_grad_k
        stats['num_func_it'] = num_func_evals

        #Final output message
        if self.output_level >= 1:
            print('')
            print('Final objective.................: %g' % f_val)
            print('||grad|| at final point.........: %g' % norm_grad_k)
            print('Number of iterations............: %d' % k)
            print('Number of function evaluations..: %d' % num_func_evals)
            print('')

        # Return output arguments
        return x, f_val, stats


    def curvature_satisfied(self, s, y):
        """
        check the curvature condition: s'y >= zeta*norm(s)*norm(y)

        @param s: x_k+1 - x_k
        @param y: grad_k+1 - grad_k

        @return: 
            TRUE: curvature condition is satisfied
            FALSE: curvature condition is not satisfied
        """
        #print(np.inner(s, y) >= self.zeta * norm(s) * norm(y))
        return np.inner(s, y) >= self.zeta * norm(s) * norm(y)

    def is_convergence(self, f_val, fval_history, norm_grad, history_len = 5, tol = 1e-6):
        """
        convergence test for current iterate: terminates if either the moving average condition or gradient condition holds

        @param f_val: current iterate function value
        @param fval_history: stored function values for past history_len iterations
        @param grad: current gradient
        @param history_len: number of function values stored
        @tol: convergence tolerance for FDLM

        @return:
            TRUE: the convergence test is satisfied
            FALSE: the convergence test is not satisfied
        """
        if len(fval_history) <= 1:
            return norm_grad <= tol
        if len(fval_history) > history_len: #if more than history_len function values have been stored
            fval_history = fval_history[1:] #move the oldest one
        fval_ma = np.mean(fval_history) #calculate the moving average of length history_len
        #check moving average condition and gradient max norm condition; if either is met, the termination tolerance is met
        return norm_grad <= tol #or abs(f_val - fval_ma) <= tol * max(1, abs(fval_ma))
示例#12
0
        kcauto_kai.refresh_config()

        if not (kcauto_kai.conduct_scheduled_sleep()
                or kcauto_kai.conduct_pause()):

            kcauto_kai.run_receive_expedition_cycle()

            kcauto_kai.run_quest_cycle()

            kcauto_kai.run_expedition_cycle()

            kcauto_kai.run_pvp_cycle()

            kcauto_kai.run_combat_cycle()

            kcauto_kai.run_repair_cycle()

            kcauto_kai.run_ship_switch_cycle()

            kcauto_kai.run_resupply_cycle()

            kcauto_kai.run_quest_cycle()

            kcauto_kai.conduct_module_sleeps()

            kcauto_kai.print_cycle_stats()

        sleep(Globals.LOOP_SLEEP_LENGTH)
    except FindFailed as e:
        Recovery.recover(kcauto_kai, config, e)