def initialize_strategy(self):
     self.initializer = Initializer(self.world)
     self.actionQueue = ActionQueue(self.world)
     self.__weather_map = WeatherMap(self.world.weather_by_cell_x_y,
                                     Constant.WEATHER_MAP_CELL_SIZE)
     self.__terrain_map = TerrainMap(self.world.terrain_by_cell_x_y,
                                     Constant.TERRAIN_MAP_CELL_SIZE)
    def prepare_simulation(self):
        r"""Set up a Fourier propagator for the simulation loop. Set the
        potential and initial values according to the configuration.

        :raise: :py:class:`ValueError` For invalid or missing input data.
        """
        # The potential instance
        potential = BlockFactory().create_potential(self.parameters)

        # Compute the position space grid points
        grid = BlockFactory().create_grid(self.parameters)

        # Construct initial values
        I = Initializer(self.parameters)
        initialvalues = I.initialize_for_fourier(grid)

        # Transform the initial values to the canonical basis
        BT = BasisTransformationWF(potential)
        BT.set_grid(grid)
        BT.transform_to_canonical(initialvalues)

        # Finally create and initialize the propagator instance
        self.propagator = FourierPropagator(potential, initialvalues, self.parameters)

        # Write some initial values to disk
        slots = self._tm.compute_number_saves()

        self.IOManager.add_grid(self.parameters, blockid="global")
        self.IOManager.add_fourieroperators(self.parameters)
        self.IOManager.add_wavefunction(self.parameters, timeslots=slots)

        self.IOManager.save_grid(grid.get_nodes(flat=True), blockid="global")
        self.IOManager.save_fourieroperators(self.propagator.get_operators())
        self.IOManager.save_wavefunction(initialvalues.get_values(), timestep=0)
Beispiel #3
0
 def __init__(self):
     self.data_initializer = Initializer('sw_templates.json')
     self.background_color = [
         color / 255
         for color in self.data_initializer.get_background_color()
     ]
     self.create_window()
     self.displayer = DisplayMaster(
         self.data_initializer.get_all_figure_list(),
         self.data_initializer.get_figure_color(),
         self.data_initializer.get_move_vector())
Beispiel #4
0
def run_board(states, filename):
    """push world states onto the Queue"""
    board = Board()
    Initializer.init_file(board, filename)
    cells = board.get_cells()
    states.put(cells)

    try:
        while True:
            board.evolve()
            cells = board.get_cells()
            states.put(cells)
    except KeyboardInterrupt:
        return
Beispiel #5
0
	def __init__(self, manager, editor):
		from Initializer import Initializer
		Initializer(manager, editor)
		from SelectedEncodingsExtractor import Extractor
		Extractor(manager, editor)
		from RowSelector import Selector
		Selector(manager, editor)
		from ModelUpdater import Updater
		Updater(manager, editor)
		from ModelDataGenerator import Generator
		Generator(manager, editor)
Beispiel #6
0
 def __init__(self, manager, editor):
     from Initializer import Initializer
     Initializer(manager, editor)
     from LanguageEmitter import Emitter
     Emitter(manager, editor)
     from LanguageSelector import Selector
     Selector(manager, editor)
     from ModelUpdater import Updater
     Updater(manager, editor)
     from DataModelGenerator import Generator
     Generator(manager, editor)
Beispiel #7
0
 def __init__(self, manager, editor):
     from Initializer import Initializer
     Initializer(manager, editor)
     from FolderChanger import Changer
     Changer(manager, editor)
     from URISelector import Selector
     Selector(manager, editor)
     from URILoader import Loader
     Loader(manager, editor)
     from ActivatorHandler import Handler
     Handler(manager, editor)
Beispiel #8
0
 def get_virtual_marker(simulated_marker, walking_data, marker_cali_matrix, R_standing_to_ground):
     segment_marker_num = marker_cali_matrix.shape[0]
     walking_data = walking_data.as_matrix()
     data_len = walking_data.shape[0]
     virtual_marker = np.zeros([data_len, 3])
     R_IMU_transform = np.zeros([3, 3, data_len])
     for i_frame in range(data_len):
         current_marker_matrix = walking_data[i_frame, :].reshape([segment_marker_num, 3])
         [R_between_frames, t] = Initializer.rigid_transform_3D(marker_cali_matrix, current_marker_matrix)
         virtual_marker[i_frame, :] = (np.dot(R_between_frames, simulated_marker) + t)
         R_IMU_transform[:, :, i_frame] = np.matmul(R_standing_to_ground, R_between_frames.T)
     return virtual_marker, R_IMU_transform
Beispiel #9
0
    def prepare_simulation(self):
        r"""Set up a Fourier propagator for the simulation loop. Set the
        potential and initial values according to the configuration.

        :raise ValueError: For invalid or missing input data.
        """
        # The potential instance
        potential = BlockFactory().create_potential(self.parameters)

        # Compute the position space grid points
        grid = BlockFactory().create_grid(self.parameters)

        # Construct initial values
        I = Initializer(self.parameters)
        initialvalues = I.initialize_for_fourier(grid)

        # Transform the initial values to the canonical basis
        BT = BasisTransformationWF(potential)
        BT.set_grid(grid)
        BT.transform_to_canonical(initialvalues)

        # Finally create and initialize the propagator instace
        self.propagator = FourierPropagator(potential, initialvalues,
                                            self.parameters)

        # Write some initial values to disk
        slots = self._tm.compute_number_saves()

        self.IOManager.add_grid(self.parameters, blockid="global")
        self.IOManager.add_fourieroperators(self.parameters)
        self.IOManager.add_wavefunction(self.parameters, timeslots=slots)

        self.IOManager.save_grid(grid.get_nodes(flat=False), blockid="global")
        self.IOManager.save_fourieroperators(self.propagator.get_operators())
        self.IOManager.save_wavefunction(initialvalues.get_values(),
                                         timestep=0)
