desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Testing whether a FileNotFound exception is raised when metadata cannot be found'
@raises(FileNotFound) def test_load_metadata_not_found(self):
self.handler.session = MockObject() self.handler.session.lm = MockObject() self.handler.session.lm.metadata_store = MockObject() self.handler.session.lm.metadata_store.get = (lambda _: None) self.handler._load_metadata('abc')
'Testing whether a FileNotFound exception is raised when a torrent cannot be found'
@raises(FileNotFound) def test_load_torrent_not_found(self):
self.handler.session = MockObject() self.handler.session.lm = MockObject() self.handler.session.lm.torrent_store = MockObject() self.handler.session.lm.torrent_store.get = (lambda _: None) self.handler._load_torrent('abc')
'Testing the handle_packet_as_receiver method'
def test_handle_packet_as_receiver(self):
def mocked_handle_error(_dummy1, _dummy2, error_msg=None): mocked_handle_error.called = True mocked_handle_error.called = False self.handler._handle_error = mocked_handle_error mock_session = MockObject() mock_session.last_received_packet = None mock_session.block_size = 42 mock_sess...
'Testing the handle_packet_as_sender method'
def test_handle_packet_as_sender(self):
def mocked_handle_error(_dummy1, _dummy2, error_msg=None): mocked_handle_error.called = True mocked_handle_error.called = False self.handler._handle_error = mocked_handle_error packet = {'opcode': OPCODE_ERROR} self.handler._handle_packet_as_sender(None, packet) self.assertTrue(mocked_ha...
'Testing the error handling of a tftp handler'
def test_handle_error(self):
mock_session = MockObject() mock_session.is_failed = False self.handler._send_error_packet = (lambda _dummy1, _dummy2, _dummy3: None) self.handler._handle_error(mock_session, None) self.assertTrue(mock_session.is_failed)
'Testing whether a correct error message is sent in the tftp handler'
def test_send_error_packet(self):
def mocked_send_packet(_, packet): self.assertEqual(packet['session_id'], 42) self.assertEqual(packet['error_code'], 43) self.assertEqual(packet['error_msg'], 'test') self.handler._send_packet = mocked_send_packet mock_session = MockObject() mock_session.session_id = 42 self....
'Testing whether the get_string method raises InvalidStringException when no zero terminator is found'
@raises(InvalidStringException) def test_get_string_no_end(self):
_get_string('', 0)
'Testing whether decoding the options raises InvalidPacketException if no options are found'
@raises(InvalidPacketException) def test_decode_options_no_option(self):
_decode_options({}, '\x00a\x00', 0)
'Testing whether decoding the options raises InvalidPacketException if no value is found'
@raises(InvalidPacketException) def test_decode_options_no_value(self):
_decode_options({}, 'b\x00\x00', 0)
'Testing whether decoding the options raises InvalidOptionException if an invalid option is found'
@raises(InvalidOptionException) def test_decode_options_unknown(self):
_decode_options({}, 'b\x00a\x00', 0)
'Testing whether decoding the options raises InvalidOptionException if an invalid option is found'
@raises(InvalidOptionException) def test_decode_options_invalid(self):
_decode_options({}, 'blksize\x00a\x00', 0)
'Testing whether an InvalidPacketException is raised when our incoming data is too small'
@raises(InvalidPacketException) def test_decode_data(self):
_decode_data(None, 'aa', 42)
'Testing whether an InvalidPacketException is raised when our incoming ack has an invalid size'
@raises(InvalidPacketException) def test_decode_ack(self):
_decode_ack(None, 'aa', 42)
'Testing whether an InvalidPacketException is raised when our incoming error has an invalid size'
@raises(InvalidPacketException) def test_decode_error_too_small(self):
_decode_error(None, 'aa', 42)
'Testing whether an InvalidPacketException is raised when our incoming error has an empty message'
@raises(InvalidPacketException) def test_decode_error_no_message(self):
_decode_error({}, 'aa\x00', 0)
'Testing whether an InvalidPacketException is raised when our incoming error has an invalid structure'
@raises(InvalidPacketException) def test_decode_error_invalid_pkg(self):
_decode_error({}, 'aaa\x00\x00', 0)
'Testing whether an InvalidPacketException is raised when our incoming packet is too small'
@raises(InvalidPacketException) def test_decode_packet_too_small(self):
decode_packet('aaa')
'Testing whether an InvalidPacketException is raised when our incoming packet contains an invalid opcode'
@raises(InvalidPacketException) def test_decode_packet_opcode(self):
decode_packet('aaaaaaaaaa')
'Testing whether the encoding of an error packet is correct'
def test_encode_packet_error(self):
encoded = encode_packet({'opcode': OPCODE_ERROR, 'session_id': 123, 'error_code': 1, 'error_msg': 'hi'}) self.assertEqual(encoded[(-3)], 'h') self.assertEqual(encoded[(-2)], 'i')
'Create a new TriblerConfig instance'
def setUp(self, annotate=True):
super(TestTriblerConfig, self).setUp(annotate=annotate) self.tribler_config = TriblerConfig() self.assertIsNotNone(self.tribler_config)
'When creating a new instance with a configobject provided, the given options must be contained in the resulting instance.'
def test_init_with_config(self):
configdict = ConfigObj({'a': 1, 'b': '2'}, configspec=CONFIG_SPEC_PATH) self.tribler_config = TriblerConfig(configdict) self.tribler_config.validate() for (key, value) in configdict.items(): self.assertEqual(self.tribler_config.config[key], value)
'A newly created TriblerConfig is valid.'
def test_init_without_config(self):
self.tribler_config.validate()
'When writing and reading a config the options should remain the same.'
def test_write_load(self):
port = 4444 self.tribler_config.set_anon_listen_port(port) self.tribler_config.write() path = os.path.join(self.tribler_config.get_state_dir(), FILENAME) read_config = TriblerConfig.load(path) read_config.validate() self.assertEqual(read_config.get_anon_listen_port(), port)
'Setting and getting of libtorrent proxy settings.'
def test_libtorrent_proxy_settings(self):
(proxy_type, server, auth) = (3, ('33.33.33.33', 22), 1) self.tribler_config.set_libtorrent_proxy_settings(proxy_type, server, auth) self.assertEqual(self.tribler_config.get_libtorrent_proxy_settings()[0], proxy_type) self.assertEqual(self.tribler_config.get_libtorrent_proxy_settings()[1], server) s...
'Check whether general get and set methods are working as expected.'
def test_get_set_methods_general(self):
self.tribler_config.set_family_filter_enabled(False) self.assertEqual(self.tribler_config.get_family_filter_enabled(), False) self.tribler_config.set_state_dir(None) self.assertEqual(self.tribler_config.get_state_dir(), self.tribler_config.get_default_state_dir()) self.tribler_config.set_state_dir('...
'Check whether torrent checking get and set methods are working as expected.'
def test_get_set_methods_torrent_checking(self):
self.tribler_config.set_torrent_checking_enabled(True) self.assertEqual(self.tribler_config.get_torrent_checking_enabled(), True)
'Check whether http api get and set methods are working as expected.'
def test_get_set_methods_http_api(self):
self.tribler_config.set_http_api_enabled(True) self.assertEqual(self.tribler_config.get_http_api_enabled(), True) self.tribler_config.set_http_api_port(True) self.assertEqual(self.tribler_config.get_http_api_port(), True)
'Check whether dispersy get and set methods are working as expected.'
def test_get_set_methods_dispersy(self):
self.tribler_config.set_dispersy_enabled(True) self.assertEqual(self.tribler_config.get_dispersy_enabled(), True) self.tribler_config.set_dispersy_port(True) self.assertEqual(self.tribler_config.get_dispersy_port(), True)
'Check whether libtorrent get and set methods are working as expected.'
def test_get_set_methods_libtorrent(self):
self.tribler_config.set_libtorrent_enabled(True) self.assertEqual(self.tribler_config.get_libtorrent_enabled(), True) self.tribler_config.set_libtorrent_utp(True) self.assertEqual(self.tribler_config.get_libtorrent_utp(), True) self.tribler_config.set_libtorrent_port(True) self.assertEqual(self....
'Check whether mainline dht get and set methods are working as expected.'
def test_get_set_methods_mainline_dht(self):
self.tribler_config.set_mainline_dht_enabled(True) self.assertEqual(self.tribler_config.get_mainline_dht_enabled(), True) self.tribler_config.set_mainline_dht_port(True) self.assertEqual(self.tribler_config.get_mainline_dht_port(), True)
'Check whether video server get and set methods are working as expected.'
def test_get_set_methods_video_server(self):
self.tribler_config.set_video_server_enabled(True) self.assertEqual(self.tribler_config.get_video_server_enabled(), True) self.tribler_config.set_video_server_port(True) self.assertEqual(self.tribler_config.get_video_server_port(), True)
'Check whether tunnel community get and set methods are working as expected.'
def test_get_set_methods_tunnel_community(self):
self.tribler_config.set_tunnel_community_enabled(True) self.assertEqual(self.tribler_config.get_tunnel_community_enabled(), True) self.tribler_config.set_tunnel_community_socks5_listen_ports([(-1)]) self.assertNotEqual(self.tribler_config.get_tunnel_community_socks5_listen_ports(), [(-1)]) self.trib...
'Check whether upgrader get and set methods are working as expected.'
def test_get_set_methods_upgrader(self):
self.tribler_config.set_upgrader_enabled(True) self.assertEqual(self.tribler_config.get_upgrader_enabled(), True)
'Check whether torrent store get and set methods are working as expected.'
def test_get_set_methods_torrent_store(self):
self.tribler_config.set_torrent_store_enabled(True) self.assertEqual(self.tribler_config.get_torrent_store_enabled(), True) self.tribler_config.set_torrent_store_dir('TESTDIR') self.tribler_config.set_state_dir('TEST') self.assertEqual(self.tribler_config.get_torrent_store_dir(), os.path.join('TEST'...
'Check whether wallet get and set methods are working as expected.'
def test_get_set_methods_wallets(self):
self.tribler_config.set_btc_testnet(True) self.assertTrue(self.tribler_config.get_btc_testnet()) self.tribler_config.set_dummy_wallets_enabled(True) self.assertTrue(self.tribler_config.get_dummy_wallets_enabled())
'Check whether metadata get and set methods are working as expected.'
def test_get_set_methods_metadata(self):
self.tribler_config.set_metadata_enabled(True) self.assertEqual(self.tribler_config.get_metadata_enabled(), True) self.tribler_config.set_metadata_store_dir('TESTDIR') self.tribler_config.set_state_dir('TEST') self.assertEqual(self.tribler_config.get_metadata_store_dir(), os.path.join('TEST', 'TESTD...
'Check whether torrent collecting get and set methods are working as expected.'
def test_get_set_methods_torrent_collecting(self):
self.tribler_config.set_torrent_collecting_enabled(True) self.assertEqual(self.tribler_config.get_torrent_collecting_enabled(), True) self.tribler_config.set_torrent_collecting_max_torrents(True) self.assertEqual(self.tribler_config.get_torrent_collecting_max_torrents(), True) self.tribler_config.se...
'Check whether search community get and set methods are working as expected.'
def test_get_set_methods_search_community(self):
self.tribler_config.set_torrent_search_enabled(True) self.assertEqual(self.tribler_config.get_torrent_search_enabled(), True)
'Check whether allchannel community get and set methods are working as expected.'
def test_get_set_methods_allchannel_community(self):
self.tribler_config.set_channel_search_enabled(True) self.assertEqual(self.tribler_config.get_channel_search_enabled(), True)
'Check whether channel community get and set methods are working as expected.'
def test_get_set_methods_channel_community(self):
self.tribler_config.set_channel_community_enabled(True) self.assertEqual(self.tribler_config.get_channel_community_enabled(), True)
'Check whether preview channel community get and set methods are working as expected.'
def test_get_set_methods_preview_channel_community(self):
self.tribler_config.set_preview_channel_community_enabled(True) self.assertEqual(self.tribler_config.get_preview_channel_community_enabled(), True)
'Check whether trustchain community get and set methods are working as expected.'
def test_get_set_methods_trustchain_community(self):
self.tribler_config.set_trustchain_enabled(True) self.assertEqual(self.tribler_config.get_trustchain_enabled(), True)
'Check whether watch folder get and set methods are working as expected.'
def test_get_set_methods_watch_folder(self):
self.tribler_config.set_watch_folder_enabled(True) self.assertEqual(self.tribler_config.get_watch_folder_enabled(), True) self.tribler_config.set_watch_folder_path(True) self.assertEqual(self.tribler_config.get_watch_folder_path(), True)
'Check whether credit mining get and set methods are working as expected.'
def test_get_set_methods_credit_mining(self):
self.tribler_config.set_credit_mining_enabled(True) self.assertEqual(self.tribler_config.get_credit_mining_enabled(), True) self.tribler_config.set_credit_mining_archive_sources(True) self.assertEqual(self.tribler_config.get_credit_mining_archive_sources(), True) self.tribler_config.set_credit_minin...
'Testing whether downloading a torrent from another peer is successful'
@deferred(timeout=20) @skipIf((sys.platform == 'win32'), 'chmod does not work on Windows') def test_torrent_download(self):
session1_port = self.session.config.get_dispersy_port() def start_download(_): candidate = Candidate(('127.0.0.1', session1_port), False) self.session2.lm.rtorrent_handler.download_torrent(candidate, self.infohashes[0]) self.session2.lm.rtorrent_handler.download_torrent(candidate, self.i...
'Testing whether downloading torrent metadata from another peer is successful'
@deferred(timeout=20) def test_metadata_download(self):
session1_port = self.session.config.get_dispersy_port() thumb_file = os.path.join(unicode(TESTS_DATA_DIR), u'41aea20908363a80d44234e8fef07fab506cd3b4', u'421px-Pots_10k_100k.jpeg') with open(thumb_file, 'rb') as f: self.thumb_data = f.read() thumb_hash = sha1(self.thumb_data).digest() thumb_...
'No extend metadata messages may be send and the connection needs to close.'
def read_extend_metadata_close(self, conn):
conn.s.settimeout(10.0) while True: response = conn.recv() if (len(response) == 0): break assert (not ((response[0] == EXTEND) and (response[1] == 3)))
'send length-prefixed message'
def send(self, data):
self.s.send(tobinary(len(data))) self.s.send(data)
'received length-prefixed message'
def recv(self):
size_data = self._readn(4) if (len(size_data) == 0): return size_data size = toint(size_data) if (size > 10000): self._logger.debug('btconn: waiting for message size %d', size) if (size == 0): return self.recv() else: return self._readn(size)
'read n bytes from socket stream'
def _readn(self, n):
nwant = n while True: try: data = self.s.recv(nwant) except socket.error as ex: if (ex[0] == 10035): continue elif (ex[0] == 10054): self._logger.exception(u'converted to EOF') return '' else: ...
'Catch unhandled exception, log it and store it to be printed at teardown time too.'
def catch_exception(self, type, value, tb):
self.exc_counter += 1 def repr_(value): try: return repr(value) except: return '<Error while REPRing value>' self.last_exc = repr_(value) self._register_exception_line('Unhandled exception raised while running the test: %s %s', typ...
'Log all unhandled exceptions, clear logged exceptions and raise to fail the currently running test.'
def check_exceptions(self):
if self.exc_counter: lines = self._lines self._lines = [] exc_counter = self.exc_counter self.exc_counter = 0 last_exc = self.last_exc self.last_exc = 0 self._logger.critical("The following unhandled exceptions where raised during this ...
'Add information about an infohash to our tracker info.'
def add_info_about_infohash(self, infohash, seeders, leechers, downloaded=0):
self.infohashes[infohash] = {'seeders': seeders, 'leechers': leechers, 'downloaded': downloaded}
'Returns information about an infohash, None if this infohash is not in our info.'
def get_info_about_infohash(self, infohash):
if (infohash not in self.infohashes): return None return self.infohashes[infohash]
'Return True if we have information about a specified infohash'
def has_info_about_infohash(self, infohash):
return (infohash in self.infohashes)
'Parse an incoming datagram. Check the action and based on that, send a response.'
def datagramReceived(self, response, (host, port)):
(connection_id, action, transaction_id) = struct.unpack_from('!qii', response, 0) if ((action == 0) and (connection_id != UDP_TRACKER_INIT_CONNECTION_ID)): self.send_error(host, port, 'invalid protocol') self.transaction_id = transaction_id if (action == TRACKER_ACTION_CONNECT): self....
'Send a connection reply.'
def send_connection_reply(self, host, port):
self.connection_id = random.randint(0, MAX_INT32) response_msg = struct.pack('!iiq', TRACKER_ACTION_CONNECT, self.transaction_id, self.connection_id) self.transport.write(response_msg, (host, port))
'Send a scrape reply.'
def send_scrape_reply(self, host, port, infohashes):
response_msg = struct.pack('!ii', TRACKER_ACTION_SCRAPE, self.transaction_id) for infohash in infohashes: ih_info = self.tracker_session.tracker_info.get_info_about_infohash(infohash) response_msg += struct.pack('!iii', ih_info['seeders'], ih_info['downloaded'], ih_info['leechers']) self.tra...
'Send an error message if the client does not follow the protocol.'
def send_error(self, host, port, error_msg):
response_msg = struct.pack((('!ii' + str(len(error_msg))) + 's'), TRACKER_ACTION_ERROR, self.transaction_id, error_msg) self.transport.write(response_msg, (host, port))
'Start the UDP Tracker'
def start(self):
self.listening_port = reactor.listenUDP(self.port, UDPTrackerProtocol(self))
'Stop the UDP Tracker, returns a deferred that fires when the server is closed.'
def stop(self):
return maybeDeferred(self.listening_port.stopListening)
'Return a bencoded dictionary with information about the queried infohashes.'
def render_GET(self, request):
if ('info_hash' not in request.args): request.setResponseCode(http.BAD_REQUEST) return 'infohash argument missing' response_dict = {'files': {}} for infohash in request.args['info_hash']: if (not self.session.tracker_info.has_info_about_infohash(infohash)): request....
'Start the HTTP Tracker'
def start(self):
self.site = reactor.listenTCP(self.port, server.Site(resource=TrackerRootEndpoint(self)))
'Stop the HTTP Tracker, returns a deferred that fires when the server is closed.'
def stop(self):
return maybeDeferred(self.site.stopListening)
'Initialize the variables of the TriblerServiceMaker and the logger.'
def __init__(self):
self.session = None self._stopping = False self.process_checker = None
'Main method to startup Tribler.'
def start_tribler(self, options):
def on_tribler_shutdown(_): msg('Tribler shut down') reactor.stop() self.process_checker.remove_lock_file() def signal_handler(sig, _): msg(('Received shut down signal %s' % sig)) if (not self._stopping): self._stopping = True sel...
'Construct a Tribler service.'
def makeService(self, options):
tribler_service = MultiService() tribler_service.setName('Tribler') manhole_namespace = {} if (options['manhole'] > 0): port = options['manhole'] manhole = manhole_tap.makeService({'namespace': manhole_namespace, 'telnetPort': ('tcp:%d:interface=127.0.0.1' % port), 'sshPort': None, 'pass...
'Load the Market community'
def load_market_community(self, _):
msg('Loading market community...') self.market_community = self.session.get_dispersy_instance().define_auto_load(MarketCommunity, self.session.dispersy_member, load=True, kargs={'tribler_session': self.session})
'Main method to startup Tribler.'
def start_tribler(self, options):
def on_tribler_shutdown(_): msg('Tribler shut down') reactor.stop() self.process_checker.remove_lock_file() def signal_handler(sig, _): msg(('Received shut down signal %s' % sig)) if (not self._stopping): self._stopping = True sel...
'Construct a Tribler service.'
def makeService(self, options):
tribler_service = MultiService() tribler_service.setName('Market') manhole_namespace = {} if (options['manhole'] > 0): port = options['manhole'] manhole = manhole_tap.makeService({'namespace': manhole_namespace, 'telnetPort': ('tcp:%d:interface=127.0.0.1' % port), 'sshPort': None, 'passw...
'Initialize the variables of this service and the logger.'
def __init__(self):
self._stopping = False self.tunnel_site = None
'Main method to startup a tunnel helper and add a signal handler.'
def start_tunnel(self, options):
socks5_port = options['socks5'] introduce_port = options['introduce'] dispersy_port = options['dispersy'] crawl_keypair_filename = options['crawl'] settings = TunnelSettings() settings.min_circuits = 0 settings.max_circuits = 0 if (socks5_port is not None): settings.socks_listen_...
'Construct a tunnel helper service.'
def makeService(self, options):
tunnel_helper_service = MultiService() tunnel_helper_service.setName('Tunnel_helper') manhole_namespace = {} if options['manhole']: port = options['manhole'] manhole = manhole_tap.makeService({'namespace': manhole_namespace, 'telnetPort': ('tcp:%d:interface=127.0.0.1' % port), 'sshPort':...
'Input is assumed to be of shape batch*height*width*channels'
def __init__(self, incoming, num_filters, filter_size, stride=1, pad='VALID', untie_biases=False, W=XavierUniformInitializer(), b=tf.zeros_initializer(), nonlinearity=tf.nn.relu, n=None, **kwargs):
super(BaseConvLayer, self).__init__(incoming, **kwargs) if (nonlinearity is None): self.nonlinearity = tf.identity else: self.nonlinearity = nonlinearity if (n is None): n = (len(self.input_shape) - 2) elif (n != (len(self.input_shape) - 2)): raise ValueError(('Tried ...
'Get the shape of the weight matrix `W`. Returns tuple of int The shape of the weight matrix.'
def get_W_shape(self):
num_input_channels = self.input_shape[(-1)] return (self.filter_size + (num_input_channels, self.num_filters))
'Symbolically convolves `input` with ``self.W``, producing an output of shape ``self.output_shape``. To be implemented by subclasses. Parameters input : Theano tensor The input minibatch to convolve **kwargs Any additional keyword arguments from :meth:`get_output_for` Returns Theano tensor `input` convolved according t...
def convolve(self, input, **kwargs):
raise NotImplementedError('BaseConvLayer does not implement the convolve() method. You will want to use a subclass such as Conv2DLayer.')
'Parameters input : tensor output from the previous layer deterministic : bool If true dropout and scaling is disabled, see notes'
def get_output_for(self, input, deterministic=False, **kwargs):
if (deterministic or (self.p == 0)): return input else: retain_prob = (1.0 - self.p) if self.rescale: input /= retain_prob return tf.nn.dropout(input, keep_prob=retain_prob)
'Incoming gate: i(t) = f_i(x(t) @ W_xi + h(t-1) @ W_hi + w_ci * c(t-1) + b_i) Forget gate: f(t) = f_f(x(t) @ W_xf + h(t-1) @ W_hf + w_cf * c(t-1) + b_f) Cell gate: c(t) = f(t) * c(t - 1) + i(t) * f_c(x(t) @ W_xc + h(t-1) @ W_hc + b_c) Out gate: o(t) = f_o(x(t) @ W_xo + h(t-1) W_ho + w_co * c(...
def step(self, hcprev, x):
hprev = hcprev[:, :self.num_units] cprev = hcprev[:, self.num_units:] if self.layer_normalization: ln = apply_ln(self) else: ln = (lambda x, *args: x) x_ifco = ln(tf.matmul(x, self.W_x_ifco), 'x_ifco') h_ifco = ln(tf.matmul(hprev, self.W_h_ifco), 'h_ifco') (x_i, x_f, x_c, x_o...
'Internal method to be implemented which does not perform caching'
def get_params_internal(self, **tags):
raise NotImplementedError
'Get the list of parameters, filtered by the provided tags. Some common tags include \'regularizable\' and \'trainable\''
def get_params(self, **tags):
tag_tuple = tuple(sorted(list(tags.items()), key=(lambda x: x[0]))) if (tag_tuple not in self._cached_params): self._cached_params[tag_tuple] = self.get_params_internal(**tags) return self._cached_params[tag_tuple]
'Compute the symbolic KL divergence of two distributions'
def kl_sym(self, old_dist_info_vars, new_dist_info_vars):
raise NotImplementedError
'Compute the KL divergence of two distributions'
def kl(self, old_dist_info, new_dist_info):
raise NotImplementedError
'Compute the symbolic KL divergence of two categorical distributions'
def kl_sym(self, old_dist_info_vars, new_dist_info_vars):
old_prob_var = old_dist_info_vars['prob'] new_prob_var = new_dist_info_vars['prob'] return tf.reduce_sum((old_prob_var * (tf.log((old_prob_var + TINY)) - tf.log((new_prob_var + TINY)))), axis=2)
'Compute the KL divergence of two categorical distributions'
def kl(self, old_dist_info, new_dist_info):
old_prob = old_dist_info['prob'] new_prob = new_dist_info['prob'] return np.sum((old_prob * (np.log((old_prob + TINY)) - np.log((new_prob + TINY)))), axis=2)
'Compute the symbolic KL divergence of two categorical distributions'
def kl_sym(self, old_dist_info_vars, new_dist_info_vars):
old_prob_var = old_dist_info_vars['prob'] new_prob_var = new_dist_info_vars['prob'] ndims = old_prob_var.get_shape().ndims return tf.reduce_sum((old_prob_var * (tf.log((old_prob_var + TINY)) - tf.log((new_prob_var + TINY)))), axis=(ndims - 1))
'Compute the KL divergence of two categorical distributions'
def kl(self, old_dist_info, new_dist_info):
old_prob = old_dist_info['prob'] new_prob = new_dist_info['prob'] return np.sum((old_prob * (np.log((old_prob + TINY)) - np.log((new_prob + TINY)))), axis=(-1))
':param loss: Symbolic expression for the loss function. :param target: A parameterized object to optimize over. It should implement methods of the :class:`rllab.core.paramerized.Parameterized` class. :param leq_constraint: A constraint provided as a tuple (f, epsilon), of the form f(*inputs) <= epsilon. :param inputs:...
def update_opt(self, loss, target, inputs, extra_inputs=None, *args, **kwargs):
self._target = target def get_opt_output(): flat_grad = tensor_utils.flatten_tensor_variables(tf.gradients(loss, target.get_params(trainable=True))) return [tf.cast(loss, tf.float64), tf.cast(flat_grad, tf.float64)] if (extra_inputs is None): extra_inputs = list() self._opt_fun =...
':param loss: Symbolic expression for the loss function. :param target: A parameterized object to optimize over. It should implement methods of the :class:`rllab.core.paramerized.Parameterized` class. :param leq_constraint: A constraint provided as a tuple (f, epsilon), of the form f(*inputs) <= epsilon. :param inputs:...
def update_opt(self, loss, target, leq_constraint, inputs, constraint_name='constraint', *args, **kwargs):
(constraint_term, constraint_value) = leq_constraint with tf.variable_scope(self._name): penalty_var = tf.placeholder(tf.float32, tuple(), name='penalty') penalized_loss = (loss + (penalty_var * constraint_term)) self._target = target self._max_constraint_val = constraint_value self._con...
':param cg_iters: The number of CG iterations used to calculate A^-1 g :param reg_coeff: A small value so that A -> A + reg*I :param subsample_factor: Subsampling factor to reduce samples when using "conjugate gradient. Since the computation time for the descent direction dominates, this can greatly reduce the overall ...
def __init__(self, cg_iters=10, reg_coeff=1e-05, subsample_factor=1.0, backtrack_ratio=0.8, max_backtracks=15, debug_nan=False, accept_violation=False, hvp_approach=None, num_slices=1):
Serializable.quick_init(self, locals()) self._cg_iters = cg_iters self._reg_coeff = reg_coeff self._subsample_factor = subsample_factor self._backtrack_ratio = backtrack_ratio self._max_backtracks = max_backtracks self._num_slices = num_slices self._opt_fun = None self._target = None...
':param loss: Symbolic expression for the loss function. :param target: A parameterized object to optimize over. It should implement methods of the :class:`rllab.core.paramerized.Parameterized` class. :param leq_constraint: A constraint provided as a tuple (f, epsilon), of the form f(*inputs) <= epsilon. :param inputs:...
def update_opt(self, loss, target, leq_constraint, inputs, extra_inputs=None, constraint_name='constraint', *args, **kwargs):
inputs = tuple(inputs) if (extra_inputs is None): extra_inputs = tuple() else: extra_inputs = tuple(extra_inputs) (constraint_term, constraint_value) = leq_constraint params = target.get_params(trainable=True) grads = tf.gradients(loss, xs=params) for (idx, (grad, param)) in ...
':param max_epochs: :param tolerance: :param update_method: :param batch_size: None or an integer. If None the whole dataset will be used. :param callback: :param kwargs: :return:'
def __init__(self, tf_optimizer_cls=None, tf_optimizer_args=None, max_epochs=1000, tolerance=1e-06, batch_size=32, callback=None, verbose=False, **kwargs):
Serializable.quick_init(self, locals()) self._opt_fun = None self._target = None self._callback = callback if (tf_optimizer_cls is None): tf_optimizer_cls = tf.train.AdamOptimizer if (tf_optimizer_args is None): tf_optimizer_args = dict(learning_rate=0.001) self._tf_optimizer...
':param loss: Symbolic expression for the loss function. :param target: A parameterized object to optimize over. It should implement methods of the :class:`rllab.core.paramerized.Parameterized` class. :param leq_constraint: A constraint provided as a tuple (f, epsilon), of the form f(*inputs) <= epsilon. :param inputs:...
def update_opt(self, loss, target, inputs, extra_inputs=None, **kwargs):
self._target = target self._train_op = self._tf_optimizer.minimize(loss, var_list=target.get_params(trainable=True)) if (extra_inputs is None): extra_inputs = list() self._input_vars = (inputs + extra_inputs) self._opt_fun = ext.lazydict(f_loss=(lambda : tensor_utils.compile_function((inputs...
':param env_spec: A spec for the env. :param hidden_dim: dimension of hidden layer :param hidden_nonlinearity: nonlinearity used for each hidden layer :return:'
def __init__(self, name, env_spec, hidden_dim=32, feature_network=None, state_include_action=True, hidden_nonlinearity=tf.tanh, learn_std=True, init_std=1.0, output_nonlinearity=None, lstm_layer_cls=L.LSTMLayer, use_peepholes=False):
with tf.variable_scope(name): Serializable.quick_init(self, locals()) super(GaussianLSTMPolicy, self).__init__(env_spec) obs_dim = env_spec.observation_space.flat_dim action_dim = env_spec.action_space.flat_dim if state_include_action: input_dim = (obs_dim + actio...
'Indicates whether the policy is vectorized. If True, it should implement get_actions(), and support resetting with multiple simultaneous states.'
@property def vectorized(self):
return False
'Indicates whether the policy is recurrent. :return:'
@property def recurrent(self):
return False
'Log extra information per iteration based on the collected paths'
def log_diagnostics(self, paths):
pass
'Return keys for the information related to the policy\'s state when taking an action. :return:'
@property def state_info_keys(self):
return [k for (k, _) in self.state_info_specs]
'Return keys and shapes for the information related to the policy\'s state when taking an action. :return:'
@property def state_info_specs(self):
return list()
'Clean up operation'
def terminate(self):
pass
':rtype Distribution'
@property def distribution(self):
raise NotImplementedError