当前位置: 首页>>代码示例>>Python>>正文


Python Stopwatch.start方法代码示例

本文整理汇总了Python中stopwatch.Stopwatch.start方法的典型用法代码示例。如果您正苦于以下问题:Python Stopwatch.start方法的具体用法?Python Stopwatch.start怎么用?Python Stopwatch.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在stopwatch.Stopwatch的用法示例。


在下文中一共展示了Stopwatch.start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_largescale

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
def test_largescale():
    s = Stopwatch()
    integration_factor = 5
    device_map = device_parser.build_device_map(device_parser.parse_data('test.xml'))
    test_size = 10000
    histogram = OrderedDict()
    
    for i in range(5):
        time = 0.0

        for j in range(5):
            s.start()
            generate_test_input(device_map, test_size, file_name='test_input1.csv')
            s.stop()
            print('Generating test input of size {}: '.format(test_size), s.read())
        
            s.reset()
            s.start()
            analyze_data_nograph('csvs/test_input1.csv', integration_factor, device_map)
            s.stop()
            print('Processing input of size {}:     '.format(test_size), s.read())

            time += s.read()
            s.reset()
            
        print('Average time for input of size {}:  '.format(test_size), time/5)
        histogram[test_size] = time/5
        
        test_size *= 2

    print(histogram)
    
    for i,j in histogram.items():
        print(' size | time ')
        print('{0:5d}|{1:5f}'.format(i,j))
开发者ID:ksegarra,项目名称:PLSim,代码行数:37,代码来源:sim_test.py

示例2: RaisArmTime

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
class RaisArmTime(Command):

    def __init__(self, robot, raise_speed, stop_time, name=None, timeout=None):
        '''
        Constructor
        '''
        super().__init__(name, timeout)
        self._robot = robot
        self._raise_speed = raise_speed
        self._stop_time = stop_time
        self.requires(robot.arm)
        self._stopwatch = Stopwatch()

    def initialize(self):
        """Called before the Command is run for the first time."""
        self._stopwatch.start()

    def execute(self):
        """Called repeatedly when this Command is scheduled to run"""
        self._robot.arm.move_arm(self._raise_speed)

    def isFinished(self):
        """Returns true when the Command no longer needs to be run"""
        return self._stopwatch.elapsed_time_in_secs() >= self._stop_time

    def end(self):
        """Called once after isFinished returns true"""
        self._robot.arm.move_arm(0)

    def interrupted(self):
        """Called when another command which requires one or more of the same subsystems is scheduled to run"""
        self.end()
开发者ID:TechnoJays,项目名称:robot2016,代码行数:34,代码来源:raise_arm_time.py

示例3: test_timeout

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
    def test_timeout(self):
        # preset future - should return within timeout
        f = future.Future.preset(3)
        self.assertEqual(f.get(100),3)

        # unset future - should raise exception
        timeout = 1 # timeout in seconds
        f = future.Future()
        stopwatch = Stopwatch()
        stopwatch.start()
        self.assertRaises(future.FutureTimeoutException,f.get,timeout*1000)
        duration = stopwatch.duration()
        self.assert_(0.9*timeout < duration < 1.3*timeout, 'duration=%s' % duration)  
开发者ID:idobarkan,项目名称:my-code,代码行数:15,代码来源:test_future.py

示例4: DriveTime

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
class DriveTime(Command):
    '''
    classdocs
    '''
    _stopwatch = None
    _start_time = None
    _duration = None
    _speed = None
    _ramp_threshold = None

    def __init__(self, robot, duration, speed, ramp_threshold, name=None, timeout=None):
        '''
        Constructor
        '''
        super().__init__(name, timeout)
        self.robot = robot;
        self.requires(robot.drivetrain)
        self._stopwatch = Stopwatch()
        self._duration = duration
        self._speed = speed
        self._ramp_threshold = ramp_threshold

    def initialize(self):
        """Called before the Command is run for the first time."""
        # Start stopwatch
        self._stopwatch.start()
        return Command.initialize(self)

    def execute(self):
        """Called repeatedly when this Command is scheduled to run"""
        speed = self._speed
        time_left = self._duration - self._stopwatch.elapsed_time_in_secs()
        if (time_left < self._ramp_threshold):
            speed = speed * time_left / self._ramp_threshold
        self.robot.drivetrain.arcade_drive(speed, 0.0)
        return Command.execute(self)

    def isFinished(self):
        """Returns true when the Command no longer needs to be run"""
        # If elapsed time is more than duration
        return self._stopwatch.elapsed_time_in_secs() >= self._duration

    def end(self):
        """Called once after isFinished returns true"""
        self._stopwatch.stop()
        # Stop driving
        self.robot.drivetrain.arcade_drive(0.0, 0.0)

    def interrupted(self):
        """Called when another command which requires one or more of the same subsystems is scheduled to run"""
        self.end()