Beispiel #10
0
	def __init__(self, manager, editor):
		from Initializer import Initializer
		Initializer(manager, editor)
		from Disabler import Disabler
		Disabler(manager, editor)
		from RowDeleter import Deleter
		Deleter(manager, editor)
		from RowActivator import Activator
		Activator(manager, editor)
		from RowSelectionMonitor import Monitor
		Monitor(manager, editor)
		from RowSelector import Selector
		Selector(manager, editor)
		from ModelUpdater import Updater
		Updater(manager, editor)
		from ModelDataGenerator import Generator
		Generator(manager, editor)
Beispiel #11
0
 def __init__(self, manager):
     from Initializer import Initializer
     Initializer(manager)
     from UpDownKeyHandler import Handler
     Handler(manager)
     from KeyboardHandler import Handler
     Handler(manager)
     from Disabler import Disabler
     Disabler(manager)
     from RowSelector import Selector
     Selector(manager)
     from RowActivator import Activator
     Activator(manager)
     from ModelUpdater import Updater
     Updater(manager)
     from ModelDataGenerator import Generator
     Generator(manager)
Beispiel #12
0
 def __init__(self, manager, editor):
     from Initializer import Initializer
     Initializer(manager, editor)
     from KeyboardHandler import Handler
     Handler(manager, editor)
     from FocusMonitor import Monitor
     Monitor(manager, editor)
     from ModelUpdater import Updater
     Updater(manager, editor)
     from ModelDataGenerator import Generator
     Generator(manager, editor)
     from RowExpansionHandler import Handler
     Handler(manager, editor)
     from RowActivationHandler import Handler
     Handler(manager, editor)
     from FocusSwitcher import Switcher
     Switcher(manager, editor)
     from FocusGrabber import Grabber
     Grabber(manager, editor)
     from SensitivityManager import Manager
     Manager(manager)
Beispiel #13
0
	def __init__(self, editor, uri, encoding):
		GObject.__init__(self)
		from Destroyer import Destroyer
		Destroyer(self, editor)
		from FileMounter import Mounter
		Mounter(self, editor)
		from GIOErrorHandler import Handler
		Handler(self, editor)
		from BusyManager import Manager
		Manager(self, editor)
		from StateNotifier import Notifier
		Notifier(self, editor)
		from ErrorManager import Manager
		Manager(self, editor)
		from TextInserter import Inserter
		Inserter(self, editor)
		from EncodingProcessor import Processor
		Processor(self, editor)
		from URIReader import Reader
		Reader(self, editor)
		from FileTypeChecker import Checker
		Checker(self, editor)
		from Initializer import Initializer
		Initializer(self, editor, uri, encoding)
Beispiel #14
0
def single_case_analysis_three_circular_ports():
    """
    Study the behavior of the rocket for a single case with ThreeCircularPort
    :return: nothing
    """

    # ------------ Generate the data-layer:

    json_interpreter = generate_data_layer(
        "Thermodynamic Data 36 bar OF 0,1 to 8,0 H2O2 87,5.json")

    # ---------- Pack the inputs:

    # Set the ox_flow
    ox_flow = 1.12

    init_parameters = {
        'combustion': {
            'geometric_params': {
                'type': ThreeCircularPorts,
                'L': 0.325,
                'portsIntialRadius': 0.016,
                'r_ext': 0.07,
                'regressionModel': Reg.TwoRegimesMarxmanAndFloodedModel
            },
            'nozzle_params': {
                'At': 0.000589,
                'expansion': 5.7,
                'lambda_e': 0.98,
                'erosion': 0
            },
            'set_nozzle_design': True,
            'design_params': {
                'gamma': 1.27,
                'p_chamber': 3600000,
                'p_exit': 100000,
                'c_star': 1500,
                'ox_flow': ox_flow,
                'OF': 5
            },
        },
    }
    simulation_parameters = {
        'combustion': {
            'ox_flow': ox_flow,
            'safety_thickness': 0.005,
            'dt': 0.01,
            'max_burn_time': 5
        },
        'mass_simulator': {
            'ox_flow': ox_flow,
            'burn_time': 'TBD',
            'system': SystemDynamic,
            'extra_filling': 0.1,
            'injection_loss': 0.5,
            'area_injection': 0.000105
        },
        'trajectory': {
            'initial_conditions': {
                'h0': 0,
                'v0': 0,
                'm0': 'TBD'
            },
            'simulation_time': 60
        }
    }

    # -------------- Generate the initializer:

    init_obj = Initializer(init_parameters=init_parameters,
                           simulation_parameters=simulation_parameters,
                           json_interpreter=json_interpreter)

    # -------------- Generate the simulation object:

    simulation_object = SimulationObject(initializer_collection=init_obj)

    # --------------- Run the simulation:

    simulation_object.run_simulation_in_batch()

    # Print the total mass
    print("\nRockets Total Mass: {0} kgs".format(
        simulation_object.mass_simulator_module.get_mass()))

    # Print the splitted masses
    print(simulation_object.mass_simulator_module)

    # # data directory
    # data_directory = "../data/data_tests"
    #
    # file_name_expression = "Tentative Design {number}.csv"
    #
    # simulation_object.export_results_to_file(file_name_expression="/".join([data_directory,
    #                                                                         file_name_expression]))
    #
    # # Save to json the mass simulator dict
    # output_file = "Tentative Design 1.json"
    # with open("/".join([data_directory, output_file]), 'w') as f:
    #     json.dump(simulation_object.mass_simulator_module.dict, f)

    # --------------- Plot the results

    simulation_object.results_collection.elements_list[
        0].combustion.plot_results()
    simulation_object.results_collection.elements_list[
        0].trajectory.plot_results()

    # Show any plots
    plt.show()
