signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def reset(self):
elm_name = '<STR_LIT>' % self.get_attribute('<STR_LIT:id>')<EOL>self.click(elm_name)<EOL>
Try to find element with ID "[FORM_ID]_reset" and click on it. You should use it for forms where you have cleaning/reseting of data.
f10504:c0:m3
@classmethod<EOL><INDENT>def _click_on_elm_or_his_ancestor(cls, elm):<DEDENT>
try:<EOL><INDENT>elm.click()<EOL><DEDENT>except WebDriverException:<EOL><INDENT>elm.click(xpath='<STR_LIT>')<EOL><DEDENT>
For example Bootstrap wraps chboxes or radio button into label and hide that element, so Selenium can't click on it.
f10504:c1:m13
def expected_info_messages(*info_messages):
def wrapper(func):<EOL><INDENT>setattr(func, EXPECTED_INFO_MESSAGES, info_messages)<EOL>return func<EOL><DEDENT>return wrapper<EOL>
Decorator expecting defined info messages at the end of test method. As param use what :py:meth:`~.WebdriverWrapperInfoMixin.get_info_messages` returns. .. versionadded:: 2.0 Before this decorator was called ``ShouldBeInfo``.
f10505:m0
def allowed_info_messages(*info_messages):
def wrapper(func):<EOL><INDENT>setattr(func, ALLOWED_INFO_MESSAGES, info_messages)<EOL>return func<EOL><DEDENT>return wrapper<EOL>
Decorator ignoring defined info messages at the end of test method. As param use what :py:meth:`~.WebdriverWrapperInfoMixin.get_info_messages` returns. .. versionadded:: 2.0
f10505:m1
def check_infos(self, expected_info_messages=[], allowed_info_messages=[]):
<EOL>self.close_alert(ignore_exception=True)<EOL>expected_info_messages = set(expected_info_messages)<EOL>allowed_info_messages = set(allowed_info_messages)<EOL>info_messages = set(self.get_info_messages())<EOL>if (<EOL>info_messages & expected_info_messages != expected_info_messages<EOL>or<EOL>(expected_info_messages and info_messages - (expected_info_messages | allowed_info_messages))<EOL>):<EOL><INDENT>raise InfoMessagesException(self.current_url, info_messages, expected_info_messages, allowed_info_messages)<EOL><DEDENT>
This method should be called whenever you need to check if there is some info. Normally you need only ``check_expected_infos`` called after each test (which you specify only once), but it will check infos only at the end of test. When you have big use case and you need to check messages on every step, use this. To parameters you should pass same values like to decorators :py:func:`.expected_info_messages` and :py:func:`.allowed_info_messages`.
f10505:c0:m1
def get_info_messages(self):
try:<EOL><INDENT>info_elms = self.get_elms(class_name='<STR_LIT:info>')<EOL><DEDENT>except NoSuchElementException:<EOL><INDENT>return []<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>info_values = [info_elm.get_attribute('<STR_LIT:info>') for info_elm in info_elms]<EOL><DEDENT>except Exception: <EOL><INDENT>info_values = [info_elm.text for info_elm in info_elms]<EOL><DEDENT>finally:<EOL><INDENT>return info_values<EOL><DEDENT><DEDENT>
Method returning info messages. Should return list of messages. By default it find element with class ``info`` and theirs value in attribute ``info`` or text if that attribute is missing. You can change this method accordingly to your app. Info messages returned from this method are used in decorators :py:func:`.expected_info_messages` and :py:func:`.allowed_info_messages`.
f10505:c0:m2
def make_screenshot(self, screenshot_name=None):
if not screenshot_name:<EOL><INDENT>if not self.screenshot_path:<EOL><INDENT>return<EOL><DEDENT>screenshot_name = self.id()<EOL><DEDENT>self.driver.close_alert(ignore_exception=True)<EOL>self.driver.get_screenshot_as_file('<STR_LIT>' % (self.screenshot_path, screenshot_name))<EOL>
Save screenshot to :py:attr:`.screenshot_path` with given name ``screenshot_name``. If name is not given, then the name is name of current test (``self.id()``). .. versionchanged:: 2.2 Use ``make_screenshot`` directly on ``driver`` instead. This method is used for making screenshot of failed tests and therefor does nothing if ``screenshot_path`` is not configured. It stays there only for compatibility.
f10508:c0:m3
def _get_driver(self):
return Firefox()<EOL>
Create driver. By default it creates Firefox. Change it to your needs.
f10508:c0:m5
@staticmethod<EOL><INDENT>def quit_driver():<DEDENT>
if hasattr(WebdriverTestCase, '<STR_LIT>'):<EOL><INDENT>WebdriverTestCase.driver.quit()<EOL>del WebdriverTestCase.driver<EOL><DEDENT>
When you set :py:attr:`.instances_of_driver` to :py:attr:`.ONE_INSTANCE_FOR_ALL_TESTS` (which is default), then you have to quit driver by yourself by this method.
f10508:c0:m7
def break_point(self):
self.driver.break_point()<EOL>
Alias for :py:meth:`~webdriverwrapper.wrapper._WebdriverWrapper.break_point`.
f10508:c0:m9
def check_errors(self, expected_error_page=None, allowed_error_pages=[], expected_error_messages=[], allowed_error_messages=[]):
self.driver.check_errors(expected_error_page, allowed_error_pages, expected_error_messages, allowed_error_messages)<EOL>
Alias for :py:meth:`~webdriverwrapper.errors.WebdriverWrapperErrorMixin.check_errors`. .. versionchanged:: 2.0 Only alias. Code moved to wrapper so it could be used also by pytest.
f10508:c0:m10
def find_element_by_text(self, text):
return self.driver.find_element_by_text(text)<EOL>
Alias for :py:meth:`~webdriverwrapper.wrapper._WebdriverBaseWrapper.find_element_by_text`. .. versionadded:: 2.0
f10508:c0:m11
def find_elements_by_text(self, text):
return self.driver.find_elements_by_text(text)<EOL>
Alias for :py:meth:`~webdriverwrapper.wrapper._WebdriverBaseWrapper.find_elements_by_text`.
f10508:c0:m12
def contains_text(self, text):
return self.driver.contains_text(text)<EOL>
Alias for :py:meth:`~webdriverwrapper.wrapper._WebdriverBaseWrapper.contains_text`.
f10508:c0:m13
def get_elm(self, *args, **kwds):
return self.driver.get_elm(*args, **kwds)<EOL>
Alias for :py:meth:`~webdriverwrapper.wrapper._WebdriverBaseWrapper.get_elm`.
f10508:c0:m14
def get_elms(self, *args, **kwds):
return self.driver.get_elms(*args, **kwds)<EOL>
Alias for :py:meth:`~webdriverwrapper.wrapper._WebdriverBaseWrapper.get_elms`.
f10508:c0:m15
def click(self, *args, **kwds):
self.driver.click(*args, **kwds)<EOL>
Alias for :py:meth:`~webdriverwrapper.wrapper._WebdriverBaseWrapper.click`.
f10508:c0:m16
def wait_for_element(self, *args, **kwds):
return self.driver.wait_for_element(*args, **kwds)<EOL>
Alias for :py:meth:`~webdriverwrapper.wrapper._WebdriverWrapper.wait_for_element`.
f10508:c0:m17
def wait(self, timeout=<NUM_LIT:10>):
return self.driver.wait(timeout)<EOL>
Alias for :py:meth:`~webdriverwrapper.wrapper._WebdriverWrapper.wait`.
f10508:c0:m18
def go_to(self, *args, **kwds):
self.driver.go_to(*args, **kwds)<EOL>
Alias for :py:meth:`~webdriverwrapper.wrapper._WebdriverWrapper.go_to`.
f10508:c0:m19
def switch_to_window(self, window_name=None, title=None, url=None):
self.driver.switch_to_window(window_name, title, url)<EOL>
Alias for :py:meth:`~webdriverwrapper.wrapper._WebdriverWrapper.switch_to_window`.
f10508:c0:m20
def close_window(self, window_name=None, title=None, url=None):
self.driver.close_window(window_name, title, url)<EOL>
Alias for :py:meth:`~webdriverwrapper.wrapper._WebdriverWrapper.close_window`.
f10508:c0:m21
def close_other_windows(self):
self.driver.close_other_windows()<EOL>
Alias for :py:meth:`~webdriverwrapper.wrapper._WebdriverWrapper.close_other_windows`.
f10508:c0:m22
@classmethod<EOL><INDENT>def _make_instance(cls, element_class, webelement):<DEDENT>
if isinstance(webelement, FirefoxWebElement):<EOL><INDENT>element_class = copy.deepcopy(element_class)<EOL>element_class.__bases__ = tuple(<EOL>FirefoxWebElement if base is WebElement else base<EOL>for base in element_class.__bases__<EOL>)<EOL><DEDENT>return element_class(webelement)<EOL>
Firefox uses another implementation of element. This method switch base of wrapped element to firefox one.
f10513:c0:m3
def contains_text(self, text):
return bool(self.get_elms(text=text))<EOL>
Does page or element contains `text`? Uses method :py:meth:`~._WebdriverBaseWrapper.get_elms`.
f10513:c1:m0
def find_element_by_text(self, text):
return self.get_elm(text=text)<EOL>
Returns first element on page or in element containing ``text``. .. versionadded:: 2.0 .. deprecated:: 2.8 Use :py:meth:`~._WebdriverBaseWrapper.get_elm` instead.
f10513:c1:m1
def find_elements_by_text(self, text):
return self.get_elms(text=text)<EOL>
Returns all elements on page or in element containing ``text``. .. versionchanged:: 2.0 Searching in all text nodes. Before it wouldn't find string "text" in HTML like ``<div>some<br />text in another text node</div>``. .. deprecated:: 2.8 Use :py:meth:`~._WebdriverBaseWrapper.get_elms` instead.
f10513:c1:m2
def click(self, *args, **kwds):
if args or kwds:<EOL><INDENT>elm = self.get_elm(*args, **kwds)<EOL>elm.click()<EOL><DEDENT>else:<EOL><INDENT>super().click()<EOL><DEDENT>
When you not pass any argument, it clicks on current element. If you pass some arguments, it works as following snippet. For more info what you can pass check out method :py:meth:`~._WebdriverBaseWrapper.get_elm`. .. code-block:: python driver.get_elm('someid').click()
f10513:c1:m3
def get_elm(<EOL>self,<EOL>id_=None, class_name=None, name=None, tag_name=None, text=None, xpath=None,<EOL>parent_id=None, parent_class_name=None, parent_name=None, parent_tag_name=None,<EOL>css_selector=None<EOL>):
elms = self.get_elms(<EOL>id_, class_name, name, tag_name, text, xpath,<EOL>parent_id, parent_class_name, parent_name, parent_tag_name,<EOL>css_selector<EOL>)<EOL>if not elms:<EOL><INDENT>raise selenium_exc.NoSuchElementException(_create_exception_msg(<EOL>id_, class_name, name, tag_name,<EOL>parent_id, parent_class_name, parent_name, parent_tag_name,<EOL>text, xpath, css_selector, self.current_url,<EOL>driver=self._driver,<EOL>))<EOL><DEDENT>return elms[<NUM_LIT:0>]<EOL>
Returns first found element. This method uses :py:meth:`~._WebdriverBaseWrapper.get_elms`.
f10513:c1:m4
def get_elms(<EOL>self,<EOL>id_=None, class_name=None, name=None, tag_name=None, text=None, xpath=None,<EOL>parent_id=None, parent_class_name=None, parent_name=None, parent_tag_name=None,<EOL>css_selector=None<EOL>):
if parent_id or parent_class_name or parent_name or parent_tag_name:<EOL><INDENT>parent = self.get_elm(parent_id, parent_class_name, parent_name, parent_tag_name)<EOL><DEDENT>else:<EOL><INDENT>parent = self<EOL><DEDENT>if len([x for x in (id_, class_name, tag_name, text, xpath) if x is not None]) > <NUM_LIT:1>:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if id_ is not None:<EOL><INDENT>return parent.find_elements_by_id(id_)<EOL><DEDENT>if class_name is not None:<EOL><INDENT>return parent.find_elements_by_class_name(class_name)<EOL><DEDENT>if name is not None:<EOL><INDENT>return parent.find_elements_by_name(name)<EOL><DEDENT>if tag_name is not None:<EOL><INDENT>return parent.find_elements_by_tag_name(tag_name)<EOL><DEDENT>if text is not None:<EOL><INDENT>xpath = '<STR_LIT>'.format(text)<EOL><DEDENT>if xpath is not None:<EOL><INDENT>return parent.find_elements_by_xpath(xpath)<EOL><DEDENT>if css_selector is not None:<EOL><INDENT>return parent.find_elements_by_css_selector(css_selector)<EOL><DEDENT>raise Exception('<STR_LIT>')<EOL>
Shortcut for :py:meth:`find_element* <selenium.webdriver.remote.webelement.WebElement.find_element>` methods. It's shorter and you can quickly find element in element. .. code-block:: python elm = driver.find_element_by_id('someid') elm.find_elements_by_class_name('someclasss') # vs. elm = driver.get_elm(parent_id='someid', class_name='someclass') .. versionchanged:: 2.8 Added ``text`` param. Use it instead of old ``find_element[s]_by_text`` methods. Thanks to that it can be used also in ``wait_for_element*`` methods.
f10513:c1:m5
def wait_for_element(self, timeout=None, message='<STR_LIT>', *args, **kwds):
if not timeout:<EOL><INDENT>timeout = self.default_wait_timeout<EOL><DEDENT>if not message:<EOL><INDENT>message = _create_exception_msg(*args, url=self.current_url, **kwds)<EOL><DEDENT>self.wait(timeout).until(lambda driver: driver.get_elm(*args, **kwds), message=message)<EOL>elm = self.get_elm(*args, **kwds)<EOL>return elm<EOL>
Shortcut for waiting for element. If it not ends with exception, it returns that element. Detault timeout is `~.default_wait_timeout`. Same as following: .. code-block:: python selenium.webdriver.support.wait.WebDriverWait(driver, timeout).until(lambda driver: driver.get_elm(...)) .. versionchanged:: 2.5 Waits only for visible elements. .. versionchanged:: 2.6 Returned functionality back in favor of new method :py:meth:`~._WebdriverBaseWrapper.wait_for_element_show`.
f10513:c1:m10
def wait_for_element_show(self, timeout=None, message='<STR_LIT>', *args, **kwds):
if not timeout:<EOL><INDENT>timeout = self.default_wait_timeout<EOL><DEDENT>if not message:<EOL><INDENT>message = _create_exception_msg(*args, url=self.current_url, **kwds)<EOL><DEDENT>def callback(driver):<EOL><INDENT>elms = driver.get_elms(*args, **kwds)<EOL>if not elms:<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>if all(not elm.is_displayed() for elm in elms):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>except selenium_exc.StaleElementReferenceException:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL><DEDENT>self.wait(timeout).until(callback, message=message)<EOL>elm = self.get_elm(*args, **kwds)<EOL>return elm<EOL>
Shortcut for waiting for visible element. If it not ends with exception, it returns that element. Detault timeout is `~.default_wait_timeout`. Same as following: .. code-block:: python selenium.webdriver.support.wait.WebDriverWait(driver, timeout).until(lambda driver: driver.get_elm(...)) .. versionadded:: 2.6
f10513:c1:m11
def wait_for_element_hide(self, timeout=None, message='<STR_LIT>', *args, **kwds):
if not timeout:<EOL><INDENT>timeout = self.default_wait_timeout<EOL><DEDENT>if not message:<EOL><INDENT>message = '<STR_LIT>'.format(_create_exception_msg(*args, url=self.current_url, **kwds))<EOL><DEDENT>def callback(driver):<EOL><INDENT>elms = driver.get_elms(*args, **kwds)<EOL>if not elms:<EOL><INDENT>return True<EOL><DEDENT>try:<EOL><INDENT>if all(not elm.is_displayed() for elm in elms):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>except selenium_exc.StaleElementReferenceException:<EOL><INDENT>return False<EOL><DEDENT>return False<EOL><DEDENT>self.wait(timeout).until(callback, message=message)<EOL>
Shortcut for waiting for hiding of element. Detault timeout is `~.default_wait_timeout`. Same as following: .. code-block:: python selenium.webdriver.support.wait.WebDriverWait(driver, timeout).until(lambda driver: not driver.get_elm(...)) .. versionadded:: 2.0
f10513:c1:m12
def wait(self, timeout=None):
if not timeout:<EOL><INDENT>timeout = self.default_wait_timeout<EOL><DEDENT>return WebDriverWait(self, timeout)<EOL>
Calls following snippet so you don't have to remember what import. See :py:obj:`WebDriverWait <selenium.webdriver.support.wait.WebDriverWait>` for more information. Detault timeout is `~.default_wait_timeout`. .. code-block:: python selenium.webdriver.support.wait.WebDriverWait(driver, timeout) Example: .. code-block:: python driver.wait().until(lambda driver: len(driver.find_element_by_id('elm')) > 10) If you need to wait for element, consider using :py:meth:`~._WebdriverWrapper.wait_for_element` instead.
f10513:c1:m13
@property<EOL><INDENT>def _driver(self):<DEDENT>
return self<EOL>
Returns always driver, not element. Use it when you need driver and variable can be driver or element.
f10513:c2:m1
@property<EOL><INDENT>def html(self):<DEDENT>
try:<EOL><INDENT>body = self.get_elm(tag_name='<STR_LIT:body>')<EOL><DEDENT>except selenium_exc.NoSuchElementException:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return body.get_attribute('<STR_LIT>')<EOL><DEDENT>
Returns ``innerHTML`` of whole page. On page have to be tag ``body``. .. versionadded:: 2.2
f10513:c2:m2
def make_screenshot(self, screenshot_name=None):
if not self.screenshot_path:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if not screenshot_name:<EOL><INDENT>screenshot_name = str(time.time())<EOL><DEDENT>self.get_screenshot_as_file('<STR_LIT>'.format(self.screenshot_path, screenshot_name))<EOL>
Shortcut for ``get_screenshot_as_file`` but with configured path. If you are using base :py:class:`~webdriverwrapper.unittest.testcase.WebdriverTestCase`. or pytest, ``screenshot_path`` is passed to driver automatically. If ``screenshot_name`` is not passed, current timestamp is used. .. versionadded:: 2.2
f10513:c2:m3
def break_point(self):
logging.info('<STR_LIT>')<EOL>input()<EOL>
Stops testing and wait for pressing enter to continue. Useful when you need check Chrome console for some info for example. .. versionadded:: 2.1
f10513:c2:m4
def go_to(self, path=None, query=None):
self.get(self.get_url(path, query))<EOL>
You have to pass absolute URL to method :py:meth:`~selenium.webdriver.remote.webdriver.WebDriver.get`. This method help you to pass only relative ``path`` and/or ``query``. See method :py:meth:`.get_url` for more information. .. versionchanged:: 2.0 Removed parameter ``domain``. If you want to go to completely another web app, use absolute address.
f10513:c2:m5
def get_url(self, path=None, query=None):
if urlparse(path).netloc:<EOL><INDENT>return path<EOL><DEDENT>if isinstance(query, dict):<EOL><INDENT>query = urlencode(query)<EOL><DEDENT>url_parts = urlparse(self.current_url)<EOL>new_url_parts = (<EOL>url_parts.scheme,<EOL>url_parts.netloc,<EOL>path or url_parts.path,<EOL>None, <EOL>query,<EOL>None, <EOL>)<EOL>url = urlunparse(new_url_parts)<EOL>return url<EOL>
You have to pass absolute URL to method :py:meth:`~selenium.webdriver.remote.webdriver.WebDriver.get`. This method help you to pass only relative ``path`` and/or ``query``. Scheme and domains is append to URL from :py:attr:`~selenium.webdriver.remote.webdriver.WebDriver.current_url`. ``query`` can be final string or dictionary. On dictionary it calls :py:func:`urllib.urlencode`. .. versionadded:: 2.0
f10513:c2:m6
def switch_to_window(self, window_name=None, title=None, url=None):
if window_name:<EOL><INDENT>self.switch_to.window(window_name)<EOL>return<EOL><DEDENT>if url:<EOL><INDENT>url = self.get_url(path=url)<EOL><DEDENT>for window_handle in self.window_handles:<EOL><INDENT>self.switch_to.window(window_handle)<EOL>if title and self.title == title:<EOL><INDENT>return<EOL><DEDENT>if url and self.current_url == url:<EOL><INDENT>return<EOL><DEDENT><DEDENT>raise selenium_exc.NoSuchWindowException('<STR_LIT>' % (title, url))<EOL>
WebDriver implements switching to other window only by it's name. With wrapper there is also option to switch by title of window or URL. URL can be also relative path.
f10513:c2:m7
def close_window(self, window_name=None, title=None, url=None):
main_window_handle = self.current_window_handle<EOL>self.switch_to_window(window_name, title, url)<EOL>self.close()<EOL>self.switch_to_window(main_window_handle)<EOL>
WebDriver implements only closing current window. If you want to close some window without having to switch to it, use this method.
f10513:c2:m8
def close_other_windows(self):
main_window_handle = self.current_window_handle<EOL>for window_handle in self.window_handles:<EOL><INDENT>if window_handle == main_window_handle:<EOL><INDENT>continue<EOL><DEDENT>self.switch_to_window(window_handle)<EOL>self.close()<EOL><DEDENT>self.switch_to_window(main_window_handle)<EOL>
Closes all not current windows. Useful for tests - after each test you can automatically close all windows.
f10513:c2:m9
def close_alert(self, ignore_exception=False):
try:<EOL><INDENT>alert = self.get_alert()<EOL>alert.accept()<EOL><DEDENT>except:<EOL><INDENT>if not ignore_exception:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>
JS alerts all blocking. This method closes it. If there is no alert, method raises exception. In tests is good to call this method with ``ignore_exception`` setted to ``True`` which will ignore any exception.
f10513:c2:m10
def get_alert(self):
return Alert(self)<EOL>
Returns instance of :py:obj:`~selenium.webdriver.common.alert.Alert`.
f10513:c2:m11
def wait_for_alert(self, timeout=None):
if not timeout:<EOL><INDENT>timeout = self.default_wait_timeout<EOL><DEDENT>alert = Alert(self)<EOL>def alert_shown(driver):<EOL><INDENT>try:<EOL><INDENT>alert.text<EOL>return True<EOL><DEDENT>except selenium_exc.NoAlertPresentException:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>self.wait(timeout).until(alert_shown)<EOL>return alert<EOL>
Shortcut for waiting for alert. If it not ends with exception, it returns that alert. Detault timeout is `~.default_wait_timeout`.
f10513:c2:m12
def download_url(self, url=None):
return DownloadUrl(self, url)<EOL>
With WebDriver you can't check status code or headers. For this you have to make classic request. But web pages needs cookies and by this it gets ugly. You can easily use this method. When you not pass ``url``, :py:attr:`~selenium.webdriver.remote.webdriver.WebDriver.current_url` will be used. Returns :py:obj:`~webdriverwrapper.download._Download` instance.
f10513:c2:m13
def fill_out_and_submit(self, data, prefix='<STR_LIT>', turbo=False):
return self.get_elm(tag_name='<STR_LIT>').fill_out_and_submit(data, prefix, turbo)<EOL>
Shortcut for filling out first ``<form>`` on page. See :py:class:`~webdriverwrapper.forms.Form` for more information. .. versionadded:: 2.0
f10513:c2:m14
def fill_out(self, data, prefix='<STR_LIT>', turbo=False):
return self.get_elm(tag_name='<STR_LIT>').fill_out(data, prefix, turbo)<EOL>
Shortcut for filling out first ``<form>`` on page. See :py:class:`~webdriverwrapper.forms.Form` for more information. .. versionadded:: 2.0
f10513:c2:m15
@property<EOL><INDENT>def _driver(self):<DEDENT>
return self._parent<EOL>
Returns always driver, not element. Use it when you need driver and variable can be driver or element.
f10513:c3:m2
@property<EOL><INDENT>def current_url(self):<DEDENT>
try:<EOL><INDENT>current_url = self._driver.current_url<EOL><DEDENT>except Exception: <EOL><INDENT>current_url = '<STR_LIT>'<EOL><DEDENT>finally:<EOL><INDENT>return current_url<EOL><DEDENT>
Accessing :py:attr:`~selenium.webdriver.remote.webdriver.WebDriver.current_url` also on elements.
f10513:c3:m3
@property<EOL><INDENT>def html(self):<DEDENT>
self.get_attribute('<STR_LIT>')<EOL>
Returns ``innerHTML``. .. versionadded:: 2.2
f10513:c3:m4
def download_file(self):
return DownloadFile(self)<EOL>
With WebDriver you can't check status code or headers. For this you have to make classic request. But web pages needs cookies and data from forms and by this it gets pretty ugly. You can easily use this method. It can handle downloading of page/file by link or any type of form. Returns :py:obj:`~webdriverwrapper.download._Download` instance.
f10513:c3:m6
def sphinx_extension(app, exception):
if not app.builder.name in ("<STR_LIT:html>", "<STR_LIT>"):<EOL><INDENT>return<EOL><DEDENT>if not app.config.sphinx_to_github:<EOL><INDENT>if app.config.sphinx_to_github_verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return<EOL><DEDENT>if exception:<EOL><INDENT>if app.config.sphinx_to_github_verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return<EOL><DEDENT>dir_helper = DirHelper(<EOL>os.path.isdir,<EOL>os.listdir,<EOL>os.walk,<EOL>shutil.rmtree<EOL>)<EOL>file_helper = FileSystemHelper(<EOL>lambda f, mode: codecs.open(f, mode, app.config.sphinx_to_github_encoding),<EOL>os.path.join,<EOL>shutil.move,<EOL>os.path.exists<EOL>)<EOL>operations_factory = OperationsFactory()<EOL>handler_factory = HandlerFactory()<EOL>layout_factory = LayoutFactory(<EOL>operations_factory,<EOL>handler_factory,<EOL>file_helper,<EOL>dir_helper,<EOL>app.config.sphinx_to_github_verbose,<EOL>sys.stdout,<EOL>force=True<EOL>)<EOL>layout = layout_factory.create_layout(app.outdir)<EOL>layout.process()<EOL>
Wrapped up as a Sphinx Extension
f10515:m0
def setup(app):
app.add_config_value("<STR_LIT>", True, '<STR_LIT>')<EOL>app.add_config_value("<STR_LIT>", True, '<STR_LIT>')<EOL>app.add_config_value("<STR_LIT>", '<STR_LIT:utf-8>', '<STR_LIT>')<EOL>app.connect("<STR_LIT>", sphinx_extension)<EOL>
Setup function for Sphinx Extension
f10515:m1
def apply_calibration(sig, fs, frange, calibration):
if isinstance(calibration, tuple):<EOL><INDENT>calfqs, calvals = calibration<EOL>return multiply_frequencies(sig, fs, frange, calfqs, calvals)<EOL><DEDENT>elif calibration is not None:<EOL><INDENT>return convolve_filter(sig, calibration)<EOL><DEDENT>else:<EOL><INDENT>return sig<EOL><DEDENT>
Takes the given *calibration* and applies to to signal *sig*, implicitly determining calibration method by type of *calibration*
f10565:m3
def run_tone_curve(frequencies, intensities, player, fs, duration, <EOL>refdb, refv, calibration, frange):
tone = PureTone()<EOL>tone.setRisefall(<NUM_LIT>)<EOL>vfunc = np.vectorize(calc_db)<EOL>player.set_aidur(duration)<EOL>player.set_aifs(fs)<EOL>tone.setDuration(duration)<EOL>specpeaks = np.zeros((len(intensities), len(frequencies)))<EOL>toneamps_rms = np.zeros((len(intensities), len(frequencies)))<EOL>toneamps_peak = np.zeros((len(intensities), len(frequencies)))<EOL>tone_summed_curve_db = np.zeros((len(intensities), len(frequencies)))<EOL>tone_signal_amp = np.zeros((len(intensities), len(frequencies)))<EOL>for db_idx, ti in enumerate(intensities):<EOL><INDENT>tone.setIntensity(ti)<EOL>for freq_idx, tf in enumerate(frequencies):<EOL><INDENT>sys.stdout.write('<STR_LIT:.>') <EOL>tone.setFrequency(tf)<EOL>calibrated_tone = apply_calibration(tone.signal(fs, <NUM_LIT:0>, refdb, refv), <EOL>fs, frange, calibration)<EOL>mean_response = record(player, calibrated_tone, fs)<EOL>freqs, spectrum = calc_spectrum(mean_response, fs)<EOL>mag = spectrum[(np.abs(freqs-tf)).argmin()]<EOL>specpeaks[db_idx, freq_idx] = mag<EOL>toneamps_rms[db_idx, freq_idx] = rms(mean_response, fs)<EOL>toneamps_peak[db_idx, freq_idx] = np.amax(mean_response)<EOL>idx = np.where((freqs > <NUM_LIT>) & (freqs < <NUM_LIT>))<EOL>tone_summed_curve_db[db_idx, freq_idx] = calc_summed_db(spectrum[idx], MPHONESENS, MPHONECALDB)<EOL>tone_signal_amp[db_idx, freq_idx] = signal_amplitude(mean_response, fs)<EOL><DEDENT><DEDENT>spec_peak_curve_db = vfunc(specpeaks, MPHONESENS, MPHONECALDB)<EOL>tone_amp_rms_curve_db = vfunc(toneamps_rms, MPHONESENS, MPHONECALDB)<EOL>tone_amp_peak_curve_db = vfunc(toneamps_peak, MPHONESENS, MPHONECALDB)<EOL>tone_signal_amp_db = vfunc(tone_signal_amp, MPHONESENS, MPHONECALDB)<EOL>return tone_signal_amp_db, spec_peak_curve_db, tone_amp_rms_curve_db, tone_amp_peak_curve_db, tone_summed_curve_db<EOL>
Runs a calibration tone curve, spits out arrays with a bunch of different methods to calculate the dB SPL: * dB SPL calculated from signal_amplitude from audiotools * dB SPL calculated from the peak value of the response spectrum * dB SPL calculated from the RMS value of the signal * dB SPL calculated from the peak value of the signal * dB SPL calculated from the summed values of the spectrum
f10565:m4
def record_refdb(player, calf, refv, fs):
dur = <NUM_LIT><EOL>reftone = PureTone()<EOL>reftone.setRisefall(<NUM_LIT>)<EOL>reftone.setDuration(dur)<EOL>tempdb = <NUM_LIT> <EOL>reftone.setIntensity(tempdb)<EOL>reftone.setFrequency(calf)<EOL>ref_db_signal = reftone.signal(fs, <NUM_LIT:0>, tempdb, refv)<EOL>player.set_aidur(dur)<EOL>player.set_aifs(fs)<EOL>ref_db_response = record(player, ref_db_signal, fs)<EOL>refdb = calc_db(signal_amplitude(ref_db_response, fs), MPHONESENS, MPHONECALDB)<EOL>print("<STR_LIT>", refdb)<EOL>return refdb<EOL>
records a tone to determine the dB SPL for a given voltage amplitude
f10565:m5
def rgbcolor(h, f):
<EOL>if h == <NUM_LIT:0>:<EOL><INDENT>return v, f, p<EOL><DEDENT>elif h == <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:1> - f, v, p<EOL><DEDENT>elif h == <NUM_LIT:2>:<EOL><INDENT>return p, v, f<EOL><DEDENT>elif h == <NUM_LIT:3>:<EOL><INDENT>return p, <NUM_LIT:1> - f, v<EOL><DEDENT>elif h == <NUM_LIT:4>:<EOL><INDENT>return f, p, v<EOL><DEDENT>elif h == <NUM_LIT:5>:<EOL><INDENT>return v, p, <NUM_LIT:1> - f<EOL><DEDENT>
Convert a color specified by h-value and f-value to an RGB three-tuple.
f10568:m0
def rgb(i, n):
hue = <NUM_LIT> / n * i<EOL>h = np.floor(hue / <NUM_LIT>) % <NUM_LIT:6><EOL>f = hue / <NUM_LIT> - np.floor(hue / <NUM_LIT>)<EOL>color_tuple = rgbcolor(h,f)<EOL>color_tuple = (color_tuple[<NUM_LIT:0>]*<NUM_LIT:255>, color_tuple[<NUM_LIT:1>]*<NUM_LIT:255>, color_tuple[<NUM_LIT:2>]*<NUM_LIT:255>)<EOL>return color_tuple<EOL>
Compute a list of distinct colors, ecah of which is represented as an RGB three-tuple
f10568:m1
def increment_title(title):
count = re.search('<STR_LIT>', title).group(<NUM_LIT:0>)<EOL>new_title = title[:-(len(count))] + str(int(count)+<NUM_LIT:1>)<EOL>return new_title<EOL>
Increments a string that ends in a number
f10571:m0
def clearLayout(layout):
if layout is not None:<EOL><INDENT>while layout.count():<EOL><INDENT>item = layout.takeAt(<NUM_LIT:0>)<EOL>widget = item.widget()<EOL>if widget is not None:<EOL><INDENT>widget.deleteLater()<EOL><DEDENT>else:<EOL><INDENT>clearLayout(item.layout())<EOL><DEDENT><DEDENT><DEDENT>
Clears widgets from the given *layout*
f10571:m5
def qtdoc_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
base = '<STR_LIT>'<EOL>match = re.search('<STR_LIT>', text)<EOL>if match is None:<EOL><INDENT>raise ValueError<EOL><DEDENT>label = match.group(<NUM_LIT:1>)<EOL>if match.lastindex == <NUM_LIT:2>:<EOL><INDENT>clsmeth = match.group(<NUM_LIT:2>)[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL>cls, meth = clsmeth.split('<STR_LIT:.>')<EOL>ref = base + cls + '<STR_LIT>' + meth<EOL><DEDENT>else:<EOL><INDENT>ref = base + label.lower() + '<STR_LIT>'<EOL><DEDENT>node = nodes.reference(rawtext, label, refuri=ref, **options)<EOL>return [node], []<EOL>
Links to a Qt class's doc Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization.
f10572:m0
def setup(app):
app.info("<STR_LIT>")<EOL>app.add_role('<STR_LIT>', qtdoc_role)<EOL>
Installs the plugin. :param app: Sphinx application context.
f10572:m1
def init_logging():
with open(os.path.join(os.path.dirname(__file__),'<STR_LIT>'), '<STR_LIT:r>') as yf:<EOL><INDENT>config = yaml.load(yf)<EOL><DEDENT>logging.config.dictConfig(config)<EOL>
Initialize a logger from a configuration file to use throughout the project
f10573:m0
def init_logging():
with open(os.path.join(os.path.dirname(__file__),'<STR_LIT>'), '<STR_LIT:r>') as yf:<EOL><INDENT>config = yaml.load(yf)<EOL><DEDENT>logging.config.dictConfig(config)<EOL>
Initialize a logger from a configuration file to use throughout the project
f10575:m0
def refractory(times, refract=<NUM_LIT>):
times_refract = []<EOL>times_refract.append(times[<NUM_LIT:0>])<EOL>for i in range(<NUM_LIT:1>,len(times)):<EOL><INDENT>if times_refract[-<NUM_LIT:1>]+refract <= times[i]:<EOL><INDENT>times_refract.append(times[i]) <EOL><DEDENT><DEDENT>return times_refract<EOL>
Removes spikes in times list that do not satisfy refractor period :param times: list(float) of spike times in seconds :type times: list(float) :param refract: Refractory period in seconds :type refract: float :returns: list(float) of spike times in seconds For every interspike interval < refract, removes the second spike time in list and returns the result
f10576:m0
def spike_times(signal, threshold, fs, absval=True):
times = []<EOL>if absval:<EOL><INDENT>signal = np.abs(signal)<EOL><DEDENT>over, = np.where(signal>threshold)<EOL>segments, = np.where(np.diff(over) > <NUM_LIT:1>)<EOL>if len(over) > <NUM_LIT:1>:<EOL><INDENT>if len(segments) == <NUM_LIT:0>:<EOL><INDENT>segments = [<NUM_LIT:0>, len(over)-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>if segments[<NUM_LIT:0>] != <NUM_LIT:0>:<EOL><INDENT>segments = np.insert(segments, [<NUM_LIT:0>], [<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>times.append(float(over[<NUM_LIT:0>])/fs)<EOL>if <NUM_LIT:1> not in segments:<EOL><INDENT>segments[<NUM_LIT:0>] = <NUM_LIT:1><EOL><DEDENT><DEDENT>if segments[-<NUM_LIT:1>] != len(over)-<NUM_LIT:1>:<EOL><INDENT>segments = np.insert(segments, [len(segments)], [len(over)-<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>times.append(float(over[-<NUM_LIT:1>])/fs)<EOL><DEDENT><DEDENT>for iseg in range(<NUM_LIT:1>,len(segments)):<EOL><INDENT>if segments[iseg] - segments[iseg-<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>idx = over[segments[iseg]]<EOL><DEDENT>else:<EOL><INDENT>segments[<NUM_LIT:0>] = segments[<NUM_LIT:0>]-<NUM_LIT:1> <EOL>idx = over[segments[iseg-<NUM_LIT:1>]+<NUM_LIT:1>] + np.argmax(signal[over[segments[iseg-<NUM_LIT:1>]+<NUM_LIT:1>]:over[segments[iseg]]])<EOL><DEDENT>times.append(float(idx)/fs)<EOL><DEDENT><DEDENT>elif len(over) == <NUM_LIT:1>:<EOL><INDENT>times.append(float(over[<NUM_LIT:0>])/fs)<EOL><DEDENT>if len(times)><NUM_LIT:0>:<EOL><INDENT>return refractory(times)<EOL><DEDENT>else:<EOL><INDENT>return times<EOL><DEDENT>
Detect spikes from a given signal :param signal: Spike trace recording (vector) :type signal: numpy array :param threshold: Threshold value to determine spikes :type threshold: float :param absval: Whether to apply absolute value to signal before thresholding :type absval: bool :returns: list(float) of spike times in seconds For every continuous set of points over given threshold, returns the time of the maximum
f10576:m1
def bin_spikes(spike_times, binsz):
bins = np.empty((len(spike_times),), dtype=int)<EOL>for i, stime in enumerate(spike_times):<EOL><INDENT>bins[i] = np.floor(np.around(stime/binsz, <NUM_LIT:5>))<EOL><DEDENT>return bins<EOL>
Sort spike times into bins :param spike_times: times of spike instances :type spike_times: list :param binsz: length of time bin to use :type binsz: float :returns: list of bin indicies, one for each element in spike_times
f10576:m2
def spike_latency(signal, threshold, fs):
over, = np.where(signal>threshold)<EOL>segments, = np.where(np.diff(over) > <NUM_LIT:1>)<EOL>if len(over) > <NUM_LIT:1>:<EOL><INDENT>if len(segments) == <NUM_LIT:0>:<EOL><INDENT>idx = over[<NUM_LIT:0>] + np.argmax(signal[over[<NUM_LIT:0>]:over[-<NUM_LIT:1>]])<EOL>latency = float(idx)/fs<EOL><DEDENT>elif segments[<NUM_LIT:0>] == <NUM_LIT:0>:<EOL><INDENT>latency = float(over[<NUM_LIT:0>])/fs<EOL><DEDENT>else:<EOL><INDENT>idx = over[<NUM_LIT:0>] + np.argmax(signal[over[<NUM_LIT:0>]:over[segments[<NUM_LIT:0>]]])<EOL>latency = float(idx)/fs<EOL><DEDENT><DEDENT>elif len(over) > <NUM_LIT:0>:<EOL><INDENT>latency = float(over[<NUM_LIT:0>])/fs<EOL><DEDENT>else:<EOL><INDENT>latency = np.nan<EOL><DEDENT>return latency<EOL>
Find the latency of the first spike over threshold :param signal: Spike trace recording (vector) :type signal: numpy array :param threshold: Threshold value to determine spikes :type threshold: float :returns: float -- Time of peak of first spike, or None if no values over threshold This is the same as the first value returned from calc_spike_times
f10576:m3
def firing_rate(spike_times, window_size=None):
if len(spike_times) == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>if window_size is None:<EOL><INDENT>if len(spike_times) > <NUM_LIT:1>:<EOL><INDENT>window_size = spike_times[-<NUM_LIT:1>] - spike_times[<NUM_LIT:0>]<EOL><DEDENT>elif len(spike_times) > <NUM_LIT:0>:<EOL><INDENT>window_size = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>window_size = <NUM_LIT:0><EOL><DEDENT><DEDENT>rate = window_size/len(spike_times)<EOL>return rate<EOL>
Calculate the firing rate of spikes :param spike_times: times of spike instances :type spike_times: list :param window_size: length of time to use to determine rate. If none, uses time from first to last spike in spike_times :type window_size: float
f10576:m4
def dataset_spike_counts(dset, threshold, fs):
if len(dset.shape) == <NUM_LIT:3>:<EOL><INDENT>results = np.zeros(dset.shape[<NUM_LIT:0>])<EOL>for itrace in range(dset.shape[<NUM_LIT:0>]):<EOL><INDENT>results[itrace] = count_spikes(dset[itrace], threshold, fs)<EOL><DEDENT>return results<EOL><DEDENT>elif len(dset.shape == <NUM_LIT:2>):<EOL><INDENT>return count_spikes(dset, threshold, fs)<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>
Dataset should be of dimensions (trace, rep, samples)
f10576:m5
def calc_db(peak, refval, mphonecaldb=<NUM_LIT:0>):
if refval == <NUM_LIT:0>:<EOL><INDENT>return np.nan<EOL><DEDENT>if hasattr(peak, '<STR_LIT>'):<EOL><INDENT>peak[peak == <NUM_LIT:0>] = np.nan<EOL><DEDENT>pbdB = mphonecaldb + (<NUM_LIT> * np.log10(peak / refval))<EOL>return pbdB<EOL>
Converts voltage difference into decibels : 20*log10(peak/refval) :param peak: amplitude :type peak: float or np.array :param refval: This can be either a another sound peak(or RMS val), to get the dB difference, or the microphone mphone_sensitivity :type refval: float :param mphonecaldb: If using the microphone sensitivity for refval, provide the dB SPL the microphone was calibrated at. Otherwise, leave as 0 :type mphonecaldb: int :returns: float -- decibels difference (comparision), or dB SPL (using microphone sensitivity)
f10580:m0
def calc_spectrum(signal, rate):
npts = len(signal)<EOL>padto = <NUM_LIT:1> << (npts - <NUM_LIT:1>).bit_length()<EOL>npts = padto<EOL>sp = np.fft.rfft(signal, n=padto) / npts<EOL>freq = np.arange((npts / <NUM_LIT:2>) + <NUM_LIT:1>) / (npts / rate)<EOL>return freq, abs(sp)<EOL>
Return the spectrum and frequency indexes for real-valued input signal
f10580:m3
def make_tone(freq, db, dur, risefall, samplerate, caldb=<NUM_LIT:100>, calv=<NUM_LIT:0.1>):
if risefall > dur:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if samplerate <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if caldb <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>npts = int(dur * samplerate)<EOL>amp = (<NUM_LIT:10> ** ((db - caldb) / <NUM_LIT:20>) * calv)<EOL>if USE_RMS:<EOL><INDENT>amp = amp * <NUM_LIT><EOL><DEDENT>if VERBOSE:<EOL><INDENT>print((<EOL>"<STR_LIT>".format(db, samplerate, freq / <NUM_LIT:1000>, amp)))<EOL>print(("<STR_LIT>".format(caldb, calv)))<EOL><DEDENT>tone = amp * np.sin((freq * dur) * np.linspace(<NUM_LIT:0>, <NUM_LIT:2> * np.pi, npts))<EOL>if risefall > <NUM_LIT:0>:<EOL><INDENT>rf_npts = int(risefall * samplerate) // <NUM_LIT:2><EOL>wnd = hann(rf_npts * <NUM_LIT:2>) <EOL>tone[:rf_npts] = tone[:rf_npts] * wnd[:rf_npts]<EOL>tone[-rf_npts:] = tone[-rf_npts:] * wnd[rf_npts:]<EOL><DEDENT>timevals = np.arange(npts) / samplerate<EOL>return tone, timevals<EOL>
Produce a pure tone signal :param freq: Frequency of the tone to be produced (Hz) :type freq: int :param db: Intensity of the tone in dB SPL :type db: int :param dur: duration (seconds) :type dur: float :param risefall: linear rise fall of (seconds) :type risefall: float :param samplerate: generation frequency of tone (Hz) :type samplerate: int :param caldb: Reference intensity (dB SPL). Together with calv, provides a reference point for what intensity equals what output voltage level :type caldb: int :param calv: Reference voltage (V). Together with caldb, provides a reference point for what intensity equals what output voltage level :type calv: float :returns: tone, timevals -- the signal and the time index values
f10580:m4
def make_carrier_tone(freq, db, dur, samplerate, caldb=<NUM_LIT:100>, calv=<NUM_LIT:0.1>):
if samplerate <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if caldb <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>npts = int(dur * samplerate)<EOL>amp = (<NUM_LIT:10> ** ((db - caldb) / <NUM_LIT:20>) * calv)<EOL>if USE_RMS:<EOL><INDENT>amp *= <NUM_LIT><EOL><DEDENT>if VERBOSE:<EOL><INDENT>print((<EOL>"<STR_LIT>".format(db, samplerate, freq / <NUM_LIT:1000>, amp)))<EOL>print(("<STR_LIT>".format(caldb, calv)))<EOL><DEDENT>tone = amp * np.sin((freq * dur) * np.linspace(<NUM_LIT:0>, <NUM_LIT:2> * np.pi, npts))<EOL>timevals = np.arange(npts) / samplerate<EOL>return tone, timevals<EOL>
Produce a pure tone signal :param freq: Frequency of the tone to be produced (Hz) :type freq: int :param db: Intensity of the tone in dB SPL :type db: int :param dur: duration (seconds) :type dur: float :param samplerate: generation frequency of tone (Hz) :type samplerate: int :param caldb: Reference intensity (dB SPL). Together with calv, provides a reference point for what intensity equals what output voltage level :type caldb: int :param calv: Reference voltage (V). Together with caldb, provides a reference point for what intensity equals what output voltage level :type calv: float :returns: tone, timevals -- the signal and the time index values
f10580:m5
def spectrogram(source, nfft=<NUM_LIT>, overlap=<NUM_LIT>, window='<STR_LIT>', caldb=<NUM_LIT>, calv=<NUM_LIT>):
if isinstance(source, str):<EOL><INDENT>fs, wavdata = audioread(source)<EOL><DEDENT>else:<EOL><INDENT>fs, wavdata = source<EOL><DEDENT>duration = float(len(wavdata)) / fs<EOL>desired_npts = int((np.trunc(duration * <NUM_LIT:1000>) / <NUM_LIT:1000>) * fs)<EOL>wavdata = wavdata[:desired_npts]<EOL>duration = len(wavdata) / fs<EOL>if VERBOSE:<EOL><INDENT>amp = rms(wavdata, fs)<EOL>print('<STR_LIT>', amp)<EOL><DEDENT>if len(wavdata) > <NUM_LIT:0> and np.max(abs(wavdata)) != <NUM_LIT:0>:<EOL><INDENT>wavdata = wavdata / np.max(abs(wavdata))<EOL><DEDENT>if window == '<STR_LIT>':<EOL><INDENT>winfnc = mlab.window_hanning<EOL><DEDENT>elif window == '<STR_LIT>':<EOL><INDENT>winfnc = np.hamming(nfft)<EOL><DEDENT>elif window == '<STR_LIT>':<EOL><INDENT>winfnc = np.blackman(nfft)<EOL><DEDENT>elif window == '<STR_LIT>':<EOL><INDENT>winfnc = np.bartlett(nfft)<EOL><DEDENT>elif window == None or window == '<STR_LIT:none>':<EOL><INDENT>winfnc = mlab.window_none<EOL><DEDENT>noverlap = int(nfft * (float(overlap) / <NUM_LIT:100>))<EOL>Pxx, freqs, bins = mlab.specgram(wavdata, NFFT=nfft, Fs=fs, noverlap=noverlap,<EOL>pad_to=nfft * <NUM_LIT:2>, window=winfnc, detrend=mlab.detrend_none,<EOL>sides='<STR_LIT:default>', scale_by_freq=False)<EOL>Pxx[Pxx == <NUM_LIT:0>] = np.nan<EOL>spec = <NUM_LIT> * np.log10(Pxx)<EOL>spec[np.isnan(spec)] = np.nanmin(spec)<EOL>return spec, freqs, bins, duration<EOL>
Produce a matrix of spectral intensity, uses matplotlib's specgram function. Output is in dB scale. :param source: filename of audiofile, or samplerate and vector of audio signal :type source: str or (int, numpy.ndarray) :param nfft: size of nfft window to use :type nfft: int :param overlap: percent overlap of window :type overlap: number :param window: Type of window to use, choices are hanning, hamming, blackman, bartlett or none (rectangular) :type window: string :returns: spec -- 2D array of intensities, freqs -- yaxis labels, bins -- time bin labels, duration -- duration of signal
f10580:m6
def smooth(x, window_len=<NUM_LIT>, window='<STR_LIT>'):
if x.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if x.size < window_len:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if window_len < <NUM_LIT:3>:<EOL><INDENT>return x<EOL><DEDENT>if window_len % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>window_len += <NUM_LIT:1><EOL><DEDENT>if not window in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>s = np.r_[x[window_len - <NUM_LIT:1>:<NUM_LIT:0>:-<NUM_LIT:1>], x, x[-<NUM_LIT:1>:-window_len:-<NUM_LIT:1>]]<EOL>if window == '<STR_LIT>': <EOL><INDENT>w = np.ones(window_len, '<STR_LIT:d>')<EOL><DEDENT>elif window == '<STR_LIT>':<EOL><INDENT>w = np.kaiser(window_len, <NUM_LIT:4>)<EOL><DEDENT>else:<EOL><INDENT>w = eval('<STR_LIT>' + window + '<STR_LIT>')<EOL><DEDENT>y = np.convolve(w / w.sum(), s, mode='<STR_LIT>')<EOL>return y[window_len / <NUM_LIT:2> - <NUM_LIT:1>:len(y) - window_len / <NUM_LIT:2>]<EOL>
smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the begining and end part of the output signal. input: x: the input signal window_len: the dimension of the smoothing window; should be an odd integer output: the smoothed signal example: t=linspace(-2,2,0.1) x=sin(t)+randn(len(t))*0.1 y=smooth(x) see also: numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve scipy.signal.lfilter Based from Scipy Cookbook
f10580:m7
def convolve_filter(signal, impulse_response):
if impulse_response is not None:<EOL><INDENT>adjusted_signal = fftconvolve(signal, impulse_response)<EOL>adjusted_signal = adjusted_signal[<EOL>len(impulse_response) / <NUM_LIT:2>:len(adjusted_signal) - len(impulse_response) / <NUM_LIT:2> + <NUM_LIT:1>]<EOL>return adjusted_signal<EOL><DEDENT>else:<EOL><INDENT>return signal<EOL><DEDENT>
Convovle the two input signals, if impulse_response is None, returns the unaltered signal
f10580:m8
def impulse_response(genrate, fresponse, frequencies, frange, filter_len=<NUM_LIT:2> ** <NUM_LIT>, db=True):
freq = frequencies<EOL>max_freq = genrate / <NUM_LIT:2> + <NUM_LIT:1><EOL>attenuations = np.zeros_like(fresponse)<EOL>winsz = <NUM_LIT> <EOL>lowf = max(<NUM_LIT:0>, frange[<NUM_LIT:0>] - (frange[<NUM_LIT:1>] - frange[<NUM_LIT:0>]) * winsz)<EOL>highf = min(frequencies[-<NUM_LIT:1>], frange[<NUM_LIT:1>] + (frange[<NUM_LIT:1>] - frange[<NUM_LIT:0>]) * winsz)<EOL>f0 = (np.abs(freq - lowf)).argmin()<EOL>f1 = (np.abs(freq - highf)).argmin()<EOL>fmax = (np.abs(freq - max_freq)).argmin() + <NUM_LIT:1><EOL>attenuations[f0:f1] = fresponse[f0:f1] * tukey(len(fresponse[f0:f1]), winsz)<EOL>if db:<EOL><INDENT>freq_response = <NUM_LIT:10> ** ((attenuations).astype(float) / <NUM_LIT:20>)<EOL><DEDENT>else:<EOL><INDENT>freq_response = attenuations<EOL><DEDENT>freq_response = freq_response[:fmax]<EOL>impulse_response = np.fft.irfft(freq_response)<EOL>impulse_response = np.roll(impulse_response, len(impulse_response) // <NUM_LIT:2>)<EOL>if filter_len < len(impulse_response):<EOL><INDENT>startidx = (len(impulse_response) // <NUM_LIT:2>) - (filter_len // <NUM_LIT:2>)<EOL>stopidx = (len(impulse_response) // <NUM_LIT:2>) + (filter_len // <NUM_LIT:2>)<EOL>impulse_response = impulse_response[startidx:stopidx]<EOL><DEDENT>impulse_response = impulse_response * tukey(len(impulse_response), <NUM_LIT>)<EOL>return impulse_response<EOL>
Calculate filter kernel from attenuation vector. Attenuation vector should represent magnitude frequency response of system :param genrate: The generation samplerate at which the test signal was played :type genrate: int :param fresponse: Frequency response of the system in dB, i.e. relative attenuations of frequencies :type fresponse: numpy.ndarray :param frequencies: corresponding frequencies for the fresponse :type frequencies: numpy.ndarray :param frange: the min and max frequencies for which the filter kernel will affect :type frange: (int, int) :param filter_len: the desired length for the resultant impulse response :type filter_len: int :param db: whether the fresponse given is the a vector of multiplication or decibel factors :type db: bool :returns: numpy.ndarray -- the impulse response
f10580:m9
def attenuation_curve(signal, resp, fs, calf, smooth_pts=<NUM_LIT>):
<EOL>y = resp - np.mean(resp)<EOL>x = signal<EOL>npts = len(y)<EOL>fq = np.arange(npts / <NUM_LIT:2> + <NUM_LIT:1>) / (float(npts) / fs)<EOL>Y = np.fft.rfft(y)<EOL>X = np.fft.rfft(x)<EOL>Ymag = np.sqrt(Y.real ** <NUM_LIT:2> + Y.imag ** <NUM_LIT:2>) <EOL>Xmag = np.sqrt(X.real ** <NUM_LIT:2> + X.imag ** <NUM_LIT:2>)<EOL>YmagdB = <NUM_LIT:20> * np.log10(Ymag)<EOL>XmagdB = <NUM_LIT:20> * np.log10(Xmag)<EOL>diffdB = XmagdB - YmagdB<EOL>diffdB = smooth(diffdB, smooth_pts)<EOL>fidx = (np.abs(fq - calf)).argmin()<EOL>diffdB -= diffdB[fidx]<EOL>return diffdB<EOL>
Calculate an attenuation roll-off curve, from a signal and its recording :param signal: ouput signal delivered to the generation hardware :type signal: numpy.ndarray :param resp: recording of given signal, as recieved from microphone :type resp: numpy.ndarray :param fs: input and output samplerate (should be the same) :type fs: int :param smooth_pts: amount of averaging to use on the result :type smooth_pts: int :returns: numpy.ndarray -- attenuation vector
f10580:m10
def calibrate_signal(signal, resp, fs, frange):
<EOL>dc = np.mean(resp)<EOL>resp = resp - dc<EOL>npts = len(signal)<EOL>f0 = np.ceil(frange[<NUM_LIT:0>] / (float(fs) / npts))<EOL>f1 = np.floor(frange[<NUM_LIT:1>] / (float(fs) / npts))<EOL>y = resp<EOL>Y = np.fft.rfft(y)<EOL>x = signal<EOL>X = np.fft.rfft(x)<EOL>H = Y / X<EOL>A = X / H<EOL>return np.fft.irfft(A)<EOL>
Given original signal and recording, spits out a calibrated signal
f10580:m11
def multiply_frequencies(signal, fs, frange, calibration_frequencies, attendB):
npts = len(signal)<EOL>padto = <NUM_LIT:1> << (npts - <NUM_LIT:1>).bit_length()<EOL>X = np.fft.rfft(signal, n=padto)<EOL>npts = padto<EOL>f = np.arange((npts / <NUM_LIT:2>) + <NUM_LIT:1>) / (npts / fs)<EOL>fidx_low = (np.abs(f - frange[<NUM_LIT:0>])).argmin()<EOL>fidx_high = (np.abs(f - frange[<NUM_LIT:1>])).argmin()<EOL>cal_func = interp1d(calibration_frequencies, attendB)<EOL>roi = f[fidx_low:fidx_high]<EOL>Hroi = cal_func(roi)<EOL>H = np.zeros((len(X),))<EOL>H[fidx_low:fidx_high] = Hroi<EOL>H = smooth(H)<EOL>H = <NUM_LIT:10> ** ((H).astype(float) / <NUM_LIT:20>)<EOL>Xadjusted = X * H<EOL>signal_calibrated = np.fft.irfft(Xadjusted)<EOL>return signal_calibrated[:len(signal)]<EOL>
Given a vector of dB attenuations, adjust signal by multiplication in the frequency domain
f10580:m12
def tukey(winlen, alpha):
taper = hann(winlen * alpha)<EOL>rect = np.ones(winlen - len(taper) + <NUM_LIT:1>)<EOL>win = fftconvolve(taper, rect)<EOL>win = win / np.amax(win)<EOL>return win<EOL>
Generate a tukey (tapered cosine) window :param winlen: length of the window, in samples :type winlen: int :param alpha: proportion of the window to be tapered. 0 = rectangular window 1.0 = hann window :type alpha: float
f10580:m13
def audioread(filename):
try:<EOL><INDENT>if '<STR_LIT>' in filename.lower():<EOL><INDENT>fs, signal = wv.read(filename)<EOL><DEDENT>elif '<STR_LIT>' in filename.lower():<EOL><INDENT>with open(filename, '<STR_LIT:rb>') as f:<EOL><INDENT>signal = np.fromfile(f, dtype=np.int16)<EOL><DEDENT>fs = <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>raise IOError("<STR_LIT>".format(filename))<EOL><DEDENT><DEDENT>except:<EOL><INDENT>print("<STR_LIT>")<EOL>raise<EOL><DEDENT>signal = signal.astype(float)<EOL>return fs, signal<EOL>
Reads an audio signal from file. Supported formats : wav :param filename: filename of the audiofile to load :type filename: str :returns: int, numpy.ndarray -- samplerate, array containing the audio signal
f10580:m14
def audiorate(filename):
if '<STR_LIT>' in filename.lower():<EOL><INDENT>wf = wave.open(filename)<EOL>fs = wf.getframerate()<EOL>wf.close()<EOL><DEDENT>elif '<STR_LIT>' in filename.lower():<EOL><INDENT>fs = <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>raise IOError("<STR_LIT>".format(filename))<EOL><DEDENT>return fs<EOL>
Determines the samplerate of the given audio recording file :param filename: filename of the audiofile :type filename: str :returns: int -- samplerate of the recording
f10580:m15
def rms(signal, fs):
<EOL>chunk_time = <NUM_LIT> <EOL>chunk_samps = int(chunk_time * fs)<EOL>amps = []<EOL>if chunk_samps > <NUM_LIT:10>:<EOL><INDENT>for i in range(<NUM_LIT:0>, len(signal) - chunk_samps, chunk_samps):<EOL><INDENT>amps.append(np.sqrt(np.mean(pow(signal[i:i + chunk_samps], <NUM_LIT:2>))))<EOL><DEDENT>amps.append(np.sqrt(np.mean(pow(signal[len(signal) - chunk_samps:], <NUM_LIT:2>))))<EOL>return np.amax(amps)<EOL><DEDENT>else:<EOL><INDENT>return np.sqrt(np.mean(pow(signal, <NUM_LIT:2>)))<EOL><DEDENT>
Returns the root mean square (RMS) of the given *signal* :param signal: a vector of electric potential :type signal: numpy.ndarray :param fs: samplerate of the signal (Hz) :type fs: int :returns: float -- the RMS value of the signal
f10580:m16
def get_free_mb(folder):
if platform.system() == '<STR_LIT>':<EOL><INDENT>free_bytes = ctypes.c_ulonglong(<NUM_LIT:0>)<EOL>ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))<EOL>return free_bytes.value/<NUM_LIT>/<NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>st = os.statvfs(folder)<EOL>return st.f_bavail * st.f_frsize/<NUM_LIT>/<NUM_LIT><EOL><DEDENT>
Return folder/drive free space (in bytes)
f10581:m3
def get_ao_chans(dev):
buf = create_string_buffer(<NUM_LIT>)<EOL>buflen = c_uint32(sizeof(buf))<EOL>DAQmxGetDevAOPhysicalChans(dev.encode(), buf, buflen)<EOL>pybuf = buf.value<EOL>chans = pybuf.decode(u'<STR_LIT:utf-8>').split(u"<STR_LIT:U+002C>")<EOL>return chans<EOL>
Discover and return a list of the names of all analog output channels for the given device :param dev: the device name :type dev: str
f10583:m0
def get_ai_chans(dev):
buf = create_string_buffer(<NUM_LIT>)<EOL>buflen = c_uint32(sizeof(buf))<EOL>DAQmxGetDevAIPhysicalChans(dev.encode(), buf, buflen)<EOL>pybuf = buf.value<EOL>chans = pybuf.decode(u'<STR_LIT:utf-8>').split(u"<STR_LIT:U+002CU+0020>")<EOL>return chans<EOL>
Discover and return a list of the names of all analog input channels for the given device :param dev: the device name :type dev: str
f10583:m1
def get_devices():
buf = create_string_buffer(<NUM_LIT>)<EOL>buflen = c_uint32(sizeof(buf))<EOL>DAQmxGetSysDevNames(buf, buflen)<EOL>pybuf = buf.value<EOL>devices = pybuf.decode(u'<STR_LIT:utf-8>').split(u"<STR_LIT:U+002C>")<EOL>return devices<EOL>
Discover and return a list of the names of all NI devices on this system
f10583:m2
def start(self):
self.StartTask()<EOL>
Begins acquistition
f10583:c0:m1
def register_callback(self, fun, npts):
self.callback_fun = fun<EOL>self.n = npts<EOL>self.AutoRegisterEveryNSamplesEvent(DAQmx_Val_Acquired_Into_Buffer,<EOL>npts, <NUM_LIT:0>, name=u"<STR_LIT>")<EOL>
Provide a function to be executed periodically on data collection, every time after the specified number of points are collected. :param fun: the function that gets called, it must have a single positional argument that will be the data buffer read :type fun: function :param npts: The number of data points collected before the function is called. :type npts: int
f10583:c0:m2
def stop(self):
try:<EOL><INDENT>self.StopTask()<EOL>self.ClearTask()<EOL><DEDENT>except DAQError:<EOL><INDENT>pass<EOL><DEDENT>
Halts the acquisition
f10583:c0:m5
def start(self):
self.StartTask()<EOL>
Begins generation -- immediately if not using a trigger
f10583:c1:m1
def write(self, output):
w = c_int32()<EOL>self.WriteAnalogF64(self.bufsize, <NUM_LIT:0>, <NUM_LIT>, DAQmx_Val_GroupByChannel,<EOL>output, w, None)<EOL>
Writes the data to be output to the device buffer, output will be looped when the data runs out :param output: data to output :type output: numpy.ndarray
f10583:c1:m2
def stop(self):
self.StopTask()<EOL>self.ClearTask()<EOL>
Halts the Generation
f10583:c1:m3
def start(self):
self.StartTask()<EOL>
Begins acquistition -- immediately if not using a trigger
f10583:c2:m1
def read(self):
r = c_int32()<EOL>bufsize = self.npts*self.nchans<EOL>inbuffer = np.zeros(bufsize)<EOL>self.ReadAnalogF64(self.npts, <NUM_LIT>, DAQmx_Val_GroupByChannel, inbuffer,<EOL>bufsize, byref(r), None)<EOL>self.WaitUntilTaskDone(<NUM_LIT>)<EOL>return inbuffer.reshape(self.nchans, self.npts)<EOL>
Reads the data off of the device input buffer. Blocks for acquisition to finish with a timeout of 10 seconds :returns: numpy.ndarray -- the acquired data
f10583:c2:m2
def stop(self):
<EOL>try:<EOL><INDENT>self.StopTask()<EOL>self.ClearTask()<EOL><DEDENT>except DAQError:<EOL><INDENT>pass<EOL><DEDENT>
Halts the acquisition
f10583:c2:m3