开发者ID:TechnoJays,项目名称:robot2016,代码行数:53,代码来源:drive_time.py

示例5: evaluate

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
 def evaluate(self,times=None):
     results = []
     s = Stopwatch()
     times = times if times != None else self._times
     for i in range(times):
         self._setup()
         s.reset()
         gc.disable()
         s.start()
         self._code()
         gc.enable()
         results.append(s.read())
     self._evaluate_results = [(min(results),sum(results)/times,max(results))] + [results]
     return self._evaluate_results
开发者ID:dblam,项目名称:Duy-s-Python-Projects,代码行数:16,代码来源:performance.py

示例6: __init__

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
class FpsMeter:
    print_fps = True
    
    def __init__(self, name=None):
        if name is None:
            self._name_argument_string = ""
        else:
            self._name_argument_string = "(%s)" % name
        self._fps_history = collections.deque(maxlen=10)
        self._previous_time = None
        self._previous_calculated_fps_time = None
        self._stopwatch = Stopwatch()
        self._fps = None

    def update(self):
        self._now = self._stopwatch.get_elapsed_time()
        if self._previous_time is None:
            self._stopwatch.start()
        else:
            self._update_fps_history()
            self._update_fps_if_timely()
        self._previous_time = self._now

    def _update_fps_history(self):
        time_increment = self._now - self._previous_time
        fps = 1.0 / time_increment
        self._fps_history.append(fps)

    def _update_fps_if_timely(self):
        if self._previous_calculated_fps_time:
            if (self._stopwatch.get_elapsed_time() - self._previous_calculated_fps_time) > 1.0:
                self._calculate_fps()
        else:
            self._calculate_fps()

    def _calculate_fps(self):
        self._fps = sum(self._fps_history) / len(self._fps_history)
        if self.print_fps:
            print "FPS%s: %.1f" % (self._name_argument_string, self._fps)
        self._previous_calculated_fps_time = self._stopwatch.get_elapsed_time()

    def get_fps(self):
        return self._fps
开发者ID:gaborpapp,项目名称:AIam,代码行数:45,代码来源:fps_meter.py

示例7: add_parser_arguments

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
class Orchestra:
    SAMPLE_RATE = 44100
    PLAYABLE_FORMATS = ['mp3', 'flac', 'wav', 'm4b']
    JACK = "jack"
    SSR = "ssr"

    @staticmethod
    def add_parser_arguments(parser):
        parser.add_argument("--rt", action="store_true", dest="realtime")
        parser.add_argument("-t", "--torrent", dest="torrentname", default="")
        parser.add_argument("-z", "--timefactor", dest="timefactor", type=float, default=1)
        parser.add_argument("--start", dest="start_time", type=float, default=0)
        parser.add_argument("-q", "--quiet", action="store_true", dest="quiet")
        parser.add_argument("--pretend-sequential", action="store_true", dest="pretend_sequential")
        parser.add_argument("--gui", action="store_true", dest="gui_enabled")
        parser.add_argument("--predecode", action="store_true", dest="predecode", default=True)
        parser.add_argument("--file-location", dest="file_location", default=DOWNLOAD_LOCATION)
        parser.add_argument("--fast-forward", action="store_true", dest="ff")
        parser.add_argument("--fast-forward-to-start", action="store_true", dest="ff_to_start")
        parser.add_argument("--quit-at-end", action="store_true", dest="quit_at_end")
        parser.add_argument("--loop", dest="loop", action="store_true")
        parser.add_argument("--max-passivity", dest="max_passivity", type=float)
        parser.add_argument("--max-pause-within-segment", dest="max_pause_within_segment", type=float)
        parser.add_argument("--looped-duration", dest="looped_duration", type=float)
        parser.add_argument("-o", "--output", dest="output", type=str, default=Orchestra.JACK)
        parser.add_argument("--include-non-playable", action="store_true")
        parser.add_argument("-f", "--file", dest="selected_files", type=int, nargs="+")
        parser.add_argument("--no-synth", action="store_true")
        parser.add_argument("--locate-peers", action="store_true")

    _extension_re = re.compile('\.(\w+)$')

    def __init__(self, sessiondir, tr_log, options):
        self.options = options
        self.sessiondir = sessiondir
        self.tr_log = tr_log
        self.realtime = options.realtime
        self.timefactor = options.timefactor
        self.quiet = options.quiet
        self.predecode = options.predecode
        self.file_location = options.file_location
        self._loop = options.loop
        self._max_passivity = options.max_passivity
        self.looped_duration = options.looped_duration
        self.output = options.output

        self.include_non_playable = options.include_non_playable

        if options.locate_peers:
            import geo.ip_locator
            self._peer_location = {}
            ip_locator = geo.ip_locator.IpLocator()
            for peeraddr in tr_log.peers:
                self._peer_location[peeraddr] = ip_locator.locate(peeraddr)

        if options.predecode:
            predecoder = Predecoder(tr_log, options.file_location, self.SAMPLE_RATE)
            predecoder.decode()

        if options.selected_files:
            tr_log.select_files(options.selected_files)

        self.playback_enabled = True
        self.fast_forwarding = False
        self._log_time_for_last_handled_event = 0
        self.gui = None
        self._check_which_files_are_audio()

        if options.no_synth:
            self.synth = None
        else:
            from synth_controller import SynthController
            self.synth = SynthController()

        self._create_players()
        self._prepare_playable_files()
        self.stopwatch = Stopwatch()
        self.playable_chunks = self._filter_playable_chunks(tr_log.chunks)

        if self.include_non_playable:
            self.chunks = tr_log.chunks
            self._num_selected_files = len(self.tr_log.files)
        else:
            self.chunks = self.playable_chunks
            self._num_selected_files = self._num_playable_files
        logger.debug("total num chunks: %s" % len(tr_log.chunks))
        logger.debug("num playable chunks: %s" % len(self.playable_chunks))
        logger.debug("num selected chunks: %s" % len(self.chunks))

        self._interpret_chunks_to_score(options.max_pause_within_segment)
        self._chunks_by_id = {}
        self.segments_by_id = {}
        self._playing = False
        self._quitting = False
        self.space = Space()

        if options.ff_to_start:
            self._ff_to_time = options.start_time
            self.set_time_cursor(0)
        else:
#.........这里部分代码省略.........
开发者ID:gaborpapp,项目名称:torrential-forms,代码行数:103,代码来源:orchestra.py

示例8: MainWindow

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
class MainWindow(QtGui.QWidget):
    def __init__(self, experiment):
        QtGui.QMainWindow.__init__(self)
        experiment.window = self
        self._experiment = experiment
        self._layout = QtGui.QVBoxLayout()
        self.sliders = {}
        self.setLayout(self._layout)
        self._add_parameter_form()
        self._add_map_view()
        self._create_menu()
        self._generate_map_and_path()

        self.stopwatch = Stopwatch()
        self._frame_count = 0
        timer = QtCore.QTimer(self)
        timer.setInterval(1000. / FRAME_RATE)
        QtCore.QObject.connect(timer, QtCore.SIGNAL('timeout()'), self._update)
        timer.start()

    def _add_map_view(self):
        self._map_view = MapView(self, experiment)
        self._layout.addWidget(self._map_view)

    def _add_parameter_form(self):
        layout = QtGui.QFormLayout()
        self._add_slider(layout, "novelty")
        self._add_slider(layout, "extension")
        self._add_slider(layout, "location_preference")
        self._layout.addLayout(layout)

    def _add_slider(self, layout, name):
        slider = QtGui.QSlider(QtCore.Qt.Horizontal)
        slider.setRange(0, SLIDER_PRECISION)
        slider.setSingleStep(1)
        slider.setValue(0.0)
        layout.addRow(name, slider)
        self.sliders[name] = slider

    def _create_menu(self):
        menu_bar = QtGui.QMenuBar()
        self._layout.setMenuBar(menu_bar)
        self._menu = menu_bar.addMenu("Navigator test")
        self._add_generate_new_path_action()
        self._add_extend_path_action()
        self._add_generate_map_action()

    def _add_generate_new_path_action(self):
        action = QtGui.QAction('Generate new &path', self)
        action.setShortcut('Ctrl+P')
        action.triggered.connect(self._experiment.generate_new_path)
        self._menu.addAction(action)

    def _add_extend_path_action(self):
        action = QtGui.QAction('&Extend path', self)
        action.setShortcut('Ctrl+E')
        action.triggered.connect(self._experiment.extend_path)
        self._menu.addAction(action)

    def _add_generate_map_action(self):
        action = QtGui.QAction('Generate &map', self)
        action.setShortcut('Ctrl+M')
        action.triggered.connect(self._generate_map_and_path)
        self._menu.addAction(action)

    def _generate_map_and_path(self):
        self._experiment.generate_map()
        self._experiment.create_navigator()
        self._experiment.generate_new_path()

    def _update(self):
        self.now = self.stopwatch.get_elapsed_time()
        if self._frame_count == 0:
            self.stopwatch.start()
        else:
            time_increment = self.now - self.previous_frame_time
            self._experiment.proceed(time_increment)
            self._map_view.updateGL()
        self.previous_frame_time = self.now
        self._frame_count += 1