Beispiel #15
0
def visualize(DE, iterations, title='Differential Evolution'):
    results, time = DE.run(iterations)
    fig, ax = plt.subplots(figsize=(8, 8))
    for x in range(10):
        plt.plot(results[:, x], label='Vector' + str(x))
    ax.ticklabel_format(style='plain')
    plt.ylabel("Profit/Fitness")
    plt.xlabel("Iteration")
    print('Time needed:', time)
    plt.legend()
    plt.show()


# Parameter:
np = 10  #Populationsize
problemnumber = 1
F = 0.5  #Scale Factor
Cr = 0.3  #Crossover probability

ppp = PPP(problemnumber)
initializer = Initializer(ppp, np)
donorgenerator = DonorGenerator(F)
trialgenerator = TrialGenerator(Cr, problemnumber)
selector = Selector(ppp)
de = DE

DifferentialEvolution = de(ppp, initializer, donorgenerator, trialgenerator,
                           selector)

visualize(DifferentialEvolution, 500)
Beispiel #16
0
def generate_analysis_cases_multi_port_geometry():
    """ generate analysis cases generates the associated dictionaries that will be used in the
        run in batch method.
        :return InitializerCollection"""

    # ------------ Generate the data-layer:

    json_interpreter = generate_data_layer(
        "Thermodynamic Data 36 bar OF 0,1 to 8,0 H2O2 87,5.json")

    # Set the parameters over which we want to iterate
    ports_number = 4
    burn_time = 5
    external_radius = 0.08
    chamber_length = 0.4
    internal_radius = 0.01 * np.linspace(0.5, 2, 10)
    r_center = 0.01
    ox_flows = 0.001 * np.linspace(50, 400, 10)

    # Get the Initializer Collection
    collection = InitializerCollection([])
    combinations = list(itertools.product(internal_radius, ox_flows))

    for r_int, ox_flow in combinations:

        # ---------- Pack the inputs:

        init_parameters = {
            'combustion': {
                'geometric_params': {
                    'type': MultipleCircularPortsWithCircularCenter,
                    'L': chamber_length,
                    'N': ports_number,
                    'ringPortsIntialRadius': r_int,
                    'centralPortInitialRadius': r_center,
                    'r_ext': external_radius,
                    'regressionModel':
                    Reg.MarxmanAndConstantFloodingRegimeModel
                },
                'nozzle_params': {
                    'At': 0.000589,
                    'expansion': 5.7,
                    'lambda_e': 0.98,
                    'erosion': 0
                },
                'set_nozzle_design': True,
                'design_params': {
                    'gamma': 1.27,
                    'p_chamber': 3600000,
                    'p_exit': 100000,
                    'c_star': 1500,
                    'ox_flow': ox_flow,
                    'OF': 5
                },
            },
        }

        simulation_parameters = {
            'combustion': {
                'ox_flow': ox_flow,
                'safety_thickness': 0.0025,
                'dt': 0.05,
                'max_burn_time': burn_time
            },
            'mass_simulator': {
                'ox_flow': ox_flow,
                'burn_time': 'TBD',
                'system': SystemDynamic,
                'extra_filling': 0.05,
                'injection_loss': 0.5,
                'area_injection': 0.000105
            },
            'trajectory': {
                'initial_conditions': {
                    'h0': 0,
                    'v0': 0,
                    'm0': 'TBD'
                },
                'simulation_time': 60
            }
        }

        # Add initializer to the collection
        new = Initializer(init_parameters=init_parameters,
                          simulation_parameters=simulation_parameters,
                          json_interpreter=json_interpreter)
        collection.add_element(new)

    # Return the collection
    return collection
Beispiel #17
0
from Initializer import Initializer
import threading
import socket
import random
import math

__author__ = 'capt_MAKO'
__version__ = '1.0'
__since__ = 'Saturday, February 6, 2016 12:25:00'


obj = Initializer()
obj.set_version()
obj.set_phase()
version = obj.get_version()
if version == 2:
    from Tkinter import *
    from tkFileDialog import asksaveasfilename
elif version == 3:
    from tkinter import *
    from tkinter.filedialog import asksaveasfilename
def test_simulation_initializer():
    """ the method is in charge of generating the inputs for the initializer and
    instantiating it. """

    # ------------ Generate the data-layer:

    json_interpreter = generate_data_layer(
        "Thermodynamic Data 36 bar OF 0,1 to 8,0 H2O2 87,5.json")

    # ---------- Pack the inputs:

    init_parameters = {
        'combustion': {
            'geometric_params': {
                'type': OneCircularPort,
                'L': 0.5,
                'rintInitial': 0.04,
                'rext0': 0.1
            },
            'nozzle_params': {
                'At': 0.000589,
                'expansion': 5.7,
                'lambda_e': 0.98,
                'erosion': 0
            },
            'design_params': {
                'gamma': 1.27,
                'p_chamber': 3600000,
                'p_exit': 100000,
                'c_star': 1500,
                'isp': 230,
                'thrust': 30000
            },
        },
        'mass_simulator': {
            'tank_filling': 0.9
        }
    }
    simulation_parameters = {
        'combustion': {
            'ox_flow': 'TBD',
            'injection_loss': 0.5,
            'area_injection': 0.000105,
            'safety_thickness': 0.005,
            'dt': 0.05
        },
        'trajectory': {
            'initial_conditions': {
                'h0': 0,
                'v0': 0,
                'm0': 'TBD'
            },
            'simulation_time': 40
        }
    }

    # -------------- Generate the initializer:

    init_obj = Initializer(init_parameters=init_parameters,
                           simulation_parameters=simulation_parameters,
                           json_interpreter=json_interpreter)

    # -------------- Generate the simulation object:

    simulation_object = SimulationObject(initializer_collection=init_obj)

    # --------------- Run the simulation:

    simulation_object.run_simulation_in_batch()

    # --------------- Plot the results

    # simulation_object.combustion_module.plot_results()
    # simulation_object.trajectory_module.plot_results()

    # print("Hello World"

    # Export results to csv files

    # data directory
    data_directory = "..\data\data_tests"

    file_name_expression = "Griffon Output Test {number}.csv"

    simulation_object.export_results_to_file(
        file_name_expression="/".join([data_directory, file_name_expression]))

    # Plot results

    simulation_object.results_collection.elements_list[
        0].combustion.plot_results()
    simulation_object.results_collection.elements_list[
        0].trajectory.plot_results()
