code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
port_id = context.current['id'] physnet = self._get_physnet(context) if not physnet: LOG.debug("bind_port for port %(port)s: no physical_network " "found", {'port': port_id}) return False next_segment = context.allocate_dynamic_segm...
def _bind_fabric(self, context, segment)
Allocate dynamic segments for the port Segment physnets are based on the switch to which the host is connected.
2.539083
2.45622
1.033736
port = context.current log_context("bind_port: port", port) for segment in context.segments_to_bind: physnet = segment.get(driver_api.PHYSICAL_NETWORK) segment_type = segment[driver_api.NETWORK_TYPE] if not physnet: if (segment_type ...
def bind_port(self, context)
Bind port to a network segment. Provisioning request to Arista Hardware to plug a host into appropriate network is done when the port is created this simply tells the ML2 Plugin that we are binding the port
3.295946
3.130853
1.052731
if migration: binding_levels = context.original_binding_levels else: binding_levels = context.binding_levels LOG.debug("_try_release_dynamic_segment: " "binding_levels=%(bl)s", {'bl': binding_levels}) if not binding_levels: r...
def _try_to_release_dynamic_segment(self, context, migration=False)
Release dynamic segment if necessary If this port was the last port using a segment and the segment was allocated by this driver, it should be released
3.337963
3.056946
1.091927
if not isinstance(bdom, int): raise ValueError("'bdom' must be integer") sd = pd.Timestamp(sd) ed = pd.Timestamp(ed) t1 = sd if not t1.is_month_start: t1 = t1 - pd.offsets.MonthBegin(1) t2 = ed if not t2.is_month_end: t2 = t2 + pd.offsets.MonthEnd(1) dates ...
def bdom_roll_date(sd, ed, bdom, months, holidays=[])
Convenience function for getting business day data associated with contracts. Usefully for generating business day derived 'contract_dates' which can be used as input to roller(). Returns dates for a business day of the month for months in months.keys() between the start date and end date. Parameters ...
2.156803
2.193061
0.983467
timestamps = sorted(timestamps) contract_dates = contract_dates.sort_values() _check_contract_dates(contract_dates) weights = [] # for loop speedup only validate inputs the first function call to # get_weights() validate_inputs = True ts = timestamps[0] weights.extend(get_weight...
def roller(timestamps, contract_dates, get_weights, **kwargs)
Calculate weight allocations to tradeable instruments for generic futures at a set of timestamps for a given root generic. Paramters --------- timestamps: iterable Sorted iterable of of pandas.Timestamps to calculate weights for contract_dates: pandas.Series Series with index of tra...
3.619426
4.426391
0.817692
dwts = pd.DataFrame(weights, columns=["generic", "contract", "weight", "date"]) dwts = dwts.pivot_table(index=['date', 'contract'], columns=['generic'], values='weight', fill_value=0) dwts = dwts.astype(float) dwts = dwts.sort_index() if drop_...
def aggregate_weights(weights, drop_date=False)
Transforms list of tuples of weights into pandas.DataFrame of weights. Parameters: ----------- weights: list A list of tuples consisting of the generic instrument name, the tradeable contract as a string, the weight on this contract as a float and the date as a pandas.Timestamp. ...
3.394357
2.931473
1.157902
# Get ACL rules and interface mappings from the switch switch_acls, switch_bindings = self._get_dynamic_acl_info(switch_ip) # Adjust expected bindings for switch LAG config expected_bindings = self.adjust_bindings_for_lag(switch_ip, ...
def synchronize_switch(self, switch_ip, expected_acls, expected_bindings)
Update ACL config on a switch to match expected config This is done as follows: 1. Get switch ACL config using show commands 2. Update expected bindings based on switch LAGs 3. Get commands to synchronize switch ACLs 4. Get commands to synchronize switch ACL bindings 5. ...
4.189408
3.671586
1.141035
# Get expected ACLs and rules expected_acls = self.get_expected_acls() # Get expected interface to ACL mappings all_expected_bindings = self.get_expected_bindings() # Check that config is correct on every registered switch for switch_ip in self._switches.keys(...
def synchronize(self)
Perform sync of the security groups between ML2 and EOS.
4.933884
4.334545
1.13827
cmd = ['show openstack resource-pool vlan region %s uuid' % self.region] try: self._run_eos_cmds(cmd) self.cli_commands['resource-pool'] = cmd except arista_exc.AristaRpcError: self.cli_commands['resource-pool'] = [] LOG.war...
def check_vlan_type_driver_commands(self)
Checks the validity of CLI commands for Arista's VLAN type driver. This method tries to execute the commands used exclusively by the arista_vlan type driver and stores the commands if they succeed.
6.552573
6.197335
1.057321
vlan_uuid_cmd = self.cli_commands['resource-pool'] if vlan_uuid_cmd: return self._run_eos_cmds(commands=vlan_uuid_cmd)[0] return None
def get_vlan_assignment_uuid(self)
Returns the UUID for the region's vlan assignment on CVX :returns: string containing the region's vlan assignment UUID
8.711918
9.444298
0.922453
if not self.cli_commands['resource-pool']: LOG.warning(_('The version of CVX you are using does not support' 'arista VLAN type driver.')) else: cmd = ['show openstack resource-pools region %s' % self.region] command_output = self._ru...
def get_vlan_allocation(self)
Returns the status of the region's VLAN pool in CVX :returns: dictionary containg the assigned, allocated and available VLANs for the region
8.185888
7.032502
1.164008
# Always figure out who is master (starting with the last known val) try: if self._get_eos_master() is None: msg = "Failed to identify CVX master" self.set_cvx_unavailable() raise arista_exc.AristaRpcError(msg=msg) except Exce...
def _run_eos_cmds(self, commands, commands_to_log=None)
Execute/sends a CAPI (Command API) command to EOS. In this method, list of commands is appended with prefix and postfix commands - to make is understandble by EOS. :param commands : List of command to be executed on EOS. :param commands_to_log : This should be set to the command that i...
4.346214
4.499809
0.965866
region_cmd = 'region %s' % self.region if sync: region_cmd = self.cli_commands[const.CMD_REGION_SYNC] full_command = [ 'enable', 'configure', 'cvx', 'service openstack', region_cmd, ] full_command....
def _build_command(self, cmds, sync=False)
Build full EOS's openstack CLI command. Helper method to add commands to enter and exit from openstack CLI modes. :param cmds: The openstack CLI commands that need to be executed in the openstack config mode. :param sync: This flags indicates that the region is bei...
5.954032
5.381942
1.106298
full_command = self._build_command(commands, sync=sync) if commands_to_log: full_log_command = self._build_command(commands_to_log, sync=sync) else: full_log_command = None return self._run_eos_cmds(full_command, full_log_command)
def _run_openstack_cmds(self, commands, commands_to_log=None, sync=False)
Execute/sends a CAPI (Command API) command to EOS. In this method, list of commands is appended with prefix and postfix commands - to make is understandble by EOS. :param commands : List of command to be executed on EOS. :param commands_to_logs : This should be set to the command that ...
2.481604
2.493807
0.995107
port = context.current host_id = context.host cmd = ['show network physical-topology hosts'] try: response = self._run_eos_cmds(cmd) binding_profile = port.get(portbindings.PROFILE, {}) link_info = binding_profile.get('local_link_information',...
def get_baremetal_physnet(self, context)
Returns dictionary which contains mac to hostname mapping
3.20461
3.250242
0.985961
host_id = utils.hostname(context.host) cmd = ['show network physical-topology neighbors'] try: response = self._run_eos_cmds(cmd) # Get response for 'show network physical-topology neighbors' # command neighbors = response[0]['neighbors'] ...
def get_host_physnet(self, context)
Returns dictionary which contains physical topology information for a given host_id
3.702111
3.825765
0.967679
segment_model = segment_models.NetworkSegment network_model = models_v2.Network query = (query .join_if_necessary(network_model) .join_if_necessary(segment_model) .filter(network_model.project_id != '') .filter_network_type()) return query
def filter_unnecessary_segments(query)
Filter segments are not needed on CVX
5.819688
6.345699
0.917107
segment_model = segment_models.NetworkSegment query = (query .filter( segment_model.network_type.in_( utils.SUPPORTED_NETWORK_TYPES))) return query
def filter_network_type(query)
Filter unsupported segment types
5.482402
4.576019
1.198073
# hack for pep8 E711: comparison to None should be # 'if cond is not None' none = None port_model = models_v2.Port binding_level_model = ml2_models.PortBindingLevel query = (query .join_if_necessary(port_model) .join_if_necessary(binding_level_model) ....
def filter_unbound_ports(query)
Filter ports not bound to a host or network
6.139649
5.959535
1.030223
port_model = models_v2.Port if not device_owners: device_owners = utils.SUPPORTED_DEVICE_OWNERS supported_device_owner_filter = [ port_model.device_owner.ilike('%s%%' % owner) for owner in device_owners] unsupported_device_owner_filter = [ port_model.device_owner.not...
def filter_by_device_owner(query, device_owners=None)
Filter ports by device_owner Either filter using specified device_owner or using the list of all device_owners supported and unsupported by the arista ML2 plugin
2.523261
2.306849
1.093813
port_model = models_v2.Port unsupported_device_id_filter = [ port_model.device_id.notilike('%s%%' % id) for id in utils.UNSUPPORTED_DEVICE_IDS] query = (query .filter(and_(*unsupported_device_id_filter))) return query
def filter_by_device_id(query)
Filter ports attached to devices we don't care about Currently used to filter DHCP_RESERVED ports
4.792508
4.179356
1.14671
port_model = models_v2.Port binding_model = ml2_models.PortBinding dst_binding_model = ml2_models.DistributedPortBinding query = (query .outerjoin_if_necessary( binding_model, port_model.id == binding_model.port_id) .outerjoin_if_necessary...
def filter_by_vnic_type(query, vnic_type)
Filter ports by vnic_type (currently only used for baremetals)
2.547617
2.471697
1.030716
config = cfg.CONF.ml2_arista managed_physnets = config['managed_physnets'] # Filter out ports bound to segments on physnets that we're not # managing segment_model = segment_models.NetworkSegment if managed_physnets: query = (query .join_if_necessary(segment_model)...
def filter_unmanaged_physnets(query)
Filter ports managed by other ML2 plugins
5.589601
5.178995
1.079283
port_model = models_v2.Port query = (query .filter(port_model.status == n_const.PORT_STATUS_ACTIVE)) return query
def filter_inactive_ports(query)
Filter ports that aren't in active status
3.6473
3.280703
1.111744
query = (query .filter_unbound_ports() .filter_by_device_owner(device_owners) .filter_by_device_id() .filter_unmanaged_physnets()) if active: query = query.filter_inactive_ports() if vnic_type: query = query.filter_by_vnic_type(vnic_ty...
def filter_unnecessary_ports(query, device_owners=None, vnic_type=None, active=True)
Filter out all ports are not needed on CVX
3.126708
3.082318
1.014401
if tenant_id == '': return [] session = db.get_reader_session() project_ids = set() with session.begin(): for m in [models_v2.Network, models_v2.Port]: q = session.query(m.project_id).filter(m.project_id != '') if tenant_id: q = q.filter(m.pro...
def get_tenants(tenant_id=None)
Returns list of all project/tenant ids that may be relevant on CVX
2.816854
2.832018
0.994646
session = db.get_reader_session() with session.begin(): model = models_v2.Network networks = session.query(model).filter(model.project_id != '') if network_id: networks = networks.filter(model.id == network_id) return networks.all()
def get_networks(network_id=None)
Returns list of all networks that may be relevant on CVX
3.271406
3.519868
0.929411
session = db.get_reader_session() with session.begin(): model = segment_models.NetworkSegment segments = session.query(model).filter_unnecessary_segments() if segment_id: segments = segments.filter(model.id == segment_id) return segments.all()
def get_segments(segment_id=None)
Returns list of all network segments that may be relevant on CVX
4.507053
4.063505
1.109154
session = db.get_reader_session() with session.begin(): port_model = models_v2.Port binding_model = ml2_models.PortBinding instances = (session .query(port_model, binding_model) .outerjoin( ...
def get_instances(device_owners=None, vnic_type=None, instance_id=None)
Returns filtered list of all instances in the neutron db
3.014322
2.823606
1.067543
return get_instances(device_owners=[n_const.DEVICE_OWNER_COMPUTE_PREFIX], vnic_type=portbindings.VNIC_NORMAL, instance_id=instance_id)
def get_vm_instances(instance_id=None)
Returns filtered list of vms that may be relevant on CVX
5.657238
6.075058
0.931224
session = db.get_reader_session() with session.begin(): port_model = models_v2.Port ports = (session .query(port_model) .filter_unnecessary_ports(device_owners, vnic_type, active)) if port_id: ports = ports.filter(port_model.id == port_i...
def get_ports(device_owners=None, vnic_type=None, port_id=None, active=True)
Returns list of all ports in neutron the db
3.490182
3.397707
1.027217
return get_ports(device_owners=[n_const.DEVICE_OWNER_COMPUTE_PREFIX, t_const.TRUNK_SUBPORT_OWNER], vnic_type=portbindings.VNIC_NORMAL, port_id=port_id)
def get_vm_ports(port_id=None)
Returns filtered list of vms that may be relevant on CVX
5.590743
6.018932
0.92886
session = db.get_reader_session() with session.begin(): binding_level_model = ml2_models.PortBindingLevel aliased_blm = aliased(ml2_models.PortBindingLevel) port_binding_model = ml2_models.PortBinding dist_binding_model = ml2_models.DistributedPortBinding bindings = ...
def get_port_bindings(binding_key=None)
Returns filtered list of port bindings that may be relevant on CVX This query is a little complex as we need all binding levels for any binding that has a single managed physnet, but we need to filter bindings that have no managed physnets. In order to achieve this, we join to the binding_level_model o...
1.767564
1.704137
1.03722
session = db.get_reader_session() with session.begin(): res = any( session.query(m).filter(m.tenant_id == tenant_id).count() for m in [models_v2.Network, models_v2.Port] ) return res
def tenant_provisioned(tenant_id)
Returns true if any networks or ports exist for a tenant.
3.988607
3.595361
1.109376
session = db.get_reader_session() with session.begin(): port_model = models_v2.Port res = bool(session.query(port_model) .filter(port_model.device_id == device_id).count()) return res
def instance_provisioned(device_id)
Returns true if any ports exist for an instance.
4.621578
3.794148
1.21808
session = db.get_reader_session() with session.begin(): port_model = models_v2.Port res = bool(session.query(port_model) .filter(port_model.id == port_id).count()) return res
def port_provisioned(port_id)
Returns true if port still exists.
4.073602
3.859954
1.05535
session = db.get_reader_session() res = dict() with session.begin(): subport_model = trunk_models.SubPort trunk_model = trunk_models.Trunk subport = (session.query(subport_model). filter(subport_model.port_id == port_id).first()) if subport: ...
def get_parent(port_id)
Get trunk subport's parent port
2.607025
2.321161
1.123156
session = db.get_reader_session() with session.begin(): return (session.query(ml2_models.PortBindingLevel). filter_by(**filters). order_by(ml2_models.PortBindingLevel.level). all())
def get_port_binding_level(filters)
Returns entries from PortBindingLevel based on the specified filters.
3.063998
2.962103
1.034399
import numpy as np data = np.asarray(data) if data.ndim == 1: channels = 1 else: channels = data.shape[1] with SoundFile(file, 'w', samplerate, channels, subtype, endian, format, closefd) as f: f.write(data)
def write(file, data, samplerate, subtype=None, endian=None, format=None, closefd=True)
Write data to a sound file. .. note:: If `file` exists, it will be truncated and overwritten! Parameters ---------- file : str or int or file-like object The file to write to. See :class:`SoundFile` for details. data : array_like The data to write. Usually two-dimensional (frames...
2.222116
3.510969
0.632907
with SoundFile(file, 'r', samplerate, channels, subtype, endian, format, closefd) as f: frames = f._prepare_read(start, stop, frames) for block in f.blocks(blocksize, overlap, frames, dtype, always_2d, fill_value, out): yield block
def blocks(file, blocksize=None, overlap=0, frames=-1, start=0, stop=None, dtype='float64', always_2d=False, fill_value=None, out=None, samplerate=None, channels=None, format=None, subtype=None, endian=None, closefd=True)
Return a generator for block-wise reading. By default, iteration starts at the beginning and stops at the end of the file. Use `start` to start at a later position and `frames` or `stop` to stop earlier. If you stop iterating over the generator before it's exhausted, the sound file is not closed....
2.878097
4.230581
0.680308
subtypes = _available_formats_helper(_snd.SFC_GET_FORMAT_SUBTYPE_COUNT, _snd.SFC_GET_FORMAT_SUBTYPE) return dict((subtype, name) for subtype, name in subtypes if format is None or check_format(format, subtype))
def available_subtypes(format=None)
Return a dictionary of available subtypes. Parameters ---------- format : str If given, only compatible subtypes are returned. Examples -------- >>> import soundfile as sf >>> sf.available_subtypes('FLAC') {'PCM_24': 'Signed 24 bit PCM', 'PCM_16': 'Signed 16 bit PCM', ...
6.093387
7.773878
0.783829
try: return bool(_format_int(format, subtype, endian)) except (ValueError, TypeError): return False
def check_format(format, subtype=None, endian=None)
Check if the combination of format/subtype/endian is valid. Examples -------- >>> import soundfile as sf >>> sf.check_format('WAV', 'PCM_24') True >>> sf.check_format('FLAC', 'VORBIS') False
5.44627
10.628329
0.51243
if err != 0: err_str = _snd.sf_error_number(err) raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace'))
def _error_check(err, prefix="")
Pretty-print a numerical error code if there is an error.
5.994586
5.125235
1.169622
result = _check_format(format) if subtype is None: subtype = default_subtype(format) if subtype is None: raise TypeError( "No default subtype for major format {0!r}".format(format)) elif not isinstance(subtype, (_unicode, str)): raise TypeError("Inval...
def _format_int(format, subtype, endian)
Return numeric ID for given format|subtype|endian combo.
3.009696
2.906263
1.03559
if not isinstance(mode, (_unicode, str)): raise TypeError("Invalid mode: {0!r}".format(mode)) mode_set = set(mode) if mode_set.difference('xrwb+') or len(mode) > len(mode_set): raise ValueError("Invalid mode: {0!r}".format(mode)) if len(mode_set.intersection('xrw')) != 1: ra...
def _check_mode(mode)
Check if mode is valid and return its integer representation.
3.158126
3.042743
1.037921
original_format = format if format is None: format = _get_format_from_filename(file, mode) assert isinstance(format, (_unicode, str)) else: _check_format(format) info = _ffi.new("SF_INFO*") if 'r' not in mode or format.upper() == 'RAW': if samplerate is None: ...
def _create_info_struct(file, mode, samplerate, channels, format, subtype, endian)
Check arguments and create SF_INFO struct.
3.787601
3.547195
1.067773
format = '' file = getattr(file, 'name', file) try: # This raises an exception if file is not a (Unicode/byte) string: format = _os.path.splitext(file)[-1][1:] # Convert bytes to unicode (raises AttributeError on Python 3 str): format = format.decode('utf-8', 'replace') ...
def _get_format_from_filename(file, mode)
Return a format string obtained from file (or file.name). If file already exists (= read mode), an empty string is returned on error. If not, an exception is raised. The return type will always be str or unicode (even if file/file.name is a bytes object).
4.971966
4.690541
1.059998
for dictionary in _formats, _subtypes, _endians: for k, v in dictionary.items(): if v == format_int: return k else: return 'n/a'
def _format_str(format_int)
Return the string representation of a given numeric format.
7.005756
5.75017
1.218356
format_info = _ffi.new("SF_FORMAT_INFO*") format_info.format = format_int _snd.sf_command(_ffi.NULL, format_flag, format_info, _ffi.sizeof("SF_FORMAT_INFO")) name = format_info.name return (_format_str(format_info.format), _ffi.string(name).decode('utf-8', 'repla...
def _format_info(format_int, format_flag=_snd.SFC_GET_FORMAT_INFO)
Return the ID and short description of a given format.
3.400329
3.1791
1.069588
count = _ffi.new("int*") _snd.sf_command(_ffi.NULL, count_flag, count, _ffi.sizeof("int")) for format_int in range(count[0]): yield _format_info(format_int, format_flag)
def _available_formats_helper(count_flag, format_flag)
Helper for available_formats() and available_subtypes().
6.472291
6.000689
1.078591
if not isinstance(format_str, (_unicode, str)): raise TypeError("Invalid format: {0!r}".format(format_str)) try: format_int = _formats[format_str.upper()] except KeyError: raise ValueError("Unknown format: {0!r}".format(format_str)) return format_int
def _check_format(format_str)
Check if `format_str` is valid and return format ID.
2.741553
2.356261
1.163518
readonly = mode_int == _snd.SFM_READ writeonly = mode_int == _snd.SFM_WRITE return all([ hasattr(file, 'seek'), hasattr(file, 'tell'), hasattr(file, 'write') or readonly, hasattr(file, 'read') or hasattr(file, 'readinto') or writeonly, ])
def _has_virtual_io_attrs(file, mode_int)
Check if file has all the necessary attributes for virtual IO.
4.050405
3.929197
1.030848
info = _ffi.new("char[]", 2**14) _snd.sf_command(self._file, _snd.SFC_GET_LOG_INFO, info, _ffi.sizeof(info)) return _ffi.string(info).decode('utf-8', 'replace')
def extra_info(self)
Retrieve the log string generated when opening the file.
6.459422
4.690736
1.377059
self._check_if_closed() position = _snd.sf_seek(self._file, frames, whence) _error_check(self._errorcode) return position
def seek(self, frames, whence=SEEK_SET)
Set the read/write position. Parameters ---------- frames : int The frame index or offset to seek. whence : {SEEK_SET, SEEK_CUR, SEEK_END}, optional By default (``whence=SEEK_SET``), `frames` are counted from the beginning of the file. ``w...
7.768131
24.303785
0.319626
if out is None: frames = self._check_frames(frames, fill_value) out = self._create_empty_array(frames, always_2d, dtype) else: if frames < 0 or frames > len(out): frames = len(out) frames = self._array_io('read', out, frames) i...
def read(self, frames=-1, dtype='float64', always_2d=False, fill_value=None, out=None)
Read from the file and return data as NumPy array. Reads the given number of frames in the given data format starting at the current read/write position. This advances the read/write position by the same number of frames. By default, all frames from the current read/write position to ...
2.954822
3.702841
0.797988
frames = self._check_frames(frames, fill_value=None) ctype = self._check_dtype(dtype) cdata = _ffi.new(ctype + '[]', frames * self.channels) read_frames = self._cdata_io('read', cdata, ctype, frames) assert read_frames == frames return _ffi.buffer(cdata)
def buffer_read(self, frames=-1, dtype=None)
Read from the file and return data as buffer object. Reads the given number of `frames` in the given data format starting at the current read/write position. This advances the read/write position by the same number of frames. By default, all frames from the current read/write position ...
4.585772
5.643711
0.812545
ctype = self._check_dtype(dtype) cdata, frames = self._check_buffer(buffer, ctype) frames = self._cdata_io('read', cdata, ctype, frames) return frames
def buffer_read_into(self, buffer, dtype)
Read from the file into a given buffer object. Fills the given `buffer` with frames in the given data format starting at the current read/write position (which can be changed with :meth:`.seek`) until the buffer is full or the end of the file is reached. This advances the read/write po...
7.347104
9.622027
0.763571
import numpy as np # no copy is made if data has already the correct memory layout: data = np.ascontiguousarray(data) written = self._array_io('write', data, len(data)) assert written == len(data) self._update_frames(written)
def write(self, data)
Write audio data from a NumPy array to the file. Writes a number of frames at the read/write position to the file. This also advances the read/write position by the same number of frames and enlarges the file if necessary. Note that writing int values to a float file will *not* scale ...
8.116978
10.419735
0.779
ctype = self._check_dtype(dtype) cdata, frames = self._check_buffer(data, ctype) written = self._cdata_io('write', cdata, ctype, frames) assert written == frames self._update_frames(written)
def buffer_write(self, data, dtype)
Write audio data from a buffer/bytes object to the file. Writes the contents of `data` to the file at the current read/write position. This also advances the read/write position by the number of frames that were written and enlarges the file if necessary. Parameters ---...
6.850924
8.238564
0.831568
import numpy as np if 'r' not in self.mode and '+' not in self.mode: raise RuntimeError("blocks() is not allowed in write-only mode") if out is None: if blocksize is None: raise TypeError("One of {blocksize, out} must be specified") ...
def blocks(self, blocksize=None, overlap=0, frames=-1, dtype='float64', always_2d=False, fill_value=None, out=None)
Return a generator for block-wise reading. By default, the generator yields blocks of the given `blocksize` (using a given `overlap`) until the end of the file is reached; `frames` can be used to stop earlier. Parameters ---------- blocksize : int The number...
3.131395
3.20712
0.976388
if frames is None: frames = self.tell() err = _snd.sf_command(self._file, _snd.SFC_FILE_TRUNCATE, _ffi.new("sf_count_t*", frames), _ffi.sizeof("sf_count_t")) if err: raise RuntimeError("Error truncating ...
def truncate(self, frames=None)
Truncate the file to a given number of frames. After this command, the read/write position will be at the new end of the file. Parameters ---------- frames : int, optional Only the data before `frames` is kept, the rest is deleted. If not specified, the ...
5.807604
6.472603
0.897259
if not self.closed: # be sure to flush data to disk before closing the file self.flush() err = _snd.sf_close(self._file) self._file = None _error_check(err)
def close(self)
Close the file. Can be called multiple times.
7.484194
6.338232
1.180802
if isinstance(file, (_unicode, bytes)): if _os.path.isfile(file): if 'x' in self.mode: raise OSError("File exists: {0!r}".format(self.name)) elif set(self.mode).issuperset('w+'): # truncate the file, because SFM_RDWR do...
def _open(self, file, mode_int, closefd)
Call the appropriate sf_open*() function from libsndfile.
4.110092
3.931567
1.045408
@_ffi.callback("sf_vio_get_filelen") def vio_get_filelen(user_data): curr = file.tell() file.seek(0, SEEK_END) size = file.tell() file.seek(curr, SEEK_SET) return size @_ffi.callback("sf_vio_seek") def vio_seek(offset,...
def _init_virtual_io(self, file)
Initialize callback functions for sf_open_virtual().
2.237654
2.139113
1.046066
if self.seekable(): remaining_frames = self.frames - self.tell() if frames < 0 or (frames > remaining_frames and fill_value is None): frames = remaining_frames elif frames < 0: raise ValueError("frames must be spe...
def _check_frames(self, frames, fill_value)
Reduce frames to no more than are available in the file.
4.095436
3.653066
1.121096
assert ctype in _ffi_types.values() if not isinstance(data, bytes): data = _ffi.from_buffer(data) frames, remainder = divmod(len(data), self.channels * _ffi.sizeof(ctype)) if remainder: raise ValueError("Data size must b...
def _check_buffer(self, data, ctype)
Convert buffer to cdata and check for valid size.
4.813916
4.39845
1.094457
import numpy as np if always_2d or self.channels > 1: shape = frames, self.channels else: shape = frames, return np.empty(shape, dtype, order='C')
def _create_empty_array(self, frames, always_2d, dtype)
Create an empty array with appropriate shape.
3.554287
3.36294
1.056899
try: return _ffi_types[dtype] except KeyError: raise ValueError("dtype must be one of {0!r} and not {1!r}".format( sorted(_ffi_types.keys()), dtype))
def _check_dtype(self, dtype)
Check if dtype string is valid and return ctype string.
4.196804
3.199615
1.311659
if (array.ndim not in (1, 2) or array.ndim == 1 and self.channels != 1 or array.ndim == 2 and array.shape[1] != self.channels): raise ValueError("Invalid shape: {0!r}".format(array.shape)) if not array.flags.c_contiguous: raise ValueError(...
def _array_io(self, action, array, frames)
Check array and call low-level IO function.
3.165316
3.040682
1.040989
assert ctype in _ffi_types.values() self._check_if_closed() if self.seekable(): curr = self.tell() func = getattr(_snd, 'sf_' + action + 'f_' + ctype) frames = func(self._file, data, frames) _error_check(self._errorcode) if self.seekable(): ...
def _cdata_io(self, action, data, ctype, frames)
Call one of libsndfile's read/write functions.
6.315725
5.506156
1.14703
if self.seekable(): curr = self.tell() self._info.frames = self.seek(0, SEEK_END) self.seek(curr, SEEK_SET) else: self._info.frames += written
def _update_frames(self, written)
Update self.frames after writing.
4.3608
3.931398
1.109224
if start != 0 and not self.seekable(): raise ValueError("start is only allowed for seekable files") if frames >= 0 and stop is not None: raise TypeError("Only one of {frames, stop} may be used") start, stop, _ = slice(start, stop).indices(self.frames) if...
def _prepare_read(self, start, stop, frames)
Seek to start frame and calculate length.
3.829556
3.632505
1.054246
try: # Tries to create the directory os.makedirs(dirname) except OSError: # Check that the directory exists if os.path.isdir(dirname): pass else: raise
def ensure_dir(dirname)
Creates the directory dirname if it does not already exist, taking into account concurrent 'creation' on the grid. An exception is thrown if a file (rather than a directory) already exists.
3.956095
4.052777
0.976144
import numpy as np C_probesUsed = np.ndarray((len(probe_files_full),), 'bool') C_probesUsed.fill(False) c=0 for k in sorted(probe_files_full.keys()): if probe_files_model.has_key(k): C_probesUsed[c] = True c+=1 return C_probesUsed
def probes_used_generate_vector(probe_files_full, probe_files_model)
Generates boolean matrices indicating which are the probes for each model
3.152229
3.053153
1.03245
if full_scores.shape[1] != same_probes.shape[0]: raise "Size mismatch" import numpy as np model_scores = np.ndarray((full_scores.shape[0],np.sum(same_probes)), 'float64') c=0 for i in range(0,full_scores.shape[1]): if same_probes[i]: for j in range(0,full_scores.shape[0]): model_scores[j,...
def probes_used_extract_scores(full_scores, same_probes)
Extracts a matrix of scores for a model, given a probes_used row vector of boolean
2.384299
2.116869
1.126333
# Depricated: use load() function from bob.bio.spear.database.AudioBioFile #TODO: update xbob.sox first. This will enable the use of formats like NIST sphere and other #import xbob.sox #audio = xbob.sox.reader(filename) #(rate, data) = audio.load() # We consider there is only 1 channel in the audio file ...
def read(filename)
Read audio file
8.602514
8.394979
1.024721
# Initializes variables length = 1 n_samples = len(vector) mean = numpy.ndarray((length,), 'float64') std = numpy.ndarray((length,), 'float64') mean.fill(0) std.fill(0) # Computes mean and variance for array in vector: x = array.astype('float64') mean += x std += (x ** 2) mean /= n...
def normalize_std_array(vector)
Applies a unit mean and variance normalization to an arrayset
2.941994
2.799014
1.051082
if numpy.sum(labels)< smoothing_window: return labels segments = [] for k in range(1,len(labels)-1): if labels[k]==0 and labels[k-1]==1 and labels[k+1]==1 : labels[k]=1 for k in range(1,len(labels)-1): if labels[k]==1 and labels[k-1]==0 and labels[k+1]==0 : labels[k]=0 seg = numpy...
def smoothing(labels, smoothing_window)
Applies a smoothing on VAD
1.600114
1.602272
0.998653
e = bob.ap.Energy(rate_wavsample[0], self.win_length_ms, self.win_shift_ms) energy_array = e(rate_wavsample[1]) labels = self.use_existing_vad(energy_array, vad_file) return labels
def _conversion(self, input_signal, vad_file)
Converts an external VAD to follow the Spear convention. Energy is used in order to avoind out-of-bound array indexes.
12.093795
10.735527
1.126521
# Set parameters wl = self.win_length_ms ws = self.win_shift_ms nf = self.n_filters f_min = self.f_min f_max = self.f_max pre = self.pre_emphasis_coef c = bob.ap.Spectrogram(rate_wavsample[0], wl, ws, nf, f_min, f_max, pre) c.energy_filter=True c.log_filter=False c.ene...
def mod_4hz(self, rate_wavsample)
Computes and returns the 4Hz modulation energy features for the given input wave file
5.152548
5.078991
1.014483
import bob.io.matlab # return the numpy array read from the data_file data_path = biofile.make_path(directory, extension) return bob.io.base.load(data_path)
def read_matlab_files(self, biofile, directory, extension)
Read pre-computed CQCC Matlab features here
7.255395
7.241084
1.001976
f = bob.io.base.HDF5File(data_file, 'w') f.set("rate", data[0], compression=compression) f.set("data", data[1], compression=compression) f.set("labels", data[2], compression=compression)
def write_data(self, data, data_file, compression=0)
Writes the given *preprocessed* data to a file with the given name.
3.293894
3.1135
1.057939
# create parser parser = argparse.ArgumentParser(description='Execute baseline algorithms with default parameters', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # add parameters # - the algorithm to execute parser.add_argument('-a', '--algorithms', choices = all_algorithms, default = ('gmm-vox...
def command_line_arguments(command_line_parameters)
Defines the command line parameters that are accepted.
4.684913
4.676081
1.001889
e = bob.ap.Energy(rate_wavsample[0], self.win_length_ms, self.win_shift_ms) energy_array = e(rate_wavsample[1]) labels = self._voice_activity_detection(energy_array) # discard isolated speech a number of frames defined in smoothing_window labels = utils.smoothing(labels,self.smoothing_window) ...
def _compute_energy(self, rate_wavsample)
retreive the speech / non speech labels for the speech sample given by the tuple (rate, wave signal)
10.598662
9.466896
1.11955
if c1 != []: return (numpy.mean(c0, 0) + numpy.mean(c1, 0)) / 2. else: return numpy.mean(c0, 0)
def calc_mean(c0, c1=[])
Calculates the mean of the data.
2.254611
2.104144
1.07151
if c1 == []: return numpy.std(c0, 0) prop = float(len(c0)) / float(len(c1)) if prop < 1: p0 = int(math.ceil(1 / prop)) p1 = 1 else: p0 = 1 p1 = int(math.ceil(prop)) return numpy.std(numpy.vstack(p0 * [c0] + p1 * [c1]), 0)
def calc_std(c0, c1=[])
Calculates the variance of the data.
2.61402
2.557526
1.022089
mi = calc_mean(c0, c1) std = calc_std(c0, c1) if (nonStdZero): std[std == 0] = 1 return mi, std
def calc_mean_std(c0, c1=[], nonStdZero=False)
Calculates both the mean of the data.
2.624633
2.774793
0.945884
if not features.size: raise ValueError("vad_filter_features(): data sample is empty, no features extraction is possible") vad_labels = numpy.asarray(vad_labels, dtype=numpy.int8) features = numpy.asarray(features, dtype=numpy.float64) features = numpy.reshape(features, (vad_labels.shape[0...
def vad_filter_features(vad_labels, features, filter_frames="trim_silence")
Trim the spectrogram to remove silent head/tails from the speech sample. Keep all remaining frames or either speech or non-speech only @param: filter_frames: the value is either 'silence_only' (keep the speech, remove everything else), 'speech_only' (only keep the silent parts), 'trim_silence' (trim silent ...
4.081829
3.948601
1.033741
n_effs = [] mode_types = [] fractions_te = [] fractions_tm = [] for s in tqdm.tqdm(structures, ncols=70): self.solve(s) n_effs.append(np.real(self.n_effs)) mode_types.append(self._get_mode_types()) fractions_te.append(self....
def solve_sweep_structure( self, structures, sweep_param_list, filename="structure_n_effs.dat", plot=True, x_label="Structure number", fraction_mode_list=[], )
Find the modes of many structures. Args: structures (list): A list of `Structures` to find the modes of. sweep_param_list (list): A list of the parameter-sweep sweep that was used. This is for plotting purposes only. filename (str): The nomin...
1.958156
1.907124
1.026759
n_effs = [] for w in tqdm.tqdm(wavelengths, ncols=70): structure.change_wavelength(w) self.solve(structure) n_effs.append(np.real(self.n_effs)) if filename: self._write_n_effs_to_file( n_effs, self._modes_directory + filen...
def solve_sweep_wavelength( self, structure, wavelengths, filename="wavelength_n_effs.dat", plot=True, )
Solve for the effective indices of a fixed structure at different wavelengths. Args: structure (Slabs): The target structure to solve for modes. wavelengths (list): A list of wavelengths to sweep over. filename (str): The nominal filen...
3.36066
3.473199
0.967598
r wl_nom = structure._wl self.solve(structure) n_ctrs = self.n_effs structure.change_wavelength(wl_nom - wavelength_step) self.solve(structure) n_bcks = self.n_effs structure.change_wavelength(wl_nom + wavelength_step) self.solve(structure) ...
def solve_ng(self, structure, wavelength_step=0.01, filename="ng.dat")
r""" Solve for the group index, :math:`n_g`, of a structure at a particular wavelength. Args: structure (Structure): The target structure to solve for modes. wavelength_step (float): The step to take below and above the nominal wavelength....
3.526048
3.122133
1.129372
modes_directory = "./modes_semi_vec/" if not os.path.isdir(modes_directory): os.mkdir(modes_directory) filename = modes_directory + filename for i, mode in enumerate(self._ms.modes): filename_mode = self._get_mode_filename( self._semi_vec...
def write_modes_to_file(self, filename="mode.dat", plot=True, analyse=True)
Writes the mode fields to a file and optionally plots them. Args: filename (str): The nominal filename to use for the saved data. The suffix will be automatically be changed to identifiy each mode number. Default is 'mode.dat' plot (bool): `True` if plo...
3.211817
3.20604
1.001802
modes_directory = self._modes_directory # Mode info file. with open(modes_directory + "mode_info", "w") as fs: fs.write("# Mode idx, Mode type, % in major direction, n_eff\n") for i, (n_eff, (mode_type, percentage)) in enumerate( zip(self.n_effs,...
def write_modes_to_file( self, filename="mode.dat", plot=True, fields_to_write=("Ex", "Ey", "Ez", "Hx", "Hy", "Hz"), )
Writes the mode fields to a file and optionally plots them. Args: filename (str): The nominal filename to use for the saved data. The suffix will be automatically be changed to identifiy each field and mode number. Default is 'mode.dat' ...
3.391217
3.441931
0.985266
if render_kw is None: render_kw = {} if 'required' in render_kw and not force: return render_kw if field.flags.required: render_kw['required'] = True return render_kw
def set_required(field, render_kw=None, force=False)
Returns *render_kw* with *required* set if the field is required. Sets the *required* key if the `required` flag is set for the field (this is mostly the case if it is set by validators). The `required` attribute is used by browsers to indicate a required field. ..note:: This won't change key...
2.006963
2.408945
0.833129
if render_kw is None: render_kw = {} if field.errors: classes = render_kw.get('class') or render_kw.pop('class_', '') if classes: render_kw['class'] = 'invalid {}'.format(classes) else: render_kw['class'] = 'invalid' return render_kw
def set_invalid(field, render_kw=None)
Returns *render_kw* with `invalid` added to *class* on validation errors. Set (or appends) 'invalid' to the fields CSS class(es), if the *field* got any errors. 'invalid' is also set by browsers if they detect errors on a field.
2.314269
2.402562
0.963251
if render_kw is None: render_kw = {} for validator in field.validators: if isinstance(validator, MINMAX_VALIDATORS): if 'min' not in render_kw or force: v_min = getattr(validator, 'min', -1) if v_min not in (-1, None): render_k...
def set_minmax(field, render_kw=None, force=False)
Returns *render_kw* with *min* and *max* set if validators use them. Sets *min* and / or *max* keys if a `Length` or `NumberRange` validator is using them. ..note:: This won't change keys already present unless *force* is used.
1.869794
1.928797
0.96941
if render_kw is None: render_kw = {} if 'title' not in render_kw and getattr(field, 'description'): render_kw['title'] = '{}'.format(field.description) return render_kw
def set_title(field, render_kw=None)
Returns *render_kw* with *min* and *max* set if required. If the field got a *description* but no *title* key is set, the *title* is set to *description*.
2.475147
2.56316
0.965662
if isinstance(field, UnboundField): msg = 'This function needs a bound field not: {}' raise ValueError(msg.format(field)) kwargs = render_kw.copy() if render_kw else {} kwargs = set_required(field, kwargs, force) # is field required? kwargs = set_invalid(field, kwargs) # is field ...
def get_html5_kwargs(field, render_kw=None, force=False)
Returns a copy of *render_kw* with keys added for a bound *field*. If some *render_kw* are given, the new keys are added to a copy of them, which is then returned. If none are given, a dictionary containing only the automatically generated keys is returned. .. important:: This might add new ...
4.894458
4.286582
1.141809
field_kw = getattr(field, 'render_kw', None) if field_kw is not None: render_kw = dict(field_kw, **render_kw) render_kw = get_html5_kwargs(field, render_kw) return field.widget(field, **render_kw)
def render_field(self, field, render_kw)
Returns the rendered field after adding auto–attributes. Calls the field`s widget with the following kwargs: 1. the *render_kw* set on the field are used as based 2. and are updated with the *render_kw* arguments from the render call 3. this is used as an argument for a call to `get_ht...
2.740145
2.120149
1.292431
''' np.array: The grid points in x. ''' if None not in (self.x_min, self.x_max, self.x_step) and \ self.x_min != self.x_max: x = np.arange(self.x_min, self.x_max+self.x_step-self.y_step*0.1, self.x_step) else: x = np.array([]) retur...
def x(self)
np.array: The grid points in x.
3.21769
2.565017
1.254452