开发者ID:gaborpapp,项目名称:AIam,代码行数:82,代码来源:test_navigator.py

示例9: Dice

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
from goody     import irange
from dice      import Dice
from stopwatch import Stopwatch
import prompt
import predicate

 
win_count     = 0                            #Win/Lose/Dice Statistics
lose_count    = 0

dice          = Dice([6,6])
game_timer    = Stopwatch()

games_to_play = prompt.for_int('Enter # of games to play', is_legal=predicate.is_positive, error_message='an int, but not > 0')

game_timer.start()
dice.standard_rolls_for_debugging()
for game in irange(1, games_to_play):        #Each iteration plays one game
    first_roll = dice.roll().pip_sum()       #Roll the dice and record their pip sum

    #Based on firstRoll, decide how to continue:
    #  immediate win/loss or trying to make point
    if first_roll == 7 or first_roll == 11:
        win_count += 1                       #Win on the first roll with 7 or 11

    elif first_roll == 2 or first_roll == 3 or first_roll == 12:
        lose_count += 1                      #Lose on the first roll with 2, 3, or 12

    else:                                    #Try to make the point as the game continues
        point = first_roll                   #point will never store 7, 11, 2, 3, or 12
开发者ID:shwilliams,项目名称:ICS33,代码行数:32,代码来源:craps.py

示例10: MainWindow

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
class MainWindow(QtGui.QWidget):
    def __init__(self, experiment):
        QtGui.QMainWindow.__init__(self)
        experiment.window = self
        self._experiment = experiment
        self._layout = QtGui.QVBoxLayout()
        self.setLayout(self._layout)
        self._add_parameter_form()
        self._add_map_view()
        self._create_menu()

        self.stopwatch = Stopwatch()
        self._frame_count = 0
        timer = QtCore.QTimer(self)
        timer.setInterval(1000. / FRAME_RATE)
        QtCore.QObject.connect(timer, QtCore.SIGNAL('timeout()'), self._update)
        timer.start()

    def _add_map_view(self):
        self._map_view = MapView(self, experiment)
        self._layout.addWidget(self._map_view)

    def _add_parameter_form(self):
        self._parameter_sliders = {}
        layout = QtGui.QFormLayout()
        for parameter_name in PARAMETERS:
            default_value = getattr(args, parameter_name)
            self._add_slider(layout, parameter_name, default_value)
        self._layout.addLayout(layout)

    def _add_slider(self, layout, name, default_value):
        slider = QtGui.QSlider(QtCore.Qt.Horizontal)
        slider.setRange(0, SLIDER_PRECISION)
        slider.setSingleStep(1)
        slider.setValue(int(default_value * SLIDER_PRECISION))
        slider.valueChanged.connect(lambda event: self.update_flaneur_parameter(name))
        layout.addRow(name, slider)
        self._parameter_sliders[name] = slider

    def update_flaneur_parameter(self, parameter_name):
        slider = self._parameter_sliders[parameter_name]
        value = float(slider.value()) / SLIDER_PRECISION
        setattr(self._experiment.flaneur, parameter_name, value)

    def _create_menu(self):
        menu_bar = QtGui.QMenuBar()
        self._layout.setMenuBar(menu_bar)
        self._menu = menu_bar.addMenu("Flaneur test")
        self._add_reset_action()
        self._add_generate_map_action()

    def _add_reset_action(self):
        action = QtGui.QAction('Reset', self)
        action.setShortcut('R')
        action.triggered.connect(self._experiment.reset)
        self._menu.addAction(action)

    def _add_generate_map_action(self):
        action = QtGui.QAction('Generate &map', self)
        action.setShortcut('Ctrl+M')
        action.triggered.connect(self._generate_map)
        self._menu.addAction(action)

    def _generate_map(self):
        self._experiment.generate_map()

    def _update(self):
        self.now = self.stopwatch.get_elapsed_time()
        if self._frame_count == 0:
            self.stopwatch.start()
        else:
            time_increment = self.now - self.previous_frame_time
            self._experiment.proceed(time_increment)
            self._map_view.updateGL()
        self.previous_frame_time = self.now
        self._frame_count += 1
开发者ID:gaborpapp,项目名称:AIam,代码行数:78,代码来源:test_flaneur.py

示例11: __init__

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]

#.........这里部分代码省略.........
        xwsize = right - left
        ywsize = top - bottom
        dx = -(pixdx*xwsize/self.width)
        dy = -(pixdy*ywsize/self.height)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glFrustum (left + dx, right + dx, bottom + dy, top + dy, self.near, self.far)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        glRotatef(self._camera_x_orientation, 1.0, 0.0, 0.0)
        glRotatef(self._camera_y_orientation, 0.0, 1.0, 0.0)
        glTranslatef(self._camera_position.x, self._camera_position.y, self._camera_position.z)

    def DrawGLScene(self):
        if self.exiting:
            glutDestroyWindow(glutGetWindow())
            return

        try:
            self._draw_gl_scene_error_handled()
        except Exception as error:
            traceback_printer.print_traceback()
            self.exiting = True
            raise error

    def _draw_gl_scene_error_handled(self):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()

        self.now = self.current_time()
        if self._frame_count == 0:
            self.stopwatch.start()
        else:
            self.time_increment = self.now - self.previous_frame_time
            self.configure_2d_projection()
            glTranslatef(self.margin, self.margin, 0)
            self._render_frames()
            self.render()
            if self.show_fps:
                self.update_fps_history()
                self.show_fps_if_timely()

        glutSwapBuffers()
        self.previous_frame_time = self.now
        self._frame_count += 1

    def current_time(self):
        return self.stopwatch.get_elapsed_time()

    def update_fps_history(self):
        if self.time_increment > 0:
            fps = 1.0 / self.time_increment
            self.fps_history.append(fps)

    def show_fps_if_timely(self):
        if self.previous_shown_fps_time:
            if (self.now - self.previous_shown_fps_time) > 1.0:
                self.calculate_and_show_fps()
        else:
            self.calculate_and_show_fps()

    def calculate_and_show_fps(self):
        print sum(self.fps_history) / len(self.fps_history)
        self.previous_shown_fps_time = self.now
开发者ID:gaborpapp,项目名称:AIam,代码行数:70,代码来源:window.py

示例12: Experiment

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
class Experiment(EventListener):
    @staticmethod
    def add_parser_arguments(parser):
        parser.add_argument("-profile", "-p")
        parser.add_argument("-entity", type=str)
        parser.add_argument("-train", action="store_true")
        parser.add_argument("-training-data", type=str)
        parser.add_argument("-training-duration", type=float)
        parser.add_argument("-training-data-frame-rate", type=int, default=50)
        parser.add_argument("-bvh", type=str,
                            help="If provided, this specifies both the skeleton and the training data.")
        parser.add_argument("-bvh-speed", type=float, default=1.0)
        parser.add_argument("-skeleton", type=str)
        parser.add_argument("-joint")
        parser.add_argument("-frame-rate", type=float, default=50.0)
        parser.add_argument("-unit-cube", action="store_true")
        parser.add_argument("-input-y-offset", type=float, default=.0)
        parser.add_argument("-output-y-offset", type=float, default=.0)
        parser.add_argument("-export-dir", default="export")
        parser.add_argument("--floor", action="store_true")
        parser.add_argument("--backend-only", action="store_true")
        parser.add_argument("--ui-only", action="store_true")
        parser.add_argument("--backend-host", default="localhost")
        parser.add_argument("--websockets", action="store_true",
                            help="Force websockets support (enabled automatically by --backend-only)")
        parser.add_argument("--no-websockets", action="store_true",
                            help="Force running without websockets support (e.g when combing --ui-only and --event-log-source)")
        parser.add_argument("--launch-when-ready", help="Run command when websocket server ready")
        parser.add_argument("--output-receiver-host")
        parser.add_argument("--output-receiver-port", type=int, default=10000)
        parser.add_argument("--with-profiler", action="store_true")
        parser.add_argument("--z-up", action="store_true", help="Use Z-up for BVHs")
        parser.add_argument("--show-fps", action="store_true")
        parser.add_argument("--receive-from-pn", action="store_true")
        parser.add_argument("--pn-host", default="localhost")
        parser.add_argument("--pn-port", type=int, default=tracking.pn.receiver.SERVER_PORT_BVH)
        parser.add_argument("--random-seed", type=int)
        parser.add_argument("--start-frame", type=int)
        parser.add_argument("--deterministic", action="store_true",
                            help="Handle time deterministically (fixed time interval between updates) rather than taking " +
                            "real time into account. May cause latency.")
        parser.add_argument("--stopped", action="store_true", help="Start in stopped mode")

    def __init__(self, parser, event_handlers={}):
        event_handlers.update({
            Event.START: self._start,
            Event.STOP: self._stop,
            Event.START_EXPORT_BVH: self._start_export_bvh,
            Event.STOP_EXPORT_BVH: self._stop_export_bvh,
            Event.SET_CURSOR: lambda event: self.update_cursor(event.content),
            Event.PROCEED_TO_NEXT_FRAME: self._proceed_to_next_frame,
            Event.SAVE_STUDENT: self._save_student,
            Event.LOAD_STUDENT: self._load_student,
            Event.SET_FRICTION: lambda event: self.set_friction(event.content),
            Event.SET_LEARNING_RATE: lambda event: self.student.set_learning_rate(event.content),
            Event.SET_MODEL_NOISE_TO_ADD: self._set_model_noise_to_add,
            Event.SET_MIN_TRAINING_LOSS: self._set_min_training_loss,
            Event.SET_MAX_ANGULAR_STEP: lambda event: self.entity.set_max_angular_step(
                event.content),
        })
        EventListener.__init__(self, handlers=event_handlers)

        args, _remaining_args = parser.parse_known_args()

        if args.random_seed is not None:
            random.seed(args.random_seed)
            
        if args.profile:
            profile_path = "%s/%s.profile" % (self.profiles_dir, args.profile)
            profile_args_string = open(profile_path).read()
            profile_args_strings = profile_args_string.split()
            args, _remaining_args = parser.parse_known_args(profile_args_strings, namespace=args)
            self._student_model_path = "%s/%s.model" % (self.profiles_dir, args.profile)
            self._entity_model_path = "%s/%s.entity.model" % (self.profiles_dir, args.profile)
            self._training_data_path = "%s/%s.data" % (self.profiles_dir, args.profile)

        entity_module = imp.load_source("entity", "entities/%s.py" % args.entity)
        if hasattr(entity_module, "Entity"):
            self.entity_class = entity_module.Entity
        else:
            self.entity_class = BaseEntity
        self.entity_class.add_parser_arguments(parser)
        if not args.backend_only:
            self._entity_scene_module = imp.load_source("entity", "entities/%s_scene.py" % args.entity)
            self._entity_scene_module.Scene.add_parser_arguments(parser)
            self.add_ui_parser_arguments(parser)

        self.add_parser_arguments_second_pass(parser, args)
        args = parser.parse_args()
        if args.profile:
            args = parser.parse_args(profile_args_strings, namespace=args)

        self.args = args

        skeleton_bvh_path = self._get_skeleton_bvh_path()
        if skeleton_bvh_path:
            self.bvh_reader = self._create_bvh_reader(skeleton_bvh_path)
            self.pose = self.bvh_reader.get_hierarchy().create_pose()
        else:
            self.bvh_reader = None
#.........这里部分代码省略.........
开发者ID:gaborpapp,项目名称:AIam,代码行数:103,代码来源:experiment.py

示例13: MasterBehavior

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
class MasterBehavior(Behavior):
    def __init__(self):
        Behavior.__init__(self)
        self._recall_amount = args.recall_amount
        self.memorize = args.memorize
        self.auto_friction = args.auto_friction
        self._auto_switch_enabled = False
        self.input_only = False
        self._input = None
        self._noise_amount = 0
        self.reset_translation()
        self._stopwatch = Stopwatch()
        self._stopwatch.start()

    def set_noise_amount(self, amount):
        self._noise_amount = amount
        
    def reset_translation(self):
        master_entity.reset_constrainers()
        self._chainer = Chainer()
        self._chainer.put(numpy.zeros(3))
        self._chainer.get()
        self._chainer.switch_source()
        self._selector = Selector(self._chainer.switch_source)

    def on_recall_amount_changed(self):
        pass
    
    def set_recall_amount(self, recall_amount):
        self._recall_amount = recall_amount

    def get_recall_amount(self):
        return self._recall_amount
    
    def set_model(self, model_name):
        self._improvise = improvise_behaviors[model_name]
        self._chainer.switch_source()

    def proceed(self, time_increment):
        if self._noise_amount > 0:
            students["autoencoder"].add_noise(self._noise_amount)
        self._improvise.proceed(time_increment)
        recall_behavior.proceed(time_increment)
        if self.auto_friction:
            if self._recall_amount < 0.5:
                self._set_master_entity_friction_and_update_ui(True)
            else:
                self._set_master_entity_friction_and_update_ui(False)

    def _set_master_entity_friction_and_update_ui(self, value):
        master_entity.set_friction(value)
        application.on_friction_changed(value)
                
    def sends_output(self):
        return True

    def on_input(self, input_):
        self._input = input_
        if self.memorize:
            memory.on_input(input_)

    def set_auto_switch_enabled(self, value):
        self._auto_switch_enabled = value
        
    def get_output(self):
        if self.input_only:
            return self._input

        if self._auto_switch_enabled:
            self._recall_amount = self._get_auto_switch_recall_amount()
            self.on_recall_amount_changed()
            
        improvise_output = self._get_improvise_output()
        recall_output = recall_behavior.get_output()
        
        if args.verbose:
            self._print_output_info("improvise_output", improvise_output)
            self._print_output_info("recall_output", recall_output)
            
        if recall_output is None:
            if self._recall_amount > 0:
                application.print_and_log("WARNING: recall amount > 0 but no recall output")
            translation = self._pass_through_selector_to_update_its_state(
                get_translation(improvise_output))
            orientations = get_orientations(improvise_output)
        else:
            translation = self._selector.select(
                get_translation(improvise_output),
                get_translation(recall_output),
                self._recall_amount)
            orientations = get_orientations(
                master_entity.interpolate(improvise_output, recall_output, self._recall_amount))
                
        self._chainer.put(translation)
        translation = self._chainer.get()
        output = combine_translation_and_orientations(translation, orientations)
        
        return output

    def _pass_through_selector_to_update_its_state(self, value):
#.........这里部分代码省略.........
开发者ID:gaborpapp,项目名称:AIam,代码行数:103,代码来源:learn_recall_improvise.py

示例14: __init__

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
class Visualizer:
    def __init__(self, args,
                 file_class=File,
                 chunk_class=Chunk,
                 segment_class=Segment,
                 peer_class=Peer):
        if hasattr(self, "_initialized") and self._initialized:
            return
        self.file_class = file_class
        self.chunk_class = chunk_class
        self.segment_class = segment_class
        self.peer_class = peer_class
        self.args = args
        self.sync = args.sync
        self.width = args.width
        self.height = args.height
        self.margin = args.margin
        self.show_fps = args.show_fps
        self.export = args.export
        self.capture_message_log = args.capture_message_log
        self.play_message_log = args.play_message_log
        self.waveform_gain = args.waveform_gain
        self._standalone = args.standalone
        self._target_aspect_ratio = self._get_aspect_ratio_from_args()

        self.logger = logging.getLogger("visualizer")
        self.reset()
        self._frame_count = 0
        self.exiting = False
        self.time_increment = 0
        self.stopwatch = Stopwatch()
        self._synth_instance = None
        self._synth_port = None
        self._synced = False
        self._layers = []
        self._warned_about_missing_pan_segment = False
        self.gl_display_mode = GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH
        self._accum_enabled = False
        self._3d_enabled = False
        self.fovy = 45
        self.near = 0.1
        self.far = 100.0
        self._fullscreen = False
        self._text_renderer_class = getattr(text_renderer_module, TEXT_RENDERERS[args.text_renderer])

        if args.camera_script:
            self._camera_script = CameraScriptInterpreter(args.camera_script)
        else:
            self._camera_script = None

        if self.show_fps:
            self.fps_history = collections.deque(maxlen=10)
            self.previous_shown_fps_time = None

        if not args.standalone:
            if args.port:
                port = args.port
            else:
                port = self._get_orchestra_port()
            self.orchestra_host = args.host
            self.orchestra_port = port
            self.setup_osc()
            self.orchestra.register(self.server.port)

        self._screen_dumper = Exporter(".", self.margin, self.margin, self.width, self.height)
        if self.export:
            self.export_fps = args.export_fps
            import shutil
            if args.export_dir:
                export_dir = args.export_dir
            elif hasattr(args, "sessiondir"):
                export_dir = "%s/rendered_%s" % (args.sessiondir, self.__class__.__name__)
            else:
                export_dir = "export"
            if os.path.exists(export_dir):
                shutil.rmtree(export_dir)
            os.mkdir(export_dir)
            self.exporter = Exporter(export_dir, self.margin, self.margin, self.width, self.height)

        if self.play_message_log:
            self._message_log_reader = MessageLogReader(self.play_message_log)
        if self.capture_message_log:
            self._message_log_writer = MessageLogWriter(self.capture_message_log)
            self._audio_capture_start_time = None

        self._initialized = True

    def _get_aspect_ratio_from_args(self):
        w, h = map(float, self.args.aspect.split(":"))
        return w / h

    def _get_orchestra_port(self):
        if self.args.host == "localhost":
            return self._read_port_from_disk()
        else:
            return self._read_port_from_network_share()

    def _read_port_from_disk(self):
        self._read_port_from_file("server_port.txt")

#.........这里部分代码省略.........
开发者ID:alex-berman,项目名称:tforms,代码行数:103,代码来源:visualizer.py

示例15: add_parser_arguments

# 需要导入模块: from stopwatch import Stopwatch [as 别名]
# 或者: from stopwatch.Stopwatch import start [as 别名]
class Orchestra:
    SAMPLE_RATE = 44100
    BYTES_PER_SAMPLE = 2 # mpg123, used by predecode, outputs 16-bit PCM mono
    PLAYABLE_FORMATS = ['mp3', 'flac', 'wav', 'm4b']
    JACK = "jack"
    SSR = "ssr"

    @staticmethod
    def add_parser_arguments(parser):
        parser.add_argument("--rt", action="store_true", dest="realtime")
        parser.add_argument("-t", "--torrent", dest="torrentname", default="")
        parser.add_argument("-z", "--timefactor", dest="timefactor", type=float, default=1)
        parser.add_argument("--start", dest="start_time", type=float, default=0)
        parser.add_argument("-q", "--quiet", action="store_true", dest="quiet")
        parser.add_argument("--pretend-sequential", action="store_true", dest="pretend_sequential")
        parser.add_argument("--gui", action="store_true", dest="gui_enabled")
        parser.add_argument("--fast-forward", action="store_true", dest="ff")
        parser.add_argument("--fast-forward-to-start", action="store_true", dest="ff_to_start")
        parser.add_argument("--quit-at-end", action="store_true", dest="quit_at_end")
        parser.add_argument("--loop", dest="loop", action="store_true")
        parser.add_argument("--max-pause-within-segment", type=float)
        parser.add_argument("--max-segment-duration", type=float)
        parser.add_argument("--looped-duration", dest="looped_duration", type=float)
        parser.add_argument("-o", "--output", dest="output", type=str, default=Orchestra.JACK)
        parser.add_argument("--include-non-playable", action="store_true")
        parser.add_argument("-f", "--file", dest="selected_files", type=int, nargs="+")
        parser.add_argument("--title", type=str, default="")
        parser.add_argument("--pretend-audio", dest="pretend_audio_filename")
        parser.add_argument("--capture-audio")
        parser.add_argument("--leading-pause", type=float, default=0)

    _extension_re = re.compile('\.(\w+)$')

    def __init__(self, server, sessiondir, tr_log, options):
        self.server = server
        self.options = options
        self.sessiondir = sessiondir
        self.tr_log = tr_log
        self.realtime = options.realtime
        self.timefactor = options.timefactor
        self.quiet = options.quiet
        self._loop = options.loop
        self.looped_duration = options.looped_duration
        self.output = options.output
        self.include_non_playable = options.include_non_playable
        self._leading_pause = options.leading_pause

        if server.options.locate_peers:
            self._peer_location = {}
            for peeraddr in tr_log.peers:
                self._peer_location[peeraddr] = server.ip_locator.locate(peeraddr)
            self._peers_center_location_x = self._get_peers_center_location_x()

        if options.pretend_audio_filename:
            self._pretended_file = self._fileinfo_for_pretended_audio_file()
            self._pretended_file["duration"] = self._get_file_duration(self._pretended_file)
            self._pretended_files = [self._pretended_file]
            self._files_to_play = self._pretended_files
        else:
            self._files_to_play = self.tr_log.files

        self.predecode = server.options.predecode
        if self.predecode:
            predecoder = Predecoder(
                tr_log.files, sample_rate=self.SAMPLE_RATE, location=tr_log.file_location)
            predecoder.decode(server.options.force_predecode)

            if options.pretend_audio_filename:
                predecoder = Predecoder(
                    self._pretended_files, sample_rate=self.SAMPLE_RATE)
                predecoder.decode(server.options.force_predecode)

        if options.selected_files:
            tr_log.select_files(options.selected_files)

        self.playback_enabled = True
        self.fast_forwarding = False
        self.gui = None
        self._check_which_files_are_audio()

        self._player_class = WavPlayer
        self.players = []
        self._player_for_peer = dict()

        self._prepare_playable_files()
        self.stopwatch = Stopwatch()
        self.playable_chunks = self._filter_playable_chunks(tr_log, tr_log.chunks)

        if self.include_non_playable:
            self.chunks = tr_log.chunks
            self._num_selected_files = len(self.tr_log.files)
        else:
            self.chunks = self.playable_chunks
            self._num_selected_files = self._num_playable_files
        logger.debug("total num chunks: %s" % len(tr_log.chunks))
        logger.debug("num playable chunks: %s" % len(self.playable_chunks))
        logger.debug("num selected chunks: %s" % len(self.chunks))

        self.score = self._interpret_chunks_to_score(tr_log, self.playable_chunks, options)
        self.estimated_duration = self._estimated_playback_duration(self.score, options)
#.........这里部分代码省略.........
开发者ID:alex-berman,项目名称:tforms,代码行数:103,代码来源:orchestra.py


注:本文中的stopwatch.Stopwatch.start方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。