# this project is designed to process the opensource gait database
from gaitanalysis.motek import DFlowData
from const import *
from DatabaseInfo import *
from Initializer import Initializer
from SaveData import SaveData

speed_num = SPEEDS.__len__()

data_path = 'D:\Tian\Research\Projects\ML Project\gait_database\GaitDatabase\data\\'
processed_data_path = 'D:\Tian\Research\Projects\ML Project\gait_database_processed\GaitDatabase\data\\'
my_database_info = DatabaseInfo()
my_initializer = Initializer()
necessary_columns = my_database_info.get_necessary_columns()
marker_column_num = my_database_info.get_marker_column_num(
)  # get column numbers
force_column_num = my_database_info.get_force_column_num()
all_column_names = my_database_info.get_all_column_names()

for i_sub in range(12):
    print('sub: ' + str(i_sub))
    for i_speed in range(speed_num):
        file_names = my_database_info.get_file_names(sub=i_sub,
                                                     speed=i_speed,
                                                     path=data_path)
        trial_data = DFlowData(file_names[0], file_names[1], file_names[2])
        event_dictionary = trial_data.meta['trial']['events']

        trial_data.clean_data(interpolation_order=2)
        # events: A: Force Plate Zeroing    B: Calibration Pose     C: First Normal Walking
        # D: Longitudinal Perturbation      E: Second Normal Walking    F: Unloaded End
Beispiel #20
0
# for debugging

from Initializer import Initializer
from DonorGenerator import DonorGenerator
from TrialGenerator import TrialGenerator
from Selector import Selector
from DE import DE
"""
Step 1: Read values of the control parameters of DE: scale
factor F, crossover rate Cr, and the population size NP from
user.
"""

# Parameter:
# np
# (xmin =)
# (xmax =)
# problemnumber =
# F =
# Cr =

#initializer = Initializer(xmin, xmax, np)
initializer = Initializer(problemnumber, Np)
donorgenerator = DonorGenerator(F)
trialgenerator = TrialGenerator(Cr)
selector = Selector
de = DE

DifferentialEvolution = de(initializer, donorgenerator, trialgenerator,
                           selector)
class MyStrategy:
    game = None
    world = None
    me = None

    __weather_map = None
    __terrain_map = None

    vehicleById = {}
    updateTickByVehicleId = {}
    updatedVehicleXY = {}
    allVehicles = []

    initializer = None
    actionQueue = None

    strategy = None

    _sos_mode = False

    def initialize_strategy(self):
        self.initializer = Initializer(self.world)
        self.actionQueue = ActionQueue(self.world)
        self.__weather_map = WeatherMap(self.world.weather_by_cell_x_y,
                                        Constant.WEATHER_MAP_CELL_SIZE)
        self.__terrain_map = TerrainMap(self.world.terrain_by_cell_x_y,
                                        Constant.TERRAIN_MAP_CELL_SIZE)

    def initialize_tick(self):
        self.updatedVehicleXY = {}
        for vehicle in self.world.new_vehicles:
            self.vehicleById[vehicle.id] = vehicle
            self.updateTickByVehicleId[vehicle.id] = self.world.tick_index
        for vehicleUpdate in self.world.vehicle_updates:
            vehicleId = vehicleUpdate.id
            if vehicleUpdate.durability == 0:
                self.vehicleById.pop(vehicleId)
                self.updateTickByVehicleId.pop(vehicleId)
            else:
                x_old, y_old = self.vehicleById[vehicleId].x, self.vehicleById[
                    vehicleId].y
                self.vehicleById[vehicleId].update(vehicleUpdate)
                x_new, y_new = self.vehicleById[vehicleId].x, self.vehicleById[
                    vehicleId].y
                if self.vehicleById[vehicleId].player_id == self.me.id and (
                        x_old != x_new or y_old != y_new):
                    self.updatedVehicleXY[vehicleId] = (x_new - x_old,
                                                        y_new - y_old)
                self.updateTickByVehicleId[vehicleId] = self.world.tick_index
        self.allVehicles = list(self.vehicleById.values())

    def execute_action(self, move: Move, action: dict):
        for field, value in action.items():
            setattr(move, field, value)
        return True

    def execute_delayed_action(self, move: Move, world: World):
        action = self.actionQueue.pop(world)
        if action is None:
            return False
        return self.execute_action(move, action)

    def move(self, me: Player, world: World, game: Game, move: Move):
        self.game = game
        self.world = world
        self.me = me
        if world.tick_index == 0:
            self.initialize_strategy()
        self.initialize_tick()

        if self.strategy is None:
            if self.initializer.current_step not in [
                    Initializer.STEP_STOP, Initializer.STEP_INTERRUPT_STOP
            ]:
                self.initializer.prepare_step(self.me, self.world,
                                              self.allVehicles)
                self.initializer.perform_current_step(self.actionQueue,
                                                      self.updatedVehicleXY)
            elif self.initializer.current_step == Initializer.STEP_INTERRUPT_STOP:
                self.strategy = NaiveStrategy(self.actionQueue, self.world,
                                              self.__weather_map,
                                              self.__terrain_map)
            else:
                self.strategy = NaiveStrategy(self.actionQueue, self.world,
                                              self.__weather_map,
                                              self.__terrain_map)

        if self.strategy:
            #if False:
            if not self._sos_mode:
                if self.__save_our_souls(world):
                    return
            else:
                if self.__comeback_after_strike(world):
                    return

        if me.remaining_action_cooldown_ticks > 0:
            return
        if self.execute_delayed_action(move, world):
            return
        self.determine_following_actions()
        self.execute_delayed_action(move, world)

    def determine_following_actions(self):
        if self.strategy is None:
            return
        self.strategy.initialize_tick(self.game, self.world, self.me,
                                      self.allVehicles,
                                      self.updateTickByVehicleId)
        self.strategy.determine_following_actions(self.updatedVehicleXY)

    def __save_our_souls(self, world: World):
        opponent = world.get_opponent_player()
        next_nuclear_strike_tick = opponent.next_nuclear_strike_tick_index
        if next_nuclear_strike_tick == -1:
            return False
        f = Formation(self.allVehicles, self.me, ownership=Ownership.ALLY)
        x = opponent.next_nuclear_strike_x
        y = opponent.next_nuclear_strike_y

        next_nuclear_strike_vehicle_id = opponent.next_nuclear_strike_vehicle_id
        if next_nuclear_strike_vehicle_id == -1:
            return False
        if next_nuclear_strike_vehicle_id not in self.vehicleById:
            return False
        is_aerial = self.vehicleById[next_nuclear_strike_vehicle_id].aerial

        kill_factor = f.calc_nuclear_kill_factor(x, y)
        if kill_factor['total_damage'] < 700 and kill_factor[
                'survived'] > kill_factor['killed'] * 5 and not is_aerial:
            return False

        from_x, from_y = self.vehicleById[
            next_nuclear_strike_vehicle_id].x, self.vehicleById[
                next_nuclear_strike_vehicle_id].y
        sos_vector = (y - from_y, x - from_x)
        sos_vector_norm = 120 / math.hypot(sos_vector[0], sos_vector[1])
        sos_vector = (sos_vector[0] * sos_vector_norm,
                      sos_vector[1] * sos_vector_norm)
        topleft = f.find_topleft()
        bottomright = f.find_bottomright()
        if topleft[0] + sos_vector[0] < 0 or topleft[1] + sos_vector[1] < 0:
            sos_vector = (-sos_vector[0], -sos_vector[1])
        elif bottomright[0] + sos_vector[0] >= self.world.height or bottomright[
                1] + sos_vector[1] >= self.world.width:
            sos_vector = (-sos_vector[0], -sos_vector[1])
        self.actionQueue.clear()
        self.actionQueue.push(Action.move(sos_vector[1], sos_vector[0], 0.3))
        self._sos_mode = True
        return True

    def __comeback_after_strike(self, world: World):
        opponent = world.get_opponent_player()
        next_nuclear_strike_tick = opponent.next_nuclear_strike_tick_index
        if next_nuclear_strike_tick != -1:
            return False
        if not self.actionQueue.is_action_in_queue(ActionType.MOVE):
            self.actionQueue.push(Action.move(0, 0))
        else:
            self.actionQueue.clear()
        self._sos_mode = False
        return True
Beispiel #22
0
def main():
    parser = argparse.ArgumentParser(
        description='Initialize or update a Postgres database with OSM data')

    parser.add_argument(
        '-i',
        '--init',
        dest='initialize',
        action='store_const',
        const=True,
        default=False,
        help='Initialize the database and supply a planet file')
    parser.add_argument(
        '-u',
        '--update',
        dest='update',
        action='store_const',
        const=True,
        default=False,
        help='Update and initialized database by downloading updates')

    parser.add_argument('-f',
                        '--filter',
                        dest='filter_path',
                        default='./config/filter.json',
                        help='Filter file')

    parser.add_argument('-b',
                        '--base_url',
                        dest='base_url',
                        default='https://planet.osm.ch/replication',
                        help='Planet website. Used both in init and update')
    parser.add_argument(
        '-m',
        '--mode',
        dest='mode',
        default='hour',
        help='replication mode (hour, minute...). Used both in init and update'
    )

    parser.add_argument('-ph',
                        '--psqlhost',
                        dest='psqlhost',
                        required=True,
                        help='Postgres host')
    parser.add_argument('-ppo',
                        '--psqlport',
                        dest='psqlport',
                        default=5432,
                        help='Postgres port')
    parser.add_argument('-pd',
                        '--psqldb',
                        dest='psqldb',
                        required=True,
                        help='Postgres database')
    parser.add_argument('-pu',
                        '--psqluser',
                        dest='psqluser',
                        required=True,
                        help='Postgres user')
    parser.add_argument('-pp',
                        '--psqlpassword',
                        dest='psqlpassword',
                        required=True,
                        help='Postgres password')

    parser.add_argument(
        '-p',
        '--planet',
        dest='planet_path',
        default=None,
        help='Planet file in pbf format. Option valid only if --init is used')

    parser.add_argument('-d',
                        '--debug',
                        dest='debug',
                        action='store_const',
                        const=True,
                        default=False,
                        help='Debug mode')

    args = parser.parse_args()

    if args.initialize and args.update:
        return print('Select either --init or --update, not both')
    if not args.initialize and not args.update:
        return print('Select one of --init or --update')
    if args.initialize and args.planet_path is None:
        return print('To initialize, we need a planet file (-p)')
    if args.update and args.planet_path:
        print('Ignoring planet file during updatess')

    setup_logging(args.debug)
    logging.debug('Options parsed')

    logging.info(f'base url: {args.base_url}, mode: {args.mode}')

    filt = Filter(args.filter_path)
    if filt is None:
        return

    psql = PSQL(args.psqlhost, args.psqlport, args.psqldb, args.psqluser,
                args.psqlpassword)

    if args.initialize:
        try:
            initializer = Initializer(args, psql, filt)
            initializer.start()
        except:
            logging.critical('Something came up.', exc_info=True)
            return
    psql.stop()
    logging.info('Stopping PSQL. It might take some seconds')
Beispiel #23
0
def single_case_analysis_one_port_image_geometry():
    """ case study for image geometry design """

    # ------------ Generate the data-layer:

    json_interpreter = generate_data_layer()

    # ------------ Generate the Fourier Coefficients:
    #
    r = 0.2
    br = 0.3
    delta = 0.17
    n_coefs = 100
    period = 1
    a_s, b_s = generate_fourier_coefficients(n_coefs, period, my_fun, br, r,
                                             delta)

    # n_coefs = 100
    # period = 1
    # a_s, b_s = generate_fourier_coefficients(n_coefs, period, my_fun_2, delta1, delta2)
    # delta1, delta2 = 0.12, 0.3

    # ---------- Pack the inputs:

    # Define the oxidizer flow
    ox_flow = 1.2

    init_parameters = {
        'combustion': {
            'geometric_params': {
                'type': SinglePortImageGeometry,
                'L': 0.40,
                'externalRadius': 0.05,
                'imagePixelSize': 2048,
                'imageMeterSize': 0.1
            },
            'shape_params': {
                'a': a_s,
                'b': b_s,
                'baseRadius': 0.032,
                'branches': 12,
                'impact': 0.8,
                'n': 50
            },
            'nozzle_params': {
                'At': 0.000589,
                'expansion': 5.7,
                'lambda_e': 0.98,
                'erosion': 0
            },
            'set_nozzle_design': False,
            'design_params': {
                'gamma': 1.27,
                'p_chamber': 3200000,
                'p_exit': 100000,
                'c_star': 1500,
                'ox_flow': ox_flow,
                'OF': 5
            },
        },
    }
    simulation_parameters = {
        'CombustionModel': CombustionObjectImage,
        'combustion': {
            'ox_flow': ox_flow,
            'safety_thickness': 0.004,
            'dt': 0.05,
            'max_burn_time': 5
        },
        'mass_simulator': {
            'ox_flow': ox_flow,
            'burn_time': 'TBD',
            'extra_filling': 0.05,
            'injection_loss': 0.5,
            'area_injection': 0.000105,
            'system': SystemDynamic
        },
        'trajectory': {
            'initial_conditions': {
                'h0': 0,
                'v0': 0,
                'm0': 'TBD'
            },
            'simulation_time': 60
        }
    }

    # -------------- Generate the initializer:

    init_obj = Initializer(init_parameters=init_parameters,
                           simulation_parameters=simulation_parameters,
                           json_interpreter=json_interpreter)

    # -------------- Generate the simulation object:

    simulation_object = SimulationObject(initializer_collection=init_obj)
    print("Minimum Thickness Before: {x:5.5f} mm \n".format(
        x=1000 *
        simulation_object.combustion_module.geometry.min_bloc_thickness()))

    # -------------- Generate deep copy of geometry object:

    geometry_object_original = deepcopy(
        simulation_object.combustion_module.geometry)

    # --------------- Run the simulation:

    simulation_object.run_simulation_in_batch()
    print("Minimum Thickness After: {x:5.5f} mm \n".format(
        x=1000 *
        simulation_object.combustion_module.geometry.min_bloc_thickness()))

    # Print the total mass
    print("\nRockets Total Mass: {0} kgs".format(
        simulation_object.mass_simulator_module.get_mass()))

    # Print the splitted masses
    print(simulation_object.mass_simulator_module)

    # Print combustion results
    print(simulation_object.combustion_module)

    # --------------- Export results to csv files:

    # data directory
    data_directory = "../data/data_tests"

    file_name_expression = "Griffon Output Test {number}.csv"

    simulation_object.export_results_to_file(
        file_name_expression="/".join([data_directory, file_name_expression]))

    # --------------- Plot the results

    simulation_object.results_collection.elements_list[
        0].combustion.plot_results()
    simulation_object.results_collection.elements_list[
        0].trajectory.plot_results()

    # ---------------- Plot the geometries before and after:

    geometry_object_original.export_geometry(
        file_name="../Design/Design Files/original_geometry.txt")
    simulation_object.combustion_module.geometry.export_geometry(
        file_name="../Design/Design Files/geometry_after_burn.txt")
    geometry_object_original.draw_geometry()
    simulation_object.combustion_module.geometry.draw_geometry()
Beispiel #24
0
def single_case_analysis_one_port_review():
    """
    Study the behavior of the rocket for a single case with OneCircularPort
    :return: nothing
    """

    # ------------ Generate the data-layer:

    json_interpreter = generate_data_layer(
        "Thermodynamic Data 36 bar OF 0,1 to 8,0 H2O2 87,5.json")

    # ---------- Pack the inputs:

    ox_flow = 1.09

    init_parameters = {
        'combustion': {
            'geometric_params': {
                'type': OneCircularPort,
                'L': 0.325,
                'rintInitial': 0.03,
                'rext0': 0.05,
                'regressionModel': Reg.MarxmanAndConstantFloodingRegimeModel
            },
            'nozzle_params': {
                'At': 0.000589,
                'expansion': 5.7,
                'lambda_e': 0.98,
                'erosion': 0
            },
            'set_nozzle_design': True,
            'design_params': {
                'gamma': 1.27,
                'p_chamber': 3600000,
                'p_exit': 100000,
                'c_star': 1580,
                'ox_flow': ox_flow,
                'OF': 5.5
            },
        },
    }
    simulation_parameters = {
        'combustion': {
            'ox_flow': ox_flow,
            'safety_thickness': 0.005,
            'dt': 0.01,
            'max_burn_time': 4.75
        },
        'mass_simulator': {
            'ox_flow': ox_flow,
            'burn_time': 'TBD',
            'system': SystemStatic,
            'system_dict': {
                'dry_mass': 12.35 + 20 + 1.3,
                'pressurizer_mass': 0.17,
                'oxidizer_mass': 'TBD',
                'fuel_mass': 'TBD'
            },
            'extra_filling': 0.1,
            'injection_loss': 0.5,
            'area_injection': 0.000105
        },
        'trajectory': {
            'initial_conditions': {
                'h0': 0,
                'v0': 0,
                'm0': 'TBD'
            },
            'simulation_time': 60
        }
    }

    # -------------- Generate the initializer:

    init_obj = Initializer(init_parameters=init_parameters,
                           simulation_parameters=simulation_parameters,
                           json_interpreter=json_interpreter)

    # -------------- Generate the simulation object:

    simulation_object = SimulationObject(initializer_collection=init_obj)

    # --------------- Run the simulation:

    simulation_object.run_simulation_in_batch()

    # Print the total mass
    print("\nRockets Total Mass: {0} kgs".format(
        simulation_object.mass_simulator_module.get_mass()))

    # Print the splitted masses
    print(simulation_object.mass_simulator_module)

    # Print combustion results
    print(simulation_object.combustion_module)

    # Print Trajectory results
    print(simulation_object.trajectory_module)

    # --------------- Plot the results

    simulation_object.results_collection.elements_list[
        0].combustion.plot_results()
    simulation_object.results_collection.elements_list[
        0].trajectory.plot_results()

    # # data directory
    # data_directory = "../Design/Design Files/Proposed Designs/Single Port Geometry/"
    #
    # file_name_expression = "Tentative Design Single Port Reviewed {number}.csv"
    #
    # simulation_object.export_results_to_file(file_name_expression="/".join([data_directory,
    #                                                                         file_name_expression]))
    #
    # # Save to json the mass simulator dict
    # output_file = "Tentative Design Single Port Reviewed 1.json"
    # with open("/".join([data_directory, output_file]), 'w') as f:
    #     json.dump(simulation_object.mass_simulator_module.dict, f)

    # Show any plots
    plt.show()
Beispiel #25
0
            iteration_best.append(max(evaluations))

            #updating pheromone matrix
            self.pheromone_matrix = self.evaporator.evaporate(
                self.pheromone_matrix)
            self.pheromone_matrix = self.intensificator.intensify(
                self.pheromone_matrix, solutions)



        return np.array(self.best_solutions_scores), np.array(self.solutions_generations), \
               np.array(self.evaluations_generations)


taskinitializer = Taskinitializer(1)
initializer = Initializer()
solutiongenerator = SolutionGenerator(alpha=1, beta=1, num_of_ants=20)
evaporator = Evaporator(rho=0.1)
intensificator = Intensificator(delta=0.5)

antco = ACO(taskinitializer,
            initializer,
            solutiongenerator,
            evaporator,
            intensificator,
            50,
            printing=False)
solutions, scores, best_solutions = antco.run()

plt.plot(best_solutions)
plt.ylabel('')
def test_simulation_initializer(isImageBased):
    """ the method is in charge of generating the inputs for the initializer and
    instantiating it. """

    # ------------ Generate the data-layer:

    json_interpreter = generate_data_layer("DataLayerONERATests_Hycom14.json")

    # ---------- Pack the inputs:

    init_parameters = {
                        'combustion': {
                                       'geometric_params': {'type': SinglePortImageGeometry, 'L': 0.4,
                                                            'externalRadius': 0.05, 'imagePixelSize': 1024,
                                                            'imageMeterSize': 0.1},

                                       'shape_params': {'a': [0,1], 'b': [1, 0, 0],
                                                            'baseRadius': 0.036, 'branches': 10, 'impact': 0.1,
                                                            'n': 40},

                                       'nozzle_params': {'At': 0.000589, 'expansion': 5.7, 'lambda_e': 0.98,
                                                         'erosion': 0},

                                       'set_nozzle_design': True,

                                       'design_params': {'gamma': 1.27, 'p_chamber': 3200000, 'p_exit': 100000,
                                                         'c_star': 1500, 'ox_flow': 1.2, 'OF': 5},
                                      },


                      }
    simulation_parameters = {
                              'combustion': {'ox_flow': 1, 'safety_thickness': 0.005, 'dt': 0.05,
                                             'max_burn_time': None},

                              'mass_simulator': {'ox_flow': 1, 'burn_time': 'TBD', 'extra_filling': 0.05,
                                                 'injection_loss': 0.5, 'area_injection': 0.000105, 'system' : SystemDynamic},

                              'trajectory': {'initial_conditions': {'h0': 0, 'v0': 0, 'm0': 'TBD'},
                                             'simulation_time': 100}
                            }

    # -------------- Generate the initializer:

    init_obj = Initializer(init_parameters=init_parameters,
                           simulation_parameters=simulation_parameters,
                           json_interpreter=json_interpreter)

    # -------------- Generate the simulation object:

    simulation_object = SimulationObject(isImageBased, initializer_collection=init_obj)

    # --------------- Run the simulation:

    simulation_object.run_simulation_in_batch(isImageBased)

    # Print the total mass
    print("\nRockets Total Mass: {0} kgs".format(simulation_object.mass_simulator_module.get_mass()))

    # Print the splitted masses
    print(simulation_object.mass_simulator_module)

    # --------------- Export results to csv files:

    # data directory
    data_directory = "../data/data_tests"

    file_name_expression = "Griffon Output Test {number}.csv"

    simulation_object.export_results_to_file(file_name_expression="/".join([data_directory,
                                                                            file_name_expression]))

    # --------------- Plot the results

    simulation_object.results_collection.elements_list[0].combustion.plot_results()
    simulation_object.results_collection.elements_list[0].trajectory.plot_results()
Beispiel #27
0
 def __init__(self):
     GObject.__init__(self)
     from Initializer import Initializer
     Initializer(self)
     from Monitor import Monitor
     Monitor(self)
Beispiel #28
0
 def rigid_transform_3D(A, B):
     return Initializer.rigid_transform_3D(A, B)
Beispiel #29
0
class WindowMaster:
    """
        A class for managing program window. It collects data, initializes window, draws figure, manages keyboard actions.
        ...
        Attributes
        ----------
        background_color: list
            background color stored as rgb unsigned byte

        data_initializer: Initializer
            object of class Initializer used to read and store input data
        
        displayer: DisplayMaster
            object of class DisplayMaster used to draw main figure
        ...
        Methods
        ----------
        create_window():
            Create window, set background color and grid size

        start_drawing():
            Start main loop.

        reshape_window(width, heigth):
            Manage changing window's size

        keyboardControl():
            Managing keyboard actions
    """
    def create_window(self):
        glutInit(sys.argv)
        glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
        glutInitWindowSize(800, 800)
        glutInitWindowPosition(320, 100)
        glutCreateWindow("lab1")
        glClearColor(self.background_color[0], self.background_color[1],
                     self.background_color[2], 1.0)
        gluOrtho2D(-20.0, 20.0, -20.0, 20.0)

    def __init__(self):
        self.data_initializer = Initializer('sw_templates.json')
        self.background_color = [
            color / 255
            for color in self.data_initializer.get_background_color()
        ]
        self.create_window()
        self.displayer = DisplayMaster(
            self.data_initializer.get_all_figure_list(),
            self.data_initializer.get_figure_color(),
            self.data_initializer.get_move_vector())

    def startDrawing(self):
        glutDisplayFunc(self.displayer.render_figure)
        glutReshapeFunc(self.reshapeWindow)
        glutKeyboardFunc(self.keyboardControl)
        glutMainLoop()

    def reshapeWindow(self, w, h):

        # preventing dividing by zero if window height is 0
        if h == 0:
            h = 1

        # coefficient to maintain the proportions of the picture when resizing the window
        coef = float(w) / h
        glViewport(0, 0, w, h)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        if w > h:
            gluOrtho2D(-20.0 * coef, 20.0 * coef, -20.0, 20.0)
        else:
            gluOrtho2D(-20.0, 20.0, -20.0 / coef, 20.0 / coef)

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

    def keyboardControl(self, key, x1, y1):

        # pressed key code
        key = ord(key)

        # moving picture by pressing D/W
        if key == 100 or key == 119:
            DisplayMaster.x_center_coordinate = DisplayMaster.x_center_coordinate + DisplayMaster.move_vector[
                0]
            DisplayMaster.y_center_coordinate = DisplayMaster.y_center_coordinate + DisplayMaster.move_vector[
                1]

        # moving picture by pressing A/S
        if key == 97 or key == 115:
            DisplayMaster.x_center_coordinate = DisplayMaster.x_center_coordinate - DisplayMaster.move_vector[
                0]
            DisplayMaster.y_center_coordinate = DisplayMaster.y_center_coordinate - DisplayMaster.move_vector[
                1]

        # zoom in
        if key == 43:
            DisplayMaster.scaling_coef = DisplayMaster.scaling_coef * 1.5

        # zoom out
        if key == 45:
            DisplayMaster.scaling_coef = DisplayMaster.scaling_coef / 1.5
        glutPostRedisplay()
Beispiel #30
0
from Map import Map
from Initializer import Initializer

my_map = Map('start')
my_game = Initializer(my_map)
my_game.play()
Beispiel #31
0
#-*- coding:utf-8 -*-
"""
    Description:
    Author: shelldream
    Date:
"""
import sys
reload(sys).setdefaultencoding('utf-8')

sys.path.append("../")
import Initializer.Initializer as Init
import tensorflow as tf

if __name__ == "__main__":
    initializer = Init.Initializer("w", [128, 64], initializer="")
    w = initializer.init()
    print w
# for debugging

from Initializer import Initializer
from DonorGenerator import DonorGenerator
from TrialGenerator import TrialGenerator
from Selector import Selector
from DE import DE
"""
Step 1: Read values of the control parameters of DE: scale
factor F, crossover rate Cr, and the population size NP from
user.
"""

# Parameter:
# np
# xmin =
# xmax =
# F =
# Cr =

initializer = Initializer(xmin, xmax, np)
donorgenerator = DonorGenerator(F)
trialgenerator = TrialGenerator(Cr)
selector = Selector
de = DE

DifferentialEvolution = de(initializer, donorgenerator, trialgenerator,
                           selector)