code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def __init__(self, app, *, options=None): """Initialize a new standalone application. Args: app: A wsgi Python application. options (dict): the configuration. """ self.options = options or {} self.application = app super().__init__()
Initialize a new standalone application. Args: app: A wsgi Python application. options (dict): the configuration.
__init__
python
bigchaindb/bigchaindb
bigchaindb/web/server.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/server.py
Apache-2.0
def create_app(*, debug=False, threads=1, bigchaindb_factory=None): """Return an instance of the Flask application. Args: debug (bool): a flag to activate the debug mode for the app (default: False). threads (int): number of threads to use Return: an instance of the Flas...
Return an instance of the Flask application. Args: debug (bool): a flag to activate the debug mode for the app (default: False). threads (int): number of threads to use Return: an instance of the Flask application.
create_app
python
bigchaindb/bigchaindb
bigchaindb/web/server.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/server.py
Apache-2.0
def create_server(settings, log_config=None, bigchaindb_factory=None): """Wrap and return an application ready to be run. Args: settings (dict): a dictionary containing the settings, more info here http://docs.gunicorn.org/en/latest/settings.html Return: an initialized instance...
Wrap and return an application ready to be run. Args: settings (dict): a dictionary containing the settings, more info here http://docs.gunicorn.org/en/latest/settings.html Return: an initialized instance of the application.
create_server
python
bigchaindb/bigchaindb
bigchaindb/web/server.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/server.py
Apache-2.0
def __call__(self, environ, start_response): """Run the middleware and then call the original WSGI application.""" if environ['REQUEST_METHOD'] == 'GET': try: del environ['CONTENT_TYPE'] except KeyError: pass else: logg...
Run the middleware and then call the original WSGI application.
__call__
python
bigchaindb/bigchaindb
bigchaindb/web/strip_content_type_middleware.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/strip_content_type_middleware.py
Apache-2.0
def _multiprocessing_to_asyncio(in_queue, out_queue, loop): """Bridge between a synchronous multiprocessing queue and an asynchronous asyncio queue. Args: in_queue (multiprocessing.Queue): input queue out_queue (asyncio.Queue): output queue """ while True: value = in_queue....
Bridge between a synchronous multiprocessing queue and an asynchronous asyncio queue. Args: in_queue (multiprocessing.Queue): input queue out_queue (asyncio.Queue): output queue
_multiprocessing_to_asyncio
python
bigchaindb/bigchaindb
bigchaindb/web/websocket_server.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/websocket_server.py
Apache-2.0
def __init__(self, event_source): """Create a new instance. Args: event_source: a source of events. Elements in the queue should be strings. """ self.event_source = event_source self.subscribers = {}
Create a new instance. Args: event_source: a source of events. Elements in the queue should be strings.
__init__
python
bigchaindb/bigchaindb
bigchaindb/web/websocket_server.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/websocket_server.py
Apache-2.0
async def publish(self): """Publish new events to the subscribers.""" while True: event = await self.event_source.get() str_buffer = [] if event == POISON_PILL: return if isinstance(event, str): str_buffer.append(event) ...
Publish new events to the subscribers.
publish
python
bigchaindb/bigchaindb
bigchaindb/web/websocket_server.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/websocket_server.py
Apache-2.0
def init_app(event_source, *, loop=None): """Init the application server. Return: An aiohttp application. """ dispatcher = Dispatcher(event_source) # Schedule the dispatcher loop.create_task(dispatcher.publish()) app = web.Application(loop=loop) app['dispatcher'] = dispatcher...
Init the application server. Return: An aiohttp application.
init_app
python
bigchaindb/bigchaindb
bigchaindb/web/websocket_server.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/websocket_server.py
Apache-2.0
def start(sync_event_source, loop=None): """Create and start the WebSocket server.""" if not loop: loop = asyncio.get_event_loop() event_source = asyncio.Queue(loop=loop) bridge = threading.Thread(target=_multiprocessing_to_asyncio, args=(sync_event_source, event...
Create and start the WebSocket server.
start
python
bigchaindb/bigchaindb
bigchaindb/web/websocket_server.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/websocket_server.py
Apache-2.0
def base_ws_uri(): """Base websocket URL that is advertised to external clients. Useful when the websocket URL advertised to the clients needs to be customized (typically when running behind NAT, firewall, etc.) """ config_wsserver = config['wsserver'] scheme = config_wsserver['advertised_sch...
Base websocket URL that is advertised to external clients. Useful when the websocket URL advertised to the clients needs to be customized (typically when running behind NAT, firewall, etc.)
base_ws_uri
python
bigchaindb/bigchaindb
bigchaindb/web/views/base.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/views/base.py
Apache-2.0
def get(self, block_id): """API endpoint to get details about a block. Args: block_id (str): the id of the block. Return: A JSON string containing the data about the block. """ pool = current_app.config['bigchain_pool'] with pool() as bigchain:...
API endpoint to get details about a block. Args: block_id (str): the id of the block. Return: A JSON string containing the data about the block.
get
python
bigchaindb/bigchaindb
bigchaindb/web/views/blocks.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/views/blocks.py
Apache-2.0
def get(self): """API endpoint to get the related blocks for a transaction. Return: A ``list`` of ``block_id``s that contain the given transaction. The list may be filtered when provided a status query parameter: "valid", "invalid", "undecided". """ p...
API endpoint to get the related blocks for a transaction. Return: A ``list`` of ``block_id``s that contain the given transaction. The list may be filtered when provided a status query parameter: "valid", "invalid", "undecided".
get
python
bigchaindb/bigchaindb
bigchaindb/web/views/blocks.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/views/blocks.py
Apache-2.0
def get_api_v1_info(api_prefix): """Return a dict with all the information specific for the v1 of the api. """ websocket_root = base_ws_uri() + EVENTS_ENDPOINT docs_url = [ 'https://docs.bigchaindb.com/projects/server/en/v', version.__version__, '/http-client-server-api.html'...
Return a dict with all the information specific for the v1 of the api.
get_api_v1_info
python
bigchaindb/bigchaindb
bigchaindb/web/views/info.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/views/info.py
Apache-2.0
def get(self): """API endpoint to retrieve a list of links to transaction outputs. Returns: A :obj:`list` of :cls:`str` of links to outputs. """ parser = reqparse.RequestParser() parser.add_argument('public_key', type=parameters.valid_ed25519, ...
API endpoint to retrieve a list of links to transaction outputs. Returns: A :obj:`list` of :cls:`str` of links to outputs.
get
python
bigchaindb/bigchaindb
bigchaindb/web/views/outputs.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/views/outputs.py
Apache-2.0
def get(self, tx_id): """API endpoint to get details about a transaction. Args: tx_id (str): the id of the transaction. Return: A JSON string containing the data about the transaction. """ pool = current_app.config['bigchain_pool'] with pool() a...
API endpoint to get details about a transaction. Args: tx_id (str): the id of the transaction. Return: A JSON string containing the data about the transaction.
get
python
bigchaindb/bigchaindb
bigchaindb/web/views/transactions.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/views/transactions.py
Apache-2.0
def post(self): """API endpoint to push transactions to the Federation. Return: A ``dict`` containing the data about the transaction. """ parser = reqparse.RequestParser() parser.add_argument('mode', type=parameters.valid_mode, default=BRO...
API endpoint to push transactions to the Federation. Return: A ``dict`` containing the data about the transaction.
post
python
bigchaindb/bigchaindb
bigchaindb/web/views/transactions.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/views/transactions.py
Apache-2.0
def get(self): """API endpoint to get validators set. Return: A JSON string containing the validator set of the current node. """ pool = current_app.config['bigchain_pool'] with pool() as bigchain: validators = bigchain.get_validators() return ...
API endpoint to get validators set. Return: A JSON string containing the validator set of the current node.
get
python
bigchaindb/bigchaindb
bigchaindb/web/views/validators.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/views/validators.py
Apache-2.0
def generate_validators(powers): """Generates an arbitrary number of validators with random public keys. The object under the `storage` key is in the format expected by DB. The object under the `eleciton` key is in the format expected by the upsert validator election. `public_key`, `p...
Generates an arbitrary number of validators with random public keys. The object under the `storage` key is in the format expected by DB. The object under the `eleciton` key is in the format expected by the upsert validator election. `public_key`, `private_key` are in the format used for s...
generate_validators
python
bigchaindb/bigchaindb
tests/utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/tests/utils.py
Apache-2.0
def _test_additionalproperties(node, path=''): """Validate that each object node has additionalProperties set, so that objects with junk keys do not pass as valid. """ if isinstance(node, list): for i, nnode in enumerate(node): _test_additionalproperties(nnode, path + str(i) + '.') ...
Validate that each object node has additionalProperties set, so that objects with junk keys do not pass as valid.
_test_additionalproperties
python
bigchaindb/bigchaindb
tests/common/test_schema.py
https://github.com/bigchaindb/bigchaindb/blob/master/tests/common/test_schema.py
Apache-2.0
def test_cant_spend_same_input_twice_in_tx(b, alice): """Recreate duplicated fulfillments bug https://github.com/bigchaindb/bigchaindb/issues/1099 """ from bigchaindb.models import Transaction from bigchaindb.common.exceptions import DoubleSpend # create a divisible asset tx_create = Transa...
Recreate duplicated fulfillments bug https://github.com/bigchaindb/bigchaindb/issues/1099
test_cant_spend_same_input_twice_in_tx
python
bigchaindb/bigchaindb
tests/db/test_bigchain_api.py
https://github.com/bigchaindb/bigchaindb/blob/master/tests/db/test_bigchain_api.py
Apache-2.0
def get_txs_patched(conn, **args): """Patch `get_transactions_filtered` so that rather than return an array of transactions it returns an array of shims with a to_dict() method that reports one of the arguments passed to `get_transactions_filtered`. """ return [type('...
Patch `get_transactions_filtered` so that rather than return an array of transactions it returns an array of shims with a to_dict() method that reports one of the arguments passed to `get_transactions_filtered`.
get_txs_patched
python
bigchaindb/bigchaindb
tests/web/test_transactions.py
https://github.com/bigchaindb/bigchaindb/blob/master/tests/web/test_transactions.py
Apache-2.0
def call(self, x, training=None): """ Apply random channel-swap augmentation to `x`. Args: x (`Tensor`): A batch tensor of 1D (signals) or 2D (spectrograms) data """ if training in (None, False): return x # figure out input data format if...
Apply random channel-swap augmentation to `x`. Args: x (`Tensor`): A batch tensor of 1D (signals) or 2D (spectrograms) data
call
python
keunwoochoi/kapre
kapre/augmentation.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/augmentation.py
MIT
def _apply_masks_to_axis(self, x, axis, mask_param, n_masks): """ Applies a number of masks (defined by the parameter n_masks) to the spectrogram by the axis provided. Args: x (float `Tensor`): A spectrogram. Its shape is (time, freq, ch) or (ch, time, freq) ...
Applies a number of masks (defined by the parameter n_masks) to the spectrogram by the axis provided. Args: x (float `Tensor`): A spectrogram. Its shape is (time, freq, ch) or (ch, time, freq) depending on data_format. axis (int): The axis where the m...
_apply_masks_to_axis
python
keunwoochoi/kapre
kapre/augmentation.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/augmentation.py
MIT
def _apply_spec_augment(self, x): """ Main method that applies SpecAugment technique by both frequency and time axis. Args: x (float `Tensor`) : A spectrogram. Its shape is (time, freq, ch) or (ch, time, freq) depending on data_format. Returns: ...
Main method that applies SpecAugment technique by both frequency and time axis. Args: x (float `Tensor`) : A spectrogram. Its shape is (time, freq, ch) or (ch, time, freq) depending on data_format. Returns: (float `Tensor`): The spectrogram ma...
_apply_spec_augment
python
keunwoochoi/kapre
kapre/augmentation.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/augmentation.py
MIT
def get_window_fn(window_name=None): """Return a window function given its name. This function is used inside layers such as `STFT` to get a window function. Args: window_name (None or str): name of window function. On Tensorflow 2.3, there are five windows available in `tf.signal` (`hammin...
Return a window function given its name. This function is used inside layers such as `STFT` to get a window function. Args: window_name (None or str): name of window function. On Tensorflow 2.3, there are five windows available in `tf.signal` (`hamming_window`, `hann_window`, `kaiser_bessel_der...
get_window_fn
python
keunwoochoi/kapre
kapre/backend.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/backend.py
MIT
def validate_data_format_str(data_format): """A function that validates the data format string.""" if data_format not in (_CH_DEFAULT_STR, _CH_FIRST_STR, _CH_LAST_STR): raise ValueError( 'data_format should be one of {}'.format( str([_CH_FIRST_STR, _CH_LAST_STR, _CH_DEFAULT_S...
A function that validates the data format string.
validate_data_format_str
python
keunwoochoi/kapre
kapre/backend.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/backend.py
MIT
def magnitude_to_decibel(x, ref_value=1.0, amin=1e-5, dynamic_range=80.0): """A function that converts magnitude to decibel scaling. In essence, it runs `10 * log10(x)`, but with some other utility operations. Similar to `librosa.power_to_db` with `ref=1.0` and `top_db=dynamic_range` Args: x (...
A function that converts magnitude to decibel scaling. In essence, it runs `10 * log10(x)`, but with some other utility operations. Similar to `librosa.power_to_db` with `ref=1.0` and `top_db=dynamic_range` Args: x (`Tensor`): float tensor. Can be batch or not. Something like magnitude of STFT. ...
magnitude_to_decibel
python
keunwoochoi/kapre
kapre/backend.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/backend.py
MIT
def filterbank_mel( sample_rate, n_freq, n_mels=128, f_min=0.0, f_max=None, htk=False, norm='slaney' ): """A wrapper for librosa.filters.mel that additionally does transpose and tensor conversion Args: sample_rate (`int`): sample rate of the input audio n_freq (`int`): number of frequency b...
A wrapper for librosa.filters.mel that additionally does transpose and tensor conversion Args: sample_rate (`int`): sample rate of the input audio n_freq (`int`): number of frequency bins in the input STFT magnitude. n_mels (`int`): the number of mel bands f_min (`float`): lowest fr...
filterbank_mel
python
keunwoochoi/kapre
kapre/backend.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/backend.py
MIT
def get_stft_magnitude_layer( input_shape=None, n_fft=2048, win_length=None, hop_length=None, window_name=None, pad_begin=False, pad_end=False, return_decibel=False, db_amin=1e-5, db_ref_value=1.0, db_dynamic_range=80.0, input_data_format='default', output_data_format...
A function that returns a stft magnitude layer. The layer is a `keras.Sequential` model consists of `STFT`, `Magnitude`, and optionally `MagnitudeToDecibel`. Args: input_shape (None or tuple of integers): input shape of the model. Necessary only if this melspectrogram layer is is the first ...
get_stft_magnitude_layer
python
keunwoochoi/kapre
kapre/composed.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/composed.py
MIT
def get_melspectrogram_layer( input_shape=None, n_fft=2048, win_length=None, hop_length=None, window_name=None, pad_begin=False, pad_end=False, sample_rate=22050, n_mels=128, mel_f_min=0.0, mel_f_max=None, mel_htk=False, mel_norm='slaney', return_decibel=False, ...
A function that returns a melspectrogram layer, which is a `keras.Sequential` model consists of `STFT`, `Magnitude`, `ApplyFilterbank(_mel_filterbank)`, and optionally `MagnitudeToDecibel`. Args: input_shape (None or tuple of integers): input shape of the model. Necessary only if this melspectrogram la...
get_melspectrogram_layer
python
keunwoochoi/kapre
kapre/composed.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/composed.py
MIT
def get_log_frequency_spectrogram_layer( input_shape=None, n_fft=2048, win_length=None, hop_length=None, window_name=None, pad_begin=False, pad_end=False, sample_rate=22050, log_n_bins=84, log_f_min=None, log_bins_per_octave=12, log_spread=0.125, return_decibel=False,...
A function that returns a log-frequency STFT layer, which is a `keras.Sequential` model consists of `STFT`, `Magnitude`, `ApplyFilterbank(_log_filterbank)`, and optionally `MagnitudeToDecibel`. Args: input_shape (None or tuple of integers): input shape of the model if this melspectrogram layer is ...
get_log_frequency_spectrogram_layer
python
keunwoochoi/kapre
kapre/composed.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/composed.py
MIT
def get_perfectly_reconstructing_stft_istft( stft_input_shape=None, istft_input_shape=None, n_fft=2048, win_length=None, hop_length=None, forward_window_name=None, waveform_data_format='default', stft_data_format='default', stft_name='stft', istft_name='istft', ): """A functi...
A function that returns two layers, stft and inverse stft, which would be perfectly reconstructing pair. Args: stft_input_shape (tuple): Input shape of single waveform. Must specify this if the returned stft layer is going to be used as first layer of a Sequential model. istft_input_sha...
get_perfectly_reconstructing_stft_istft
python
keunwoochoi/kapre
kapre/composed.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/composed.py
MIT
def get_stft_mag_phase( input_shape, n_fft=2048, win_length=None, hop_length=None, window_name=None, pad_begin=False, pad_end=False, return_decibel=False, db_amin=1e-5, db_ref_value=1.0, db_dynamic_range=80.0, input_data_format='default', output_data_format='default',...
A function that returns magnitude and phase of input audio. Args: input_shape (None or tuple of integers): input shape of the stft layer. Because this mag_phase is based on keras.Functional model, it is required to specify the input shape. E.g., (44100, 2) for 44100-sample stereo au...
get_stft_mag_phase
python
keunwoochoi/kapre
kapre/composed.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/composed.py
MIT
def get_frequency_aware_conv2d( data_format='default', freq_aware_name='frequency_aware_conv2d', *args, **kwargs ): """Returns a frequency-aware conv2d layer. Args: data_format (str): specifies the data format of batch input/output. freq_aware_name (str): name of the returned layer ...
Returns a frequency-aware conv2d layer. Args: data_format (str): specifies the data format of batch input/output. freq_aware_name (str): name of the returned layer *args: position args for `keras.layers.Conv2D`. **kwargs: keyword args for `keras.layers.Conv2D`. Returns: ...
get_frequency_aware_conv2d
python
keunwoochoi/kapre
kapre/composed.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/composed.py
MIT
def call(self, x): """ Args: x (`Tensor`): batch audio signal in the specified 1D format in initiation. Returns: (`Tensor`): A framed tensor. The shape is (batch, time (frames), frame_length, channel) if `channels_last`, or (batch, channel, time (frames), fra...
Args: x (`Tensor`): batch audio signal in the specified 1D format in initiation. Returns: (`Tensor`): A framed tensor. The shape is (batch, time (frames), frame_length, channel) if `channels_last`, or (batch, channel, time (frames), frame_length) if `channels_first`...
call
python
keunwoochoi/kapre
kapre/signal.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/signal.py
MIT
def call(self, x): """ Args: x (`Tensor`): batch audio signal in the specified 1D format in initiation. Returns: (`Tensor`): A framed tensor. The shape is (batch, time (frames), channel) if `channels_last`, or (batch, channel, time (frames)) if `channels_firs...
Args: x (`Tensor`): batch audio signal in the specified 1D format in initiation. Returns: (`Tensor`): A framed tensor. The shape is (batch, time (frames), channel) if `channels_last`, or (batch, channel, time (frames)) if `channels_first`.
call
python
keunwoochoi/kapre
kapre/signal.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/signal.py
MIT
def call(self, log_melgrams): """ Args: log_melgrams (float `Tensor`): a batch of log_melgrams. `(b, time, mel, ch)` if `channels_last` and `(b, ch, time, mel)` if `channels_first`. Returns: (float `Tensor`): MFCCs. `(batch, time, n_mfccs, ch...
Args: log_melgrams (float `Tensor`): a batch of log_melgrams. `(b, time, mel, ch)` if `channels_last` and `(b, ch, time, mel)` if `channels_first`. Returns: (float `Tensor`): MFCCs. `(batch, time, n_mfccs, ch)` if `channels_last`, `(batch, ch, time,...
call
python
keunwoochoi/kapre
kapre/signal.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/signal.py
MIT
def _rdft(signal, dft_length): """DFT for real signals. Calculates the onesided dft, assuming real signal implies complex conjugate symetry, hence only onesided DFT is returned. Args: signal (tensor) signal to transform, assumes that the last dimension is the time dimension signal c...
DFT for real signals. Calculates the onesided dft, assuming real signal implies complex conjugate symetry, hence only onesided DFT is returned. Args: signal (tensor) signal to transform, assumes that the last dimension is the time dimension signal can be framed, e.g. (1, 40, 1024) for a...
_rdft
python
keunwoochoi/kapre
kapre/tflite_compatible_stft.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/tflite_compatible_stft.py
MIT
def fixed_frame(signal, frame_length, frame_step): """tflite-compatible tf.signal.frame for fixed-size input. Args: signal: Tensor containing signal(s). frame_length: Number of samples to put in each frame. frame_step: Sample advance between successive frames. Returns: A ne...
tflite-compatible tf.signal.frame for fixed-size input. Args: signal: Tensor containing signal(s). frame_length: Number of samples to put in each frame. frame_step: Sample advance between successive frames. Returns: A new tensor where the last axis (or first, if first_axis) of ...
fixed_frame
python
keunwoochoi/kapre
kapre/tflite_compatible_stft.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/tflite_compatible_stft.py
MIT
def stft_tflite(signal, frame_length, frame_step, fft_length, window_fn, pad_end): """tflite-compatible implementation of tf.signal.stft. Compute the short-time Fourier transform of a 1D input while avoiding tf ops that are not currently supported in tflite (Rfft, Range, SplitV). fft_length must be fixe...
tflite-compatible implementation of tf.signal.stft. Compute the short-time Fourier transform of a 1D input while avoiding tf ops that are not currently supported in tflite (Rfft, Range, SplitV). fft_length must be fixed. A Hann window is of frame_length is always applied. Since fixed (precomputed) f...
stft_tflite
python
keunwoochoi/kapre
kapre/tflite_compatible_stft.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/tflite_compatible_stft.py
MIT
def continued_fraction_arctan(x, n=100, dtype=tf.float32): """Continued fraction Approximation to the arctan function Approximate solution to arctan(x), atan is not a natively supported tflite op (or a flex op). n is the number of iterations, the high the more accurate. Accuracy is poor whe...
Continued fraction Approximation to the arctan function Approximate solution to arctan(x), atan is not a natively supported tflite op (or a flex op). n is the number of iterations, the high the more accurate. Accuracy is poor when the argument is large. https://functions.wolfram.com/Ele...
continued_fraction_arctan
python
keunwoochoi/kapre
kapre/tflite_compatible_stft.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/tflite_compatible_stft.py
MIT
def atan2_tflite(y, x, n=100, dtype=tf.float32): """Approximation to the atan2 function atan is not a tflite supported op or flex op, thus this uses an Approximation Poor accuracy when either x is very small or y is very large. https://en.wikipedia.org/wiki/Atan2 Args: y (tenso...
Approximation to the atan2 function atan is not a tflite supported op or flex op, thus this uses an Approximation Poor accuracy when either x is very small or y is very large. https://en.wikipedia.org/wiki/Atan2 Args: y (tensor) - vertical component of tangent (or imaginary part of...
atan2_tflite
python
keunwoochoi/kapre
kapre/tflite_compatible_stft.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/tflite_compatible_stft.py
MIT
def _shape_spectrum_output(spectrums, data_format): """Shape batch spectrograms into the right format. Args: spectrums (`Tensor`): result of tf.signal.stft or similar, i.e., (..., time, freq). data_format (`str`): 'channels_first' or 'channels_last' Returns: spectrums (`Tensor`): a...
Shape batch spectrograms into the right format. Args: spectrums (`Tensor`): result of tf.signal.stft or similar, i.e., (..., time, freq). data_format (`str`): 'channels_first' or 'channels_last' Returns: spectrums (`Tensor`): a transposed version of input `spectrums`
_shape_spectrum_output
python
keunwoochoi/kapre
kapre/time_frequency.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py
MIT
def call(self, x): """ Compute STFT of the input signal. If the `time` axis is not the last axis of `x`, it should be transposed first. Args: x (float `Tensor`): batch of audio signals, (batch, ch, time) or (batch, time, ch) based on input_data_format Return: (c...
Compute STFT of the input signal. If the `time` axis is not the last axis of `x`, it should be transposed first. Args: x (float `Tensor`): batch of audio signals, (batch, ch, time) or (batch, time, ch) based on input_data_format Return: (complex `Tensor`): A STFT repre...
call
python
keunwoochoi/kapre
kapre/time_frequency.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py
MIT
def call(self, x): """ Compute inverse STFT of the input STFT. Args: x (complex `Tensor`): batch of STFTs, (batch, ch, time, freq) or (batch, time, freq, ch) depending on `input_data_format` Return: (`float`): audio signals of x. Shape: 1D batch shape. I.e., (ba...
Compute inverse STFT of the input STFT. Args: x (complex `Tensor`): batch of STFTs, (batch, ch, time, freq) or (batch, time, freq, ch) depending on `input_data_format` Return: (`float`): audio signals of x. Shape: 1D batch shape. I.e., (batch, time, ch) or (batch, ch, ...
call
python
keunwoochoi/kapre
kapre/time_frequency.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py
MIT
def call(self, x): """ Args: x (complex `Tensor`): input complex tensor Returns: (float `Tensor`): phase of `x` (Radian) """ if self.approx_atan_accuracy: return atan2_tflite(tf.math.imag(x), tf.math.real(x), n=self.approx_atan_accuracy) ...
Args: x (complex `Tensor`): input complex tensor Returns: (float `Tensor`): phase of `x` (Radian)
call
python
keunwoochoi/kapre
kapre/time_frequency.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py
MIT
def call(self, x): """ Args: x (`Tensor`): float tensor. Can be batch or not. Something like magnitude of STFT. Returns: (`Tensor`): decibel-scaled float tensor of `x`. """ return backend.magnitude_to_decibel( x, ref_value=self.ref_value, amin...
Args: x (`Tensor`): float tensor. Can be batch or not. Something like magnitude of STFT. Returns: (`Tensor`): decibel-scaled float tensor of `x`.
call
python
keunwoochoi/kapre
kapre/time_frequency.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py
MIT
def call(self, x): """ Apply filterbank to `x`. Args: x (`Tensor`): float tensor in 2D batch shape. """ # x: 2d batch input. (b, t, fr, ch) or (b, ch, t, fr) output = tf.tensordot(x, self.filterbank, axes=(self.freq_axis, 0)) # ch_last -> (b, t, ch, ...
Apply filterbank to `x`. Args: x (`Tensor`): float tensor in 2D batch shape.
call
python
keunwoochoi/kapre
kapre/time_frequency.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py
MIT
def call(self, x): """ Args: x (`Tensor`): a 2d batch (b, t, f, ch) or (b, ch, t, f) Returns: (`Tensor`): A tensor with the same shape as input data. """ if self.data_format == 'channels_first': x = K.permute_dimensions(x, (0, 2, 3, 1)) ...
Args: x (`Tensor`): a 2d batch (b, t, f, ch) or (b, ch, t, f) Returns: (`Tensor`): A tensor with the same shape as input data.
call
python
keunwoochoi/kapre
kapre/time_frequency.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py
MIT
def call(self, x): """ Compute STFT of the input signal. If the `time` axis is not the last axis of `x`, it should be transposed first. Args: x (float `Tensor`): batch of audio signals, (batch, ch, time) or (batch, time, ch) based on input_data_format Return: (r...
Compute STFT of the input signal. If the `time` axis is not the last axis of `x`, it should be transposed first. Args: x (float `Tensor`): batch of audio signals, (batch, ch, time) or (batch, time, ch) based on input_data_format Return: (real `Tensor`): A STFT represen...
call
python
keunwoochoi/kapre
kapre/time_frequency_tflite.py
https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency_tflite.py
MIT
def test_spec_augment_apply_masks_to_axis(inputs): """ Tests the method _apply_masks_to_axis to see if shape is kept and exceptions are caught """ data_format, axis, mask_param, n_masks = inputs batch_src, input_shape = get_spectrogram(data_format) spec_augment = SpecAugment( input...
Tests the method _apply_masks_to_axis to see if shape is kept and exceptions are caught
test_spec_augment_apply_masks_to_axis
python
keunwoochoi/kapre
tests/test_augmentation.py
https://github.com/keunwoochoi/kapre/blob/master/tests/test_augmentation.py
MIT
def test_spec_augment_depth_exception(): """ Checks that SpecAugments fails if Spectrogram has depth greater than 1. """ data_format = "default" with pytest.raises(RuntimeError): batch_src, input_shape = get_spectrogram(data_format=data_format, n_ch=4) model = tf.keras.Sequential(...
Checks that SpecAugments fails if Spectrogram has depth greater than 1.
test_spec_augment_depth_exception
python
keunwoochoi/kapre
tests/test_augmentation.py
https://github.com/keunwoochoi/kapre/blob/master/tests/test_augmentation.py
MIT
def test_spec_augment_layer(data_format, atol=1e-4): """ Tests the complete layer, checking if the parameter `training` has the expected behaviour. """ batch_src, input_shape = get_spectrogram(data_format) model = tf.keras.Sequential() spec_augment = SpecAugment( input_shape=input_shap...
Tests the complete layer, checking if the parameter `training` has the expected behaviour.
test_spec_augment_layer
python
keunwoochoi/kapre
tests/test_augmentation.py
https://github.com/keunwoochoi/kapre/blob/master/tests/test_augmentation.py
MIT
def test_filterbank_log(sample_rate, n_freq, n_bins, bins_per_octave, f_min, spread): """It only tests if the function is a valid wrapper""" log_fb = KPB.filterbank_log( sample_rate=sample_rate, n_freq=n_freq, n_bins=n_bins, bins_per_octave=bins_per_octave, f_min=f_min, ...
It only tests if the function is a valid wrapper
test_filterbank_log
python
keunwoochoi/kapre
tests/test_backend.py
https://github.com/keunwoochoi/kapre/blob/master/tests/test_backend.py
MIT
def allclose_phase(a, b, atol=1e-3): """Testing phase. Remember that a small error in complex value may lead to a large phase difference if the norm is very small. Therefore, it makes more sense to test it on the complex value itself rather than breaking it down to phase. """ np.testing.assert...
Testing phase. Remember that a small error in complex value may lead to a large phase difference if the norm is very small. Therefore, it makes more sense to test it on the complex value itself rather than breaking it down to phase.
allclose_phase
python
keunwoochoi/kapre
tests/test_time_frequency.py
https://github.com/keunwoochoi/kapre/blob/master/tests/test_time_frequency.py
MIT
def assert_approx_phase(a, b, atol=1e-2, acceptable_fail_ratio=0.01): """Testing approximate phase. Tflite phase is approximate, some values will always have a large error So makes more sense to count the number that are within tolerance """ count_failed = np.sum(np.abs(a - b) > atol) assert ( ...
Testing approximate phase. Tflite phase is approximate, some values will always have a large error So makes more sense to count the number that are within tolerance
assert_approx_phase
python
keunwoochoi/kapre
tests/test_time_frequency.py
https://github.com/keunwoochoi/kapre/blob/master/tests/test_time_frequency.py
MIT
def test_melspectrogram_correctness( n_fft, sr, hop_length, n_ch, data_format, amin, dynamic_range, n_mels, mel_f_min, mel_f_max ): """Test the correctness of melspectrogram. Note that mel filterbank is tested separated """ def _get_melgram_model(return_decibel, amin, dynamic_range, input_shape=N...
Test the correctness of melspectrogram. Note that mel filterbank is tested separated
test_melspectrogram_correctness
python
keunwoochoi/kapre
tests/test_time_frequency.py
https://github.com/keunwoochoi/kapre/blob/master/tests/test_time_frequency.py
MIT
def test_log_spectrogram_runnable(data_format): """test if log spectrogram layer works well""" src_mono, batch_src, input_shape = get_audio(data_format=data_format, n_ch=1) _ = get_log_frequency_spectrogram_layer(input_shape, return_decibel=True) _ = get_log_frequency_spectrogram_layer(input_shape, retu...
test if log spectrogram layer works well
test_log_spectrogram_runnable
python
keunwoochoi/kapre
tests/test_time_frequency.py
https://github.com/keunwoochoi/kapre/blob/master/tests/test_time_frequency.py
MIT
def test_log_spectrogram_fail(): """test if log spectrogram layer works well""" src_mono, batch_src, input_shape = get_audio(data_format='channels_last', n_ch=1) _ = get_log_frequency_spectrogram_layer(input_shape, return_decibel=True, log_n_bins=200)
test if log spectrogram layer works well
test_log_spectrogram_fail
python
keunwoochoi/kapre
tests/test_time_frequency.py
https://github.com/keunwoochoi/kapre/blob/master/tests/test_time_frequency.py
MIT
def test_save_load(save_format): """test saving/loading of models that has stft, melspectorgrma, and log frequency.""" src_mono, batch_src, input_shape = get_audio(data_format='channels_last', n_ch=1) # test STFT save/load save_load_compare( STFT(input_shape=input_shape, pad_begin=True), ...
test saving/loading of models that has stft, melspectorgrma, and log frequency.
test_save_load
python
keunwoochoi/kapre
tests/test_time_frequency.py
https://github.com/keunwoochoi/kapre/blob/master/tests/test_time_frequency.py
MIT
def save_load_compare( layer, input_batch, allclose_func, save_format, layer_class=None, training=None, atol=1e-4 ): """test a model with `layer` with the given `input_batch`. The model prediction result is compared using `allclose_func` which may depend on the data type of the model output (e.g., float...
test a model with `layer` with the given `input_batch`. The model prediction result is compared using `allclose_func` which may depend on the data type of the model output (e.g., float or complex).
save_load_compare
python
keunwoochoi/kapre
tests/utils.py
https://github.com/keunwoochoi/kapre/blob/master/tests/utils.py
MIT
def predict_using_tflite(model, batch_src): """Convert a keras model to tflite and infer on batch_src Attempts to convert a keras model to a tflite model, load the tflite model, then infer on the data in batch_src Args: model (keras model) batch_src (numpy array) - audio to test model ...
Convert a keras model to tflite and infer on batch_src Attempts to convert a keras model to a tflite model, load the tflite model, then infer on the data in batch_src Args: model (keras model) batch_src (numpy array) - audio to test model Returns: pred_tflite (numpy array) - arr...
predict_using_tflite
python
keunwoochoi/kapre
tests/utils.py
https://github.com/keunwoochoi/kapre/blob/master/tests/utils.py
MIT
def add(ctx, task, priority, tags, extra, category, labels): """Add a new task to the to-do list. Note: Control the output of this using the verbosity option. """ if ctx.obj["verbose"] >= 2: click.echo(f"Adding task: {task}") click.echo(f"Priority: {priority}") click.echo(f'T...
Add a new task to the to-do list. Note: Control the output of this using the verbosity option.
add
python
Textualize/trogon
examples/demo.py
https://github.com/Textualize/trogon/blob/master/examples/demo.py
MIT
def remove(ctx, task_id): """Remove a task from the to-do list by its ID.""" if ctx.obj["verbose"] >= 1: click.echo(f"Removing task with ID: {task_id}") # Implement the task removal functionality here
Remove a task from the to-do list by its ID.
remove
python
Textualize/trogon
examples/demo.py
https://github.com/Textualize/trogon/blob/master/examples/demo.py
MIT
def list_tasks(ctx, all, completed): """List tasks from the to-do list.""" if ctx.obj["verbose"] >= 1: click.echo(f"Listing tasks:") # Implement the task listing functionality here
List tasks from the to-do list.
list_tasks
python
Textualize/trogon
examples/demo.py
https://github.com/Textualize/trogon/blob/master/examples/demo.py
MIT
def add(verbose, task, priority, tags, extra, category, labels): """Add a new task to the to-do list.""" if verbose >= 2: click.echo(f"Adding task: {task}") click.echo(f"Priority: {priority}") click.echo(f'Tags: {", ".join(tags)}') click.echo(f"Extra data: {extra}") click...
Add a new task to the to-do list.
add
python
Textualize/trogon
examples/nogroup_demo.py
https://github.com/Textualize/trogon/blob/master/examples/nogroup_demo.py
MIT
def detect_run_string(_main: ModuleType = sys.modules["__main__"]) -> str: """This is a slightly modified version of a function from Click.""" path = sys.argv[0] # The value of __package__ indicates how Python was called. It may # not exist if a setuptools script is installed as an egg. It may be #...
This is a slightly modified version of a function from Click.
detect_run_string
python
Textualize/trogon
trogon/detect_run_string.py
https://github.com/Textualize/trogon/blob/master/trogon/detect_run_string.py
MIT
def introspect_click_app(app: BaseCommand) -> dict[CommandName, CommandSchema]: """ Introspect a Click application and build a data structure containing information about all commands, options, arguments, and subcommands, including the docstrings and command function references. This function recur...
Introspect a Click application and build a data structure containing information about all commands, options, arguments, and subcommands, including the docstrings and command function references. This function recursively processes each command and its subcommands (if any), creating a nested dicti...
introspect_click_app
python
Textualize/trogon
trogon/introspect.py
https://github.com/Textualize/trogon/blob/master/trogon/introspect.py
MIT
def to_cli_args(self, include_root_command: bool = False) -> list[str]: """ Generates a list of strings representing the CLI invocation based on the user input data. Returns: A list of strings that can be passed to subprocess.run to execute the command. """ cli_args ...
Generates a list of strings representing the CLI invocation based on the user input data. Returns: A list of strings that can be passed to subprocess.run to execute the command.
to_cli_args
python
Textualize/trogon
trogon/run_command.py
https://github.com/Textualize/trogon/blob/master/trogon/run_command.py
MIT
def to_cli_string(self, include_root_command: bool = False) -> Text: """ Generates a string representing the CLI invocation as if typed directly into the command line. Returns: A string representing the command invocation. """ args = self.to_cli_args(include_...
Generates a string representing the CLI invocation as if typed directly into the command line. Returns: A string representing the command invocation.
to_cli_string
python
Textualize/trogon
trogon/run_command.py
https://github.com/Textualize/trogon/blob/master/trogon/run_command.py
MIT
async def selected_command_changed( self, event: Tree.NodeHighlighted[CommandSchema] ) -> None: """When we highlight a node in the CommandTree, the main body of the home page updates to display a form specific to the highlighted command.""" await self._refresh_command_form(event.node...
When we highlight a node in the CommandTree, the main body of the home page updates to display a form specific to the highlighted command.
selected_command_changed
python
Textualize/trogon
trogon/trogon.py
https://github.com/Textualize/trogon/blob/master/trogon/trogon.py
MIT
def _update_command_description(self, command: CommandSchema) -> None: """Update the description of the command at the bottom of the sidebar based on the currently selected node in the command tree.""" description_box = self.query_one("#home-command-description", Static) description_text...
Update the description of the command at the bottom of the sidebar based on the currently selected node in the command tree.
_update_command_description
python
Textualize/trogon
trogon/trogon.py
https://github.com/Textualize/trogon/blob/master/trogon/trogon.py
MIT
def _update_execution_string_preview(self) -> None: """Update the preview box showing the command string to be executed""" command_name_syntax_style = self.get_component_rich_style("command-name-syntax") prefix = Text(f"{self.click_app_name} ", command_name_syntax_style) new_value = self...
Update the preview box showing the command string to be executed
_update_execution_string_preview
python
Textualize/trogon
trogon/trogon.py
https://github.com/Textualize/trogon/blob/master/trogon/trogon.py
MIT
def __init__(self, title: TextType, message: TextType) -> None: """Initialise the dialog. Args: title: The title for the dialog. message: The message to show. """ super().__init__() self._title = title self._message = message
Initialise the dialog. Args: title: The title for the dialog. message: The message to show.
__init__
python
Textualize/trogon
trogon/widgets/about.py
https://github.com/Textualize/trogon/blob/master/trogon/widgets/about.py
MIT
def compose(self) -> ComposeResult: """Compose the content of the modal dialog.""" with Vertical(): with Center(): yield Static(self._title, classes="spaced") yield Static(self._message, id="message", classes="spaced") with Center(classes="spaced"): ...
Compose the content of the modal dialog.
compose
python
Textualize/trogon
trogon/widgets/about.py
https://github.com/Textualize/trogon/blob/master/trogon/widgets/about.py
MIT
def _form_changed(self) -> None: """Take the current state of the form and build a UserCommandData from it, then post a FormChanged message""" command_schema = self.command_schema path_from_root = command_schema.path_from_root # Sentinel root value to make constructing the tree...
Take the current state of the form and build a UserCommandData from it, then post a FormChanged message
_form_changed
python
Textualize/trogon
trogon/widgets/form.py
https://github.com/Textualize/trogon/blob/master/trogon/widgets/form.py
MIT
def apply_filter(self, filter_query: str) -> bool: """Show or hide this ParameterControls depending on whether it matches the filter query or not. Args: filter_query: The string to filter on. Returns: True if the filter matched (and the widget is visible). """ ...
Show or hide this ParameterControls depending on whether it matches the filter query or not. Args: filter_query: The string to filter on. Returns: True if the filter matched (and the widget is visible).
apply_filter
python
Textualize/trogon
trogon/widgets/parameter_controls.py
https://github.com/Textualize/trogon/blob/master/trogon/widgets/parameter_controls.py
MIT
def compose(self) -> ComposeResult: """Takes the schemas for each parameter of the current command, and converts it into a form consisting of Textual widgets.""" schema = self.schema name = schema.name argument_type = schema.type default = schema.default help_text...
Takes the schemas for each parameter of the current command, and converts it into a form consisting of Textual widgets.
compose
python
Textualize/trogon
trogon/widgets/parameter_controls.py
https://github.com/Textualize/trogon/blob/master/trogon/widgets/parameter_controls.py
MIT
def make_widget_group(self) -> Iterable[ControlWidgetType]: """For this option, yield a single set of widgets required to receive user input for it.""" schema = self.schema default = schema.default parameter_type = schema.type name = schema.name multiple = schema.multiple...
For this option, yield a single set of widgets required to receive user input for it.
make_widget_group
python
Textualize/trogon
trogon/widgets/parameter_controls.py
https://github.com/Textualize/trogon/blob/master/trogon/widgets/parameter_controls.py
MIT
def _apply_default_value( control_widget: ControlWidgetType, default_value: Any ) -> None: """Set the default value of a parameter-handling widget.""" if isinstance(control_widget, Input): control_widget.value = str(default_value) control_widget.placeholder = f"{defau...
Set the default value of a parameter-handling widget.
_apply_default_value
python
Textualize/trogon
trogon/widgets/parameter_controls.py
https://github.com/Textualize/trogon/blob/master/trogon/widgets/parameter_controls.py
MIT
def actions(self, state): 'actions are index where we can make a move' actions = [] for index, char in enumerate(state): if char == '_': actions.append(index) return actions
actions are index where we can make a move
actions
python
simpleai-team/simpleai
samples/machine_learning/tic_tac_toe.py
https://github.com/simpleai-team/simpleai/blob/master/samples/machine_learning/tic_tac_toe.py
MIT
def find_location(rows, element_to_find): '''Find the location of a piece in the puzzle. Returns a tuple: row, column''' for ir, row in enumerate(rows): for ic, element in enumerate(row): if element == element_to_find: return ir, ic
Find the location of a piece in the puzzle. Returns a tuple: row, column
find_location
python
simpleai-team/simpleai
samples/search/eight_puzzle.py
https://github.com/simpleai-team/simpleai/blob/master/samples/search/eight_puzzle.py
MIT
def actions(self, state): '''Returns a list of the pieces we can move to the empty space.''' rows = string_to_list(state) row_e, col_e = find_location(rows, 'e') actions = [] if row_e > 0: actions.append(rows[row_e - 1][col_e]) if row_e < 2: actio...
Returns a list of the pieces we can move to the empty space.
actions
python
simpleai-team/simpleai
samples/search/eight_puzzle.py
https://github.com/simpleai-team/simpleai/blob/master/samples/search/eight_puzzle.py
MIT
def result(self, state, action): '''Return the resulting state after moving a piece to the empty space. (the "action" parameter contains the piece to move) ''' rows = string_to_list(state) row_e, col_e = find_location(rows, 'e') row_n, col_n = find_location(rows, actio...
Return the resulting state after moving a piece to the empty space. (the "action" parameter contains the piece to move)
result
python
simpleai-team/simpleai
samples/search/eight_puzzle.py
https://github.com/simpleai-team/simpleai/blob/master/samples/search/eight_puzzle.py
MIT
def heuristic(self, state): '''Returns an *estimation* of the distance from a state to the goal. We are using the manhattan distance. ''' rows = string_to_list(state) distance = 0 for number in '12345678e': row_n, col_n = find_location(rows, number) ...
Returns an *estimation* of the distance from a state to the goal. We are using the manhattan distance.
heuristic
python
simpleai-team/simpleai
samples/search/eight_puzzle.py
https://github.com/simpleai-team/simpleai/blob/master/samples/search/eight_puzzle.py
MIT
def result(self, s, a): '''Result of applying an action to a state.''' # result: boat on opposite side, and numbers of missioners and # cannibals updated according to the move if s[2] == 0: return (s[0] - a[1][0], s[1] - a[1][1], 1) else: return (s[0] + a[...
Result of applying an action to a state.
result
python
simpleai-team/simpleai
samples/search/missioners.py
https://github.com/simpleai-team/simpleai/blob/master/samples/search/missioners.py
MIT
def mkconstraints(): """ Make constraint list for binary constraint problem. """ constraints = [] for j in range(1, 10): vars = ["%s%d" % (i, j) for i in uppercase[:9]] constraints.extend((c, const_different) for c in combinations(vars, 2)) for i in uppercase[:9]: vars ...
Make constraint list for binary constraint problem.
mkconstraints
python
simpleai-team/simpleai
samples/search/sudoku.py
https://github.com/simpleai-team/simpleai/blob/master/samples/search/sudoku.py
MIT
def step(self, viewer=None): "This method evolves one step in time" if not self.is_completed(self.state): for agent in self.agents: action = agent.program(self.percept(agent, self.state)) next_state = self.do_action(self.state, action, agent) i...
This method evolves one step in time
step
python
simpleai-team/simpleai
simpleai/environments.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/environments.py
MIT
def learn(self, examples, attributes, parent_examples): """ A decision tree learner that *strictly* follows the pseudocode given in AIMA. In 3rd edition, see Figure 18.5, page 702. """ if not examples: return self.plurality_value(parent_examples) elif len(set(...
A decision tree learner that *strictly* follows the pseudocode given in AIMA. In 3rd edition, see Figure 18.5, page 702.
learn
python
simpleai-team/simpleai
simpleai/machine_learning/classifiers.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py
MIT
def importance(self, attribute, examples): """ AIMA implies that importance should be information gain. Since AIMA only defines it for binary features this implementation was based on the wikipedia article: http://en.wikipedia.org/wiki/Information_gain_in_decision_trees "...
AIMA implies that importance should be information gain. Since AIMA only defines it for binary features this implementation was based on the wikipedia article: http://en.wikipedia.org/wiki/Information_gain_in_decision_trees
importance
python
simpleai-team/simpleai
simpleai/machine_learning/classifiers.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py
MIT
def save(self, filepath): """ Saves the classifier to `filepath`. Because this classifier needs to save the dataset, it must be something that can be pickled and not something like an iterator. """ if not filepath or not isinstance(filepath, str): rai...
Saves the classifier to `filepath`. Because this classifier needs to save the dataset, it must be something that can be pickled and not something like an iterator.
save
python
simpleai-team/simpleai
simpleai/machine_learning/classifiers.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py
MIT
def tree_to_str(root): """ Returns a string representation of a decision tree with root node `root`. """ xs = [] for value, node, depth in iter_tree(root): template = "{indent}" if node is not root: template += "case={value}\t" if node.attribute is None: ...
Returns a string representation of a decision tree with root node `root`.
tree_to_str
python
simpleai-team/simpleai
simpleai/machine_learning/classifiers.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py
MIT
def take_branch(self, example): """ Returns a `DecisionTreeNode` instance that can better classify `example` based on the selectors value. If there are no more branches (ie, this node is a leaf) or the attribute gives a value for an unexistent branch then this method retu...
Returns a `DecisionTreeNode` instance that can better classify `example` based on the selectors value. If there are no more branches (ie, this node is a leaf) or the attribute gives a value for an unexistent branch then this method returns None.
take_branch
python
simpleai-team/simpleai
simpleai/machine_learning/classifiers.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py
MIT
def _max_gain_split(self, examples): """ Returns an OnlineInformationGain of the attribute with max gain based on `examples`. """ gains = self._new_set_of_gain_counters() for example in examples: for gain in gains: gain.add(example) win...
Returns an OnlineInformationGain of the attribute with max gain based on `examples`.
_max_gain_split
python
simpleai-team/simpleai
simpleai/machine_learning/classifiers.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py
MIT
def _new_set_of_gain_counters(self): """ Creates a new set of OnlineInformationGain objects for each attribute. """ return [OnlineInformationGain(attribute, self.target) for attribute in self.attributes]
Creates a new set of OnlineInformationGain objects for each attribute.
_new_set_of_gain_counters
python
simpleai-team/simpleai
simpleai/machine_learning/classifiers.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py
MIT
def precision(classifier, testset): """ Runs the classifier for each example in `testset` and verifies that the classification is correct using the `target`. Returns a number between 0.0 and 1.0 with the precision of classification for this test set. """ hit = 0 total = 0 for e...
Runs the classifier for each example in `testset` and verifies that the classification is correct using the `target`. Returns a number between 0.0 and 1.0 with the precision of classification for this test set.
precision
python
simpleai-team/simpleai
simpleai/machine_learning/evaluation.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/evaluation.py
MIT
def kfold(dataset, problem, method, k=10): """ Does a k-fold on `dataset` with `method`. This is, it randomly creates k-partitions of the dataset, and k-times trains the method with k-1 parts and runs it with the partition left. After all this, returns the overall success ratio. """ if k <=...
Does a k-fold on `dataset` with `method`. This is, it randomly creates k-partitions of the dataset, and k-times trains the method with k-1 parts and runs it with the partition left. After all this, returns the overall success ratio.
kfold
python
simpleai-team/simpleai
simpleai/machine_learning/evaluation.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/evaluation.py
MIT
def save(self, filepath): """ Pickles the tree and saves it into `filepath` """ if not filepath or not isinstance(filepath, str): raise ValueError("Invalid filepath") # Removes dataset so is not saved in the pickle self.dataset = None with open(filep...
Pickles the tree and saves it into `filepath`
save
python
simpleai-team/simpleai
simpleai/machine_learning/models.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/models.py
MIT
def load(cls, filepath): """ Loads a pickled version of the classifier saved in `filepath` """ with open(filepath, "rb") as filehandler: classifier = pickle.load(filehandler) if not isinstance(classifier, Classifier): raise ValueError("Pickled object is n...
Loads a pickled version of the classifier saved in `filepath`
load
python
simpleai-team/simpleai
simpleai/machine_learning/models.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/models.py
MIT
def __init__(self, dataset, target_index): """ `dataset` should be an iterable, *not* an iterator. `target_index` is the index in the vector where the classification of an example is defined. """ super(VectorDataClassificationProblem, self).__init__() try: ...
`dataset` should be an iterable, *not* an iterator. `target_index` is the index in the vector where the classification of an example is defined.
__init__
python
simpleai-team/simpleai
simpleai/machine_learning/models.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/models.py
MIT