input
stringlengths
53
297k
output
stringclasses
604 values
repo_name
stringclasses
376 values
test_path
stringclasses
583 values
code_path
stringlengths
7
116
"""Support for Genius Hub switch/outlet devices.""" from homeassistant.components.switch import DEVICE_CLASS_OUTLET, SwitchEntity from homeassistant.helpers.typing import ConfigType, HomeAssistantType from . import DOMAIN, GeniusZone ATTR_DURATION = "duration" GH_ON_OFF_ZONE = "on / off" async def async_setup_platform( hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None ) -> None: """Set up the Genius Hub switch entities.""" if discovery_info is None: return broker = hass.data[DOMAIN]["broker"] async_add_entities( [ GeniusSwitch(broker, z) for z in broker.client.zone_objs if z.data["type"] == GH_ON_OFF_ZONE ] ) class GeniusSwitch(GeniusZone, SwitchEntity): """Representation of a Genius Hub switch.""" @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return DEVICE_CLASS_OUTLET @property def is_on(self) -> bool: """Return the current state of the on/off zone. The zone is considered 'on' if & only if it is override/on (e.g. timer/on is 'off'). """ return self._zone.data["mode"] == "override" and self._zone.data["setpoint"] async def async_turn_off(self, **kwargs) -> None: """Send the zone to Timer mode. The zone is deemed 'off' in this mode, although the plugs may actually be on. """ await self._zone.set_mode("timer") async def async_turn_on(self, **kwargs) -> None: """Set the zone to override/on ({'setpoint': true}) for x seconds.""" await self._zone.set_override(1, kwargs.get(ATTR_DURATION, 3600))
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/geniushub/switch.py
"""Provide configuration end points for Groups.""" from homeassistant.components.group import DOMAIN, GROUP_SCHEMA from homeassistant.config import GROUP_CONFIG_PATH from homeassistant.const import SERVICE_RELOAD import homeassistant.helpers.config_validation as cv from . import EditKeyBasedConfigView async def async_setup(hass): """Set up the Group config API.""" async def hook(action, config_key): """post_write_hook for Config View that reloads groups.""" await hass.services.async_call(DOMAIN, SERVICE_RELOAD) hass.http.register_view( EditKeyBasedConfigView( "group", "config", GROUP_CONFIG_PATH, cv.slug, GROUP_SCHEMA, post_write_hook=hook, ) ) return True
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/config/group.py
"""Support for LCN climate control.""" import pypck from homeassistant.components.climate import ClimateEntity, const from homeassistant.const import ATTR_TEMPERATURE, CONF_ADDRESS, CONF_UNIT_OF_MEASUREMENT from . import LcnDevice from .const import ( CONF_CONNECTIONS, CONF_LOCKABLE, CONF_MAX_TEMP, CONF_MIN_TEMP, CONF_SETPOINT, CONF_SOURCE, DATA_LCN, ) from .helpers import get_connection async def async_setup_platform( hass, hass_config, async_add_entities, discovery_info=None ): """Set up the LCN climate platform.""" if discovery_info is None: return devices = [] for config in discovery_info: address, connection_id = config[CONF_ADDRESS] addr = pypck.lcn_addr.LcnAddr(*address) connections = hass.data[DATA_LCN][CONF_CONNECTIONS] connection = get_connection(connections, connection_id) address_connection = connection.get_address_conn(addr) devices.append(LcnClimate(config, address_connection)) async_add_entities(devices) class LcnClimate(LcnDevice, ClimateEntity): """Representation of a LCN climate device.""" def __init__(self, config, address_connection): """Initialize of a LCN climate device.""" super().__init__(config, address_connection) self.variable = pypck.lcn_defs.Var[config[CONF_SOURCE]] self.setpoint = pypck.lcn_defs.Var[config[CONF_SETPOINT]] self.unit = pypck.lcn_defs.VarUnit.parse(config[CONF_UNIT_OF_MEASUREMENT]) self.regulator_id = pypck.lcn_defs.Var.to_set_point_id(self.setpoint) self.is_lockable = config[CONF_LOCKABLE] self._max_temp = config[CONF_MAX_TEMP] self._min_temp = config[CONF_MIN_TEMP] self._current_temperature = None self._target_temperature = None self._is_on = None async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() await self.address_connection.activate_status_request_handler(self.variable) await self.address_connection.activate_status_request_handler(self.setpoint) @property def supported_features(self): """Return the list of supported features.""" return const.SUPPORT_TARGET_TEMPERATURE @property def temperature_unit(self): """Return the unit of measurement.""" return self.unit.value @property def current_temperature(self): """Return the current temperature.""" return self._current_temperature @property def target_temperature(self): """Return the temperature we try to reach.""" return self._target_temperature @property def hvac_mode(self): """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ if self._is_on: return const.HVAC_MODE_HEAT return const.HVAC_MODE_OFF @property def hvac_modes(self): """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ modes = [const.HVAC_MODE_HEAT] if self.is_lockable: modes.append(const.HVAC_MODE_OFF) return modes @property def max_temp(self): """Return the maximum temperature.""" return self._max_temp @property def min_temp(self): """Return the minimum temperature.""" return self._min_temp async def async_set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" if hvac_mode == const.HVAC_MODE_HEAT: self._is_on = True self.address_connection.lock_regulator(self.regulator_id, False) elif hvac_mode == const.HVAC_MODE_OFF: self._is_on = False self.address_connection.lock_regulator(self.regulator_id, True) self._target_temperature = None self.async_write_ha_state() async def async_set_temperature(self, **kwargs): """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature is None: return self._target_temperature = temperature self.address_connection.var_abs( self.setpoint, self._target_temperature, self.unit ) self.async_write_ha_state() def input_received(self, input_obj): """Set temperature value when LCN input object is received.""" if not isinstance(input_obj, pypck.inputs.ModStatusVar): return if input_obj.get_var() == self.variable: self._current_temperature = input_obj.get_value().to_var_unit(self.unit) elif input_obj.get_var() == self.setpoint: self._is_on = not input_obj.get_value().is_locked_regulator() if self._is_on: self._target_temperature = input_obj.get_value().to_var_unit(self.unit) self.async_write_ha_state()
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/lcn/climate.py
"""Support for HomeMatic binary sensors.""" import logging from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_MOTION, DEVICE_CLASS_OPENING, DEVICE_CLASS_PRESENCE, DEVICE_CLASS_SMOKE, BinarySensorEntity, ) from .const import ATTR_DISCOVER_DEVICES, ATTR_DISCOVERY_TYPE, DISCOVER_BATTERY from .entity import HMDevice _LOGGER = logging.getLogger(__name__) SENSOR_TYPES_CLASS = { "IPShutterContact": DEVICE_CLASS_OPENING, "IPShutterContactSabotage": DEVICE_CLASS_OPENING, "MaxShutterContact": DEVICE_CLASS_OPENING, "Motion": DEVICE_CLASS_MOTION, "MotionV2": DEVICE_CLASS_MOTION, "PresenceIP": DEVICE_CLASS_PRESENCE, "Remote": None, "RemoteMotion": None, "ShutterContact": DEVICE_CLASS_OPENING, "Smoke": DEVICE_CLASS_SMOKE, "SmokeV2": DEVICE_CLASS_SMOKE, "TiltSensor": None, "WeatherSensor": None, "IPContact": DEVICE_CLASS_OPENING, "MotionIPV2": DEVICE_CLASS_MOTION, "IPRemoteMotionV2": DEVICE_CLASS_MOTION, } def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the HomeMatic binary sensor platform.""" if discovery_info is None: return devices = [] for conf in discovery_info[ATTR_DISCOVER_DEVICES]: if discovery_info[ATTR_DISCOVERY_TYPE] == DISCOVER_BATTERY: devices.append(HMBatterySensor(conf)) else: devices.append(HMBinarySensor(conf)) add_entities(devices, True) class HMBinarySensor(HMDevice, BinarySensorEntity): """Representation of a binary HomeMatic device.""" @property def is_on(self): """Return true if switch is on.""" if not self.available: return False return bool(self._hm_get_state()) @property def device_class(self): """Return the class of this sensor from DEVICE_CLASSES.""" # If state is MOTION (Only RemoteMotion working) if self._state == "MOTION": return DEVICE_CLASS_MOTION return SENSOR_TYPES_CLASS.get(self._hmdevice.__class__.__name__) def _init_data_struct(self): """Generate the data dictionary (self._data) from metadata.""" # Add state to data struct if self._state: self._data.update({self._state: None}) class HMBatterySensor(HMDevice, BinarySensorEntity): """Representation of an HomeMatic low battery sensor.""" @property def device_class(self): """Return battery as a device class.""" return DEVICE_CLASS_BATTERY @property def is_on(self): """Return True if battery is low.""" return bool(self._hm_get_state()) def _init_data_struct(self): """Generate the data dictionary (self._data) from metadata.""" # Add state to data struct if self._state: self._data.update({self._state: None})
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/homematic/binary_sensor.py
"""Support for an Intergas heater via an InComfort/InTouch Lan2RF gateway.""" from typing import Any, Dict, Optional from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.const import ( DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, PRESSURE_BAR, TEMP_CELSIUS, ) from homeassistant.util import slugify from . import DOMAIN, IncomfortChild INCOMFORT_HEATER_TEMP = "CV Temp" INCOMFORT_PRESSURE = "CV Pressure" INCOMFORT_TAP_TEMP = "Tap Temp" INCOMFORT_MAP_ATTRS = { INCOMFORT_HEATER_TEMP: ["heater_temp", "is_pumping"], INCOMFORT_PRESSURE: ["pressure", None], INCOMFORT_TAP_TEMP: ["tap_temp", "is_tapping"], } async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up an InComfort/InTouch sensor device.""" if discovery_info is None: return client = hass.data[DOMAIN]["client"] heaters = hass.data[DOMAIN]["heaters"] async_add_entities( [IncomfortPressure(client, h, INCOMFORT_PRESSURE) for h in heaters] + [IncomfortTemperature(client, h, INCOMFORT_HEATER_TEMP) for h in heaters] + [IncomfortTemperature(client, h, INCOMFORT_TAP_TEMP) for h in heaters] ) class IncomfortSensor(IncomfortChild): """Representation of an InComfort/InTouch sensor device.""" def __init__(self, client, heater, name) -> None: """Initialize the sensor.""" super().__init__() self._client = client self._heater = heater self._unique_id = f"{heater.serial_no}_{slugify(name)}" self.entity_id = f"{SENSOR_DOMAIN}.{DOMAIN}_{slugify(name)}" self._name = f"Boiler {name}" self._device_class = None self._state_attr = INCOMFORT_MAP_ATTRS[name][0] self._unit_of_measurement = None @property def state(self) -> Optional[str]: """Return the state of the sensor.""" return self._heater.status[self._state_attr] @property def device_class(self) -> Optional[str]: """Return the device class of the sensor.""" return self._device_class @property def unit_of_measurement(self) -> Optional[str]: """Return the unit of measurement of the sensor.""" return self._unit_of_measurement class IncomfortPressure(IncomfortSensor): """Representation of an InTouch CV Pressure sensor.""" def __init__(self, client, heater, name) -> None: """Initialize the sensor.""" super().__init__(client, heater, name) self._device_class = DEVICE_CLASS_PRESSURE self._unit_of_measurement = PRESSURE_BAR class IncomfortTemperature(IncomfortSensor): """Representation of an InTouch Temperature sensor.""" def __init__(self, client, heater, name) -> None: """Initialize the signal strength sensor.""" super().__init__(client, heater, name) self._attr = INCOMFORT_MAP_ATTRS[name][1] self._device_class = DEVICE_CLASS_TEMPERATURE self._unit_of_measurement = TEMP_CELSIUS @property def device_state_attributes(self) -> Optional[Dict[str, Any]]: """Return the device state attributes.""" return {self._attr: self._heater.status[self._attr]}
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/incomfort/sensor.py
"""Support for Satel Integra devices.""" import collections import logging from satel_integra.satel_integra import AsyncSatel import voluptuous as vol from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP from homeassistant.core import callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.discovery import async_load_platform from homeassistant.helpers.dispatcher import async_dispatcher_send DEFAULT_ALARM_NAME = "satel_integra" DEFAULT_PORT = 7094 DEFAULT_CONF_ARM_HOME_MODE = 1 DEFAULT_DEVICE_PARTITION = 1 DEFAULT_ZONE_TYPE = "motion" _LOGGER = logging.getLogger(__name__) DOMAIN = "satel_integra" DATA_SATEL = "satel_integra" CONF_DEVICE_CODE = "code" CONF_DEVICE_PARTITIONS = "partitions" CONF_ARM_HOME_MODE = "arm_home_mode" CONF_ZONE_NAME = "name" CONF_ZONE_TYPE = "type" CONF_ZONES = "zones" CONF_OUTPUTS = "outputs" CONF_SWITCHABLE_OUTPUTS = "switchable_outputs" ZONES = "zones" SIGNAL_PANEL_MESSAGE = "satel_integra.panel_message" SIGNAL_PANEL_ARM_AWAY = "satel_integra.panel_arm_away" SIGNAL_PANEL_ARM_HOME = "satel_integra.panel_arm_home" SIGNAL_PANEL_DISARM = "satel_integra.panel_disarm" SIGNAL_ZONES_UPDATED = "satel_integra.zones_updated" SIGNAL_OUTPUTS_UPDATED = "satel_integra.outputs_updated" ZONE_SCHEMA = vol.Schema( { vol.Required(CONF_ZONE_NAME): cv.string, vol.Optional(CONF_ZONE_TYPE, default=DEFAULT_ZONE_TYPE): cv.string, } ) EDITABLE_OUTPUT_SCHEMA = vol.Schema({vol.Required(CONF_ZONE_NAME): cv.string}) PARTITION_SCHEMA = vol.Schema( { vol.Required(CONF_ZONE_NAME): cv.string, vol.Optional(CONF_ARM_HOME_MODE, default=DEFAULT_CONF_ARM_HOME_MODE): vol.In( [1, 2, 3] ), } ) def is_alarm_code_necessary(value): """Check if alarm code must be configured.""" if value.get(CONF_SWITCHABLE_OUTPUTS) and CONF_DEVICE_CODE not in value: raise vol.Invalid("You need to specify alarm code to use switchable_outputs") return value CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.All( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_DEVICE_CODE): cv.string, vol.Optional(CONF_DEVICE_PARTITIONS, default={}): { vol.Coerce(int): PARTITION_SCHEMA }, vol.Optional(CONF_ZONES, default={}): {vol.Coerce(int): ZONE_SCHEMA}, vol.Optional(CONF_OUTPUTS, default={}): {vol.Coerce(int): ZONE_SCHEMA}, vol.Optional(CONF_SWITCHABLE_OUTPUTS, default={}): { vol.Coerce(int): EDITABLE_OUTPUT_SCHEMA }, }, is_alarm_code_necessary, ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Set up the Satel Integra component.""" conf = config.get(DOMAIN) zones = conf.get(CONF_ZONES) outputs = conf.get(CONF_OUTPUTS) switchable_outputs = conf.get(CONF_SWITCHABLE_OUTPUTS) host = conf.get(CONF_HOST) port = conf.get(CONF_PORT) partitions = conf.get(CONF_DEVICE_PARTITIONS) monitored_outputs = collections.OrderedDict( list(outputs.items()) + list(switchable_outputs.items()) ) controller = AsyncSatel(host, port, hass.loop, zones, monitored_outputs, partitions) hass.data[DATA_SATEL] = controller result = await controller.connect() if not result: return False async def _close(): controller.close() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _close()) _LOGGER.debug("Arm home config: %s, mode: %s ", conf, conf.get(CONF_ARM_HOME_MODE)) hass.async_create_task( async_load_platform(hass, "alarm_control_panel", DOMAIN, conf, config) ) hass.async_create_task( async_load_platform( hass, "binary_sensor", DOMAIN, {CONF_ZONES: zones, CONF_OUTPUTS: outputs}, config, ) ) hass.async_create_task( async_load_platform( hass, "switch", DOMAIN, { CONF_SWITCHABLE_OUTPUTS: switchable_outputs, CONF_DEVICE_CODE: conf.get(CONF_DEVICE_CODE), }, config, ) ) @callback def alarm_status_update_callback(): """Send status update received from alarm to Home Assistant.""" _LOGGER.debug("Sending request to update panel state") async_dispatcher_send(hass, SIGNAL_PANEL_MESSAGE) @callback def zones_update_callback(status): """Update zone objects as per notification from the alarm.""" _LOGGER.debug("Zones callback, status: %s", status) async_dispatcher_send(hass, SIGNAL_ZONES_UPDATED, status[ZONES]) @callback def outputs_update_callback(status): """Update zone objects as per notification from the alarm.""" _LOGGER.debug("Outputs updated callback , status: %s", status) async_dispatcher_send(hass, SIGNAL_OUTPUTS_UPDATED, status["outputs"]) # Create a task instead of adding a tracking job, since this task will # run until the connection to satel_integra is closed. hass.loop.create_task(controller.keep_alive()) hass.loop.create_task( controller.monitor_status( alarm_status_update_callback, zones_update_callback, outputs_update_callback ) ) return True
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/satel_integra/__init__.py
"""Support for controlling projector via the PJLink protocol.""" import logging from pypjlink import MUTE_AUDIO, Projector from pypjlink.projector import ProjectorError import voluptuous as vol from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerEntity from homeassistant.components.media_player.const import ( SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, ) from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, STATE_OFF, STATE_ON, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_ENCODING = "encoding" DEFAULT_PORT = 4352 DEFAULT_ENCODING = "utf-8" DEFAULT_TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_ENCODING, default=DEFAULT_ENCODING): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) SUPPORT_PJLINK = ( SUPPORT_VOLUME_MUTE | SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_SELECT_SOURCE ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the PJLink platform.""" host = config.get(CONF_HOST) port = config.get(CONF_PORT) name = config.get(CONF_NAME) encoding = config.get(CONF_ENCODING) password = config.get(CONF_PASSWORD) if "pjlink" not in hass.data: hass.data["pjlink"] = {} hass_data = hass.data["pjlink"] device_label = f"{host}:{port}" if device_label in hass_data: return device = PjLinkDevice(host, port, name, encoding, password) hass_data[device_label] = device add_entities([device], True) def format_input_source(input_source_name, input_source_number): """Format input source for display in UI.""" return f"{input_source_name} {input_source_number}" class PjLinkDevice(MediaPlayerEntity): """Representation of a PJLink device.""" def __init__(self, host, port, name, encoding, password): """Iinitialize the PJLink device.""" self._host = host self._port = port self._name = name self._password = password self._encoding = encoding self._muted = False self._pwstate = STATE_OFF self._current_source = None with self.projector() as projector: if not self._name: self._name = projector.get_name() inputs = projector.get_inputs() self._source_name_mapping = {format_input_source(*x): x for x in inputs} self._source_list = sorted(self._source_name_mapping.keys()) def projector(self): """Create PJLink Projector instance.""" projector = Projector.from_address( self._host, self._port, self._encoding, DEFAULT_TIMEOUT ) projector.authenticate(self._password) return projector def update(self): """Get the latest state from the device.""" with self.projector() as projector: try: pwstate = projector.get_power() if pwstate in ("on", "warm-up"): self._pwstate = STATE_ON self._muted = projector.get_mute()[1] self._current_source = format_input_source(*projector.get_input()) else: self._pwstate = STATE_OFF self._muted = False self._current_source = None except KeyError as err: if str(err) == "'OK'": self._pwstate = STATE_OFF self._muted = False self._current_source = None else: raise except ProjectorError as err: if str(err) == "unavailable time": self._pwstate = STATE_OFF self._muted = False self._current_source = None else: raise @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the state of the device.""" return self._pwstate @property def is_volume_muted(self): """Return boolean indicating mute status.""" return self._muted @property def source(self): """Return current input source.""" return self._current_source @property def source_list(self): """Return all available input sources.""" return self._source_list @property def supported_features(self): """Return projector supported features.""" return SUPPORT_PJLINK def turn_off(self): """Turn projector off.""" if self._pwstate == STATE_ON: with self.projector() as projector: projector.set_power("off") def turn_on(self): """Turn projector on.""" if self._pwstate == STATE_OFF: with self.projector() as projector: projector.set_power("on") def mute_volume(self, mute): """Mute (true) of unmute (false) media player.""" with self.projector() as projector: projector.set_mute(MUTE_AUDIO, mute) def select_source(self, source): """Set the input source.""" source = self._source_name_mapping[source] with self.projector() as projector: projector.set_input(*source)
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/pjlink/media_player.py
"""Support for ADS covers.""" import logging import voluptuous as vol from homeassistant.components.cover import ( ATTR_POSITION, DEVICE_CLASSES_SCHEMA, PLATFORM_SCHEMA, SUPPORT_CLOSE, SUPPORT_OPEN, SUPPORT_SET_POSITION, SUPPORT_STOP, CoverEntity, ) from homeassistant.const import CONF_DEVICE_CLASS, CONF_NAME import homeassistant.helpers.config_validation as cv from . import ( CONF_ADS_VAR, CONF_ADS_VAR_POSITION, DATA_ADS, STATE_KEY_POSITION, STATE_KEY_STATE, AdsEntity, ) _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "ADS Cover" CONF_ADS_VAR_SET_POS = "adsvar_set_position" CONF_ADS_VAR_OPEN = "adsvar_open" CONF_ADS_VAR_CLOSE = "adsvar_close" CONF_ADS_VAR_STOP = "adsvar_stop" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_ADS_VAR): cv.string, vol.Optional(CONF_ADS_VAR_POSITION): cv.string, vol.Optional(CONF_ADS_VAR_SET_POS): cv.string, vol.Optional(CONF_ADS_VAR_CLOSE): cv.string, vol.Optional(CONF_ADS_VAR_OPEN): cv.string, vol.Optional(CONF_ADS_VAR_STOP): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the cover platform for ADS.""" ads_hub = hass.data[DATA_ADS] ads_var_is_closed = config.get(CONF_ADS_VAR) ads_var_position = config.get(CONF_ADS_VAR_POSITION) ads_var_pos_set = config.get(CONF_ADS_VAR_SET_POS) ads_var_open = config.get(CONF_ADS_VAR_OPEN) ads_var_close = config.get(CONF_ADS_VAR_CLOSE) ads_var_stop = config.get(CONF_ADS_VAR_STOP) name = config[CONF_NAME] device_class = config.get(CONF_DEVICE_CLASS) add_entities( [ AdsCover( ads_hub, ads_var_is_closed, ads_var_position, ads_var_pos_set, ads_var_open, ads_var_close, ads_var_stop, name, device_class, ) ] ) class AdsCover(AdsEntity, CoverEntity): """Representation of ADS cover.""" def __init__( self, ads_hub, ads_var_is_closed, ads_var_position, ads_var_pos_set, ads_var_open, ads_var_close, ads_var_stop, name, device_class, ): """Initialize AdsCover entity.""" super().__init__(ads_hub, name, ads_var_is_closed) if self._ads_var is None: if ads_var_position is not None: self._unique_id = ads_var_position elif ads_var_pos_set is not None: self._unique_id = ads_var_pos_set elif ads_var_open is not None: self._unique_id = ads_var_open self._state_dict[STATE_KEY_POSITION] = None self._ads_var_position = ads_var_position self._ads_var_pos_set = ads_var_pos_set self._ads_var_open = ads_var_open self._ads_var_close = ads_var_close self._ads_var_stop = ads_var_stop self._device_class = device_class async def async_added_to_hass(self): """Register device notification.""" if self._ads_var is not None: await self.async_initialize_device( self._ads_var, self._ads_hub.PLCTYPE_BOOL ) if self._ads_var_position is not None: await self.async_initialize_device( self._ads_var_position, self._ads_hub.PLCTYPE_BYTE, STATE_KEY_POSITION ) @property def device_class(self): """Return the class of this cover.""" return self._device_class @property def is_closed(self): """Return if the cover is closed.""" if self._ads_var is not None: return self._state_dict[STATE_KEY_STATE] if self._ads_var_position is not None: return self._state_dict[STATE_KEY_POSITION] == 0 return None @property def current_cover_position(self): """Return current position of cover.""" return self._state_dict[STATE_KEY_POSITION] @property def supported_features(self): """Flag supported features.""" supported_features = SUPPORT_OPEN | SUPPORT_CLOSE if self._ads_var_stop is not None: supported_features |= SUPPORT_STOP if self._ads_var_pos_set is not None: supported_features |= SUPPORT_SET_POSITION return supported_features def stop_cover(self, **kwargs): """Fire the stop action.""" if self._ads_var_stop: self._ads_hub.write_by_name( self._ads_var_stop, True, self._ads_hub.PLCTYPE_BOOL ) def set_cover_position(self, **kwargs): """Set cover position.""" position = kwargs[ATTR_POSITION] if self._ads_var_pos_set is not None: self._ads_hub.write_by_name( self._ads_var_pos_set, position, self._ads_hub.PLCTYPE_BYTE ) def open_cover(self, **kwargs): """Move the cover up.""" if self._ads_var_open is not None: self._ads_hub.write_by_name( self._ads_var_open, True, self._ads_hub.PLCTYPE_BOOL ) elif self._ads_var_pos_set is not None: self.set_cover_position(position=100) def close_cover(self, **kwargs): """Move the cover down.""" if self._ads_var_close is not None: self._ads_hub.write_by_name( self._ads_var_close, True, self._ads_hub.PLCTYPE_BOOL ) elif self._ads_var_pos_set is not None: self.set_cover_position(position=0) @property def available(self): """Return False if state has not been updated yet.""" if self._ads_var is not None or self._ads_var_position is not None: return ( self._state_dict[STATE_KEY_STATE] is not None or self._state_dict[STATE_KEY_POSITION] is not None ) return True
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/ads/cover.py
"""Support for ESPHome switches.""" import logging from typing import Optional from aioesphomeapi import SwitchInfo, SwitchState from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.typing import HomeAssistantType from . import EsphomeEntity, esphome_state_property, platform_async_setup_entry _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up ESPHome switches based on a config entry.""" await platform_async_setup_entry( hass, entry, async_add_entities, component_key="switch", info_type=SwitchInfo, entity_type=EsphomeSwitch, state_type=SwitchState, ) class EsphomeSwitch(EsphomeEntity, SwitchEntity): """A switch implementation for ESPHome.""" @property def _static_info(self) -> SwitchInfo: return super()._static_info @property def _state(self) -> Optional[SwitchState]: return super()._state @property def icon(self) -> str: """Return the icon.""" return self._static_info.icon @property def assumed_state(self) -> bool: """Return true if we do optimistic updates.""" return self._static_info.assumed_state # https://github.com/PyCQA/pylint/issues/3150 for @esphome_state_property # pylint: disable=invalid-overridden-method @esphome_state_property def is_on(self) -> Optional[bool]: """Return true if the switch is on.""" return self._state.state async def async_turn_on(self, **kwargs) -> None: """Turn the entity on.""" await self._client.switch_command(self._static_info.key, True) async def async_turn_off(self, **kwargs) -> None: """Turn the entity off.""" await self._client.switch_command(self._static_info.key, False)
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/esphome/switch.py
"""Support for IOTA wallets.""" from datetime import timedelta import logging from iota import Iota import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.helpers.discovery import load_platform from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) CONF_IRI = "iri" CONF_TESTNET = "testnet" CONF_WALLET_NAME = "name" CONF_WALLET_SEED = "seed" CONF_WALLETS = "wallets" DOMAIN = "iota" IOTA_PLATFORMS = ["sensor"] SCAN_INTERVAL = timedelta(minutes=10) WALLET_CONFIG = vol.Schema( { vol.Required(CONF_WALLET_NAME): cv.string, vol.Required(CONF_WALLET_SEED): cv.string, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_IRI): cv.string, vol.Optional(CONF_TESTNET, default=False): cv.boolean, vol.Required(CONF_WALLETS): vol.All(cv.ensure_list, [WALLET_CONFIG]), } ) }, extra=vol.ALLOW_EXTRA, ) def setup(hass, config): """Set up the IOTA component.""" iota_config = config[DOMAIN] for platform in IOTA_PLATFORMS: load_platform(hass, platform, DOMAIN, iota_config, config) return True class IotaDevice(Entity): """Representation of a IOTA device.""" def __init__(self, name, seed, iri, is_testnet=False): """Initialise the IOTA device.""" self._name = name self._seed = seed self.iri = iri self.is_testnet = is_testnet @property def name(self): """Return the default name of the device.""" return self._name @property def device_state_attributes(self): """Return the state attributes of the device.""" attr = {CONF_WALLET_NAME: self._name} return attr @property def api(self): """Construct API object for interaction with the IRI node.""" return Iota(adapter=self.iri, seed=self._seed)
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/iota/__init__.py
"""Provides device automations for Fan.""" from typing import List import voluptuous as vol from homeassistant.components.automation import AutomationActionType from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.homeassistant.triggers import state as state_trigger from homeassistant.const import ( CONF_DEVICE_ID, CONF_DOMAIN, CONF_ENTITY_ID, CONF_PLATFORM, CONF_TYPE, STATE_OFF, STATE_ON, ) from homeassistant.core import CALLBACK_TYPE, HomeAssistant from homeassistant.helpers import config_validation as cv, entity_registry from homeassistant.helpers.typing import ConfigType from . import DOMAIN TRIGGER_TYPES = {"turned_on", "turned_off"} TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES), } ) async def async_get_triggers(hass: HomeAssistant, device_id: str) -> List[dict]: """List device triggers for Fan devices.""" registry = await entity_registry.async_get_registry(hass) triggers = [] # Get all the integrations entities for this device for entry in entity_registry.async_entries_for_device(registry, device_id): if entry.domain != DOMAIN: continue # Add triggers for each entity that belongs to this integration triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "turned_on", } ) triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "turned_off", } ) return triggers async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Attach a trigger.""" config = TRIGGER_SCHEMA(config) if config[CONF_TYPE] == "turned_on": from_state = STATE_OFF to_state = STATE_ON else: from_state = STATE_ON to_state = STATE_OFF state_config = { state_trigger.CONF_PLATFORM: "state", CONF_ENTITY_ID: config[CONF_ENTITY_ID], state_trigger.CONF_FROM: from_state, state_trigger.CONF_TO: to_state, } state_config = state_trigger.TRIGGER_SCHEMA(state_config) return await state_trigger.async_attach_trigger( hass, state_config, action, automation_info, platform_type="device" )
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/fan/device_trigger.py
import itertools import numpy as np import pytest import pandas as pd from pandas.core.internals import ExtensionBlock from .base import BaseExtensionTests class BaseReshapingTests(BaseExtensionTests): """Tests for reshaping and concatenation.""" @pytest.mark.parametrize('in_frame', [True, False]) def test_concat(self, data, in_frame): wrapped = pd.Series(data) if in_frame: wrapped = pd.DataFrame(wrapped) result = pd.concat([wrapped, wrapped], ignore_index=True) assert len(result) == len(data) * 2 if in_frame: dtype = result.dtypes[0] else: dtype = result.dtype assert dtype == data.dtype assert isinstance(result._data.blocks[0], ExtensionBlock) @pytest.mark.parametrize('in_frame', [True, False]) def test_concat_all_na_block(self, data_missing, in_frame): valid_block = pd.Series(data_missing.take([1, 1]), index=[0, 1]) na_block = pd.Series(data_missing.take([0, 0]), index=[2, 3]) if in_frame: valid_block = pd.DataFrame({"a": valid_block}) na_block = pd.DataFrame({"a": na_block}) result = pd.concat([valid_block, na_block]) if in_frame: expected = pd.DataFrame({"a": data_missing.take([1, 1, 0, 0])}) self.assert_frame_equal(result, expected) else: expected = pd.Series(data_missing.take([1, 1, 0, 0])) self.assert_series_equal(result, expected) def test_concat_mixed_dtypes(self, data): # https://github.com/pandas-dev/pandas/issues/20762 df1 = pd.DataFrame({'A': data[:3]}) df2 = pd.DataFrame({"A": [1, 2, 3]}) df3 = pd.DataFrame({"A": ['a', 'b', 'c']}).astype('category') dfs = [df1, df2, df3] # dataframes result = pd.concat(dfs) expected = pd.concat([x.astype(object) for x in dfs]) self.assert_frame_equal(result, expected) # series result = pd.concat([x['A'] for x in dfs]) expected = pd.concat([x['A'].astype(object) for x in dfs]) self.assert_series_equal(result, expected) # simple test for just EA and one other result = pd.concat([df1, df2]) expected = pd.concat([df1.astype('object'), df2.astype('object')]) self.assert_frame_equal(result, expected) result = pd.concat([df1['A'], df2['A']]) expected = pd.concat([df1['A'].astype('object'), df2['A'].astype('object')]) self.assert_series_equal(result, expected) def test_concat_columns(self, data, na_value): df1 = pd.DataFrame({'A': data[:3]}) df2 = pd.DataFrame({'B': [1, 2, 3]}) expected = pd.DataFrame({'A': data[:3], 'B': [1, 2, 3]}) result = pd.concat([df1, df2], axis=1) self.assert_frame_equal(result, expected) result = pd.concat([df1['A'], df2['B']], axis=1) self.assert_frame_equal(result, expected) # non-aligned df2 = pd.DataFrame({'B': [1, 2, 3]}, index=[1, 2, 3]) expected = pd.DataFrame({ 'A': data._from_sequence(list(data[:3]) + [na_value], dtype=data.dtype), 'B': [np.nan, 1, 2, 3]}) result = pd.concat([df1, df2], axis=1) self.assert_frame_equal(result, expected) result = pd.concat([df1['A'], df2['B']], axis=1) self.assert_frame_equal(result, expected) def test_align(self, data, na_value): a = data[:3] b = data[2:5] r1, r2 = pd.Series(a).align(pd.Series(b, index=[1, 2, 3])) # Assumes that the ctor can take a list of scalars of the type e1 = pd.Series(data._from_sequence(list(a) + [na_value], dtype=data.dtype)) e2 = pd.Series(data._from_sequence([na_value] + list(b), dtype=data.dtype)) self.assert_series_equal(r1, e1) self.assert_series_equal(r2, e2) def test_align_frame(self, data, na_value): a = data[:3] b = data[2:5] r1, r2 = pd.DataFrame({'A': a}).align( pd.DataFrame({'A': b}, index=[1, 2, 3]) ) # Assumes that the ctor can take a list of scalars of the type e1 = pd.DataFrame({'A': data._from_sequence(list(a) + [na_value], dtype=data.dtype)}) e2 = pd.DataFrame({'A': data._from_sequence([na_value] + list(b), dtype=data.dtype)}) self.assert_frame_equal(r1, e1) self.assert_frame_equal(r2, e2) def test_align_series_frame(self, data, na_value): # https://github.com/pandas-dev/pandas/issues/20576 ser = pd.Series(data, name='a') df = pd.DataFrame({"col": np.arange(len(ser) + 1)}) r1, r2 = ser.align(df) e1 = pd.Series(data._from_sequence(list(data) + [na_value], dtype=data.dtype), name=ser.name) self.assert_series_equal(r1, e1) self.assert_frame_equal(r2, df) def test_set_frame_expand_regular_with_extension(self, data): df = pd.DataFrame({"A": [1] * len(data)}) df['B'] = data expected = pd.DataFrame({"A": [1] * len(data), "B": data}) self.assert_frame_equal(df, expected) def test_set_frame_expand_extension_with_regular(self, data): df = pd.DataFrame({'A': data}) df['B'] = [1] * len(data) expected = pd.DataFrame({"A": data, "B": [1] * len(data)}) self.assert_frame_equal(df, expected) def test_set_frame_overwrite_object(self, data): # https://github.com/pandas-dev/pandas/issues/20555 df = pd.DataFrame({"A": [1] * len(data)}, dtype=object) df['A'] = data assert df.dtypes['A'] == data.dtype def test_merge(self, data, na_value): # GH-20743 df1 = pd.DataFrame({'ext': data[:3], 'int1': [1, 2, 3], 'key': [0, 1, 2]}) df2 = pd.DataFrame({'int2': [1, 2, 3, 4], 'key': [0, 0, 1, 3]}) res = pd.merge(df1, df2) exp = pd.DataFrame( {'int1': [1, 1, 2], 'int2': [1, 2, 3], 'key': [0, 0, 1], 'ext': data._from_sequence([data[0], data[0], data[1]], dtype=data.dtype)}) self.assert_frame_equal(res, exp[['ext', 'int1', 'key', 'int2']]) res = pd.merge(df1, df2, how='outer') exp = pd.DataFrame( {'int1': [1, 1, 2, 3, np.nan], 'int2': [1, 2, 3, np.nan, 4], 'key': [0, 0, 1, 2, 3], 'ext': data._from_sequence( [data[0], data[0], data[1], data[2], na_value], dtype=data.dtype)}) self.assert_frame_equal(res, exp[['ext', 'int1', 'key', 'int2']]) def test_merge_on_extension_array(self, data): # GH 23020 a, b = data[:2] key = type(data)._from_sequence([a, b], dtype=data.dtype) df = pd.DataFrame({"key": key, "val": [1, 2]}) result = pd.merge(df, df, on='key') expected = pd.DataFrame({"key": key, "val_x": [1, 2], "val_y": [1, 2]}) self.assert_frame_equal(result, expected) # order result = pd.merge(df.iloc[[1, 0]], df, on='key') expected = expected.iloc[[1, 0]].reset_index(drop=True) self.assert_frame_equal(result, expected) def test_merge_on_extension_array_duplicates(self, data): # GH 23020 a, b = data[:2] key = type(data)._from_sequence([a, b, a], dtype=data.dtype) df1 = pd.DataFrame({"key": key, "val": [1, 2, 3]}) df2 = pd.DataFrame({"key": key, "val": [1, 2, 3]}) result = pd.merge(df1, df2, on='key') expected = pd.DataFrame({ "key": key.take([0, 0, 0, 0, 1]), "val_x": [1, 1, 3, 3, 2], "val_y": [1, 3, 1, 3, 2], }) self.assert_frame_equal(result, expected) @pytest.mark.parametrize("columns", [ ["A", "B"], pd.MultiIndex.from_tuples([('A', 'a'), ('A', 'b')], names=['outer', 'inner']), ]) def test_stack(self, data, columns): df = pd.DataFrame({"A": data[:5], "B": data[:5]}) df.columns = columns result = df.stack() expected = df.astype(object).stack() # we need a second astype(object), in case the constructor inferred # object -> specialized, as is done for period. expected = expected.astype(object) if isinstance(expected, pd.Series): assert result.dtype == df.iloc[:, 0].dtype else: assert all(result.dtypes == df.iloc[:, 0].dtype) result = result.astype(object) self.assert_equal(result, expected) @pytest.mark.parametrize("index", [ # Two levels, uniform. pd.MultiIndex.from_product(([['A', 'B'], ['a', 'b']]), names=['a', 'b']), # non-uniform pd.MultiIndex.from_tuples([('A', 'a'), ('A', 'b'), ('B', 'b')]), # three levels, non-uniform pd.MultiIndex.from_product([('A', 'B'), ('a', 'b', 'c'), (0, 1, 2)]), pd.MultiIndex.from_tuples([ ('A', 'a', 1), ('A', 'b', 0), ('A', 'a', 0), ('B', 'a', 0), ('B', 'c', 1), ]), ]) @pytest.mark.parametrize("obj", ["series", "frame"]) def test_unstack(self, data, index, obj): data = data[:len(index)] if obj == "series": ser = pd.Series(data, index=index) else: ser = pd.DataFrame({"A": data, "B": data}, index=index) n = index.nlevels levels = list(range(n)) # [0, 1, 2] # [(0,), (1,), (2,), (0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] combinations = itertools.chain.from_iterable( itertools.permutations(levels, i) for i in range(1, n) ) for level in combinations: result = ser.unstack(level=level) assert all(isinstance(result[col].array, type(data)) for col in result.columns) expected = ser.astype(object).unstack(level=level) result = result.astype(object) self.assert_frame_equal(result, expected)
import numpy as np import pytest import pandas as pd from pandas.util import testing as tm class TestTimedeltaIndexing(object): def test_boolean_indexing(self): # GH 14946 df = pd.DataFrame({'x': range(10)}) df.index = pd.to_timedelta(range(10), unit='s') conditions = [df['x'] > 3, df['x'] == 3, df['x'] < 3] expected_data = [[0, 1, 2, 3, 10, 10, 10, 10, 10, 10], [0, 1, 2, 10, 4, 5, 6, 7, 8, 9], [10, 10, 10, 3, 4, 5, 6, 7, 8, 9]] for cond, data in zip(conditions, expected_data): result = df.assign(x=df.mask(cond, 10).astype('int64')) expected = pd.DataFrame(data, index=pd.to_timedelta(range(10), unit='s'), columns=['x'], dtype='int64') tm.assert_frame_equal(expected, result) @pytest.mark.parametrize( "indexer, expected", [(0, [20, 1, 2, 3, 4, 5, 6, 7, 8, 9]), (slice(4, 8), [0, 1, 2, 3, 20, 20, 20, 20, 8, 9]), ([3, 5], [0, 1, 2, 20, 4, 20, 6, 7, 8, 9])]) def test_list_like_indexing(self, indexer, expected): # GH 16637 df = pd.DataFrame({'x': range(10)}, dtype="int64") df.index = pd.to_timedelta(range(10), unit='s') df.loc[df.index[indexer], 'x'] = 20 expected = pd.DataFrame(expected, index=pd.to_timedelta(range(10), unit='s'), columns=['x'], dtype="int64") tm.assert_frame_equal(expected, df) def test_string_indexing(self): # GH 16896 df = pd.DataFrame({'x': range(3)}, index=pd.to_timedelta(range(3), unit='days')) expected = df.iloc[0] sliced = df.loc['0 days'] tm.assert_series_equal(sliced, expected) @pytest.mark.parametrize( "value", [None, pd.NaT, np.nan]) def test_masked_setitem(self, value): # issue (#18586) series = pd.Series([0, 1, 2], dtype='timedelta64[ns]') series[series == series[0]] = value expected = pd.Series([pd.NaT, 1, 2], dtype='timedelta64[ns]') tm.assert_series_equal(series, expected) @pytest.mark.parametrize( "value", [None, pd.NaT, np.nan]) def test_listlike_setitem(self, value): # issue (#18586) series = pd.Series([0, 1, 2], dtype='timedelta64[ns]') series.iloc[0] = value expected = pd.Series([pd.NaT, 1, 2], dtype='timedelta64[ns]') tm.assert_series_equal(series, expected) @pytest.mark.parametrize('start,stop, expected_slice', [ [np.timedelta64(0, 'ns'), None, slice(0, 11)], [np.timedelta64(1, 'D'), np.timedelta64(6, 'D'), slice(1, 7)], [None, np.timedelta64(4, 'D'), slice(0, 5)]]) def test_numpy_timedelta_scalar_indexing(self, start, stop, expected_slice): # GH 20393 s = pd.Series(range(11), pd.timedelta_range('0 days', '10 days')) result = s.loc[slice(start, stop)] expected = s.iloc[expected_slice] tm.assert_series_equal(result, expected) def test_roundtrip_thru_setitem(self): # PR 23462 dt1 = pd.Timedelta(0) dt2 = pd.Timedelta(28767471428571405) df = pd.DataFrame({'dt': pd.Series([dt1, dt2])}) df_copy = df.copy() s = pd.Series([dt1]) expected = df['dt'].iloc[1].value df.loc[[True, False]] = s result = df['dt'].iloc[1].value assert expected == result tm.assert_frame_equal(df, df_copy)
MJuddBooth/pandas
pandas/tests/indexing/test_timedelta.py
pandas/tests/extension/base/reshaping.py
# flake8: noqa from .common import ( is_array_like, is_bool, is_bool_dtype, is_categorical, is_categorical_dtype, is_complex, is_complex_dtype, is_datetime64_any_dtype, is_datetime64_dtype, is_datetime64_ns_dtype, is_datetime64tz_dtype, is_datetimetz, is_dict_like, is_dtype_equal, is_extension_array_dtype, is_extension_type, is_file_like, is_float, is_float_dtype, is_hashable, is_int64_dtype, is_integer, is_integer_dtype, is_interval, is_interval_dtype, is_iterator, is_list_like, is_named_tuple, is_number, is_numeric_dtype, is_object_dtype, is_period, is_period_dtype, is_re, is_re_compilable, is_scalar, is_signed_integer_dtype, is_sparse, is_string_dtype, is_timedelta64_dtype, is_timedelta64_ns_dtype, is_unsigned_integer_dtype, pandas_dtype)
import numpy as np import pytest import pandas as pd from pandas.util import testing as tm class TestTimedeltaIndexing(object): def test_boolean_indexing(self): # GH 14946 df = pd.DataFrame({'x': range(10)}) df.index = pd.to_timedelta(range(10), unit='s') conditions = [df['x'] > 3, df['x'] == 3, df['x'] < 3] expected_data = [[0, 1, 2, 3, 10, 10, 10, 10, 10, 10], [0, 1, 2, 10, 4, 5, 6, 7, 8, 9], [10, 10, 10, 3, 4, 5, 6, 7, 8, 9]] for cond, data in zip(conditions, expected_data): result = df.assign(x=df.mask(cond, 10).astype('int64')) expected = pd.DataFrame(data, index=pd.to_timedelta(range(10), unit='s'), columns=['x'], dtype='int64') tm.assert_frame_equal(expected, result) @pytest.mark.parametrize( "indexer, expected", [(0, [20, 1, 2, 3, 4, 5, 6, 7, 8, 9]), (slice(4, 8), [0, 1, 2, 3, 20, 20, 20, 20, 8, 9]), ([3, 5], [0, 1, 2, 20, 4, 20, 6, 7, 8, 9])]) def test_list_like_indexing(self, indexer, expected): # GH 16637 df = pd.DataFrame({'x': range(10)}, dtype="int64") df.index = pd.to_timedelta(range(10), unit='s') df.loc[df.index[indexer], 'x'] = 20 expected = pd.DataFrame(expected, index=pd.to_timedelta(range(10), unit='s'), columns=['x'], dtype="int64") tm.assert_frame_equal(expected, df) def test_string_indexing(self): # GH 16896 df = pd.DataFrame({'x': range(3)}, index=pd.to_timedelta(range(3), unit='days')) expected = df.iloc[0] sliced = df.loc['0 days'] tm.assert_series_equal(sliced, expected) @pytest.mark.parametrize( "value", [None, pd.NaT, np.nan]) def test_masked_setitem(self, value): # issue (#18586) series = pd.Series([0, 1, 2], dtype='timedelta64[ns]') series[series == series[0]] = value expected = pd.Series([pd.NaT, 1, 2], dtype='timedelta64[ns]') tm.assert_series_equal(series, expected) @pytest.mark.parametrize( "value", [None, pd.NaT, np.nan]) def test_listlike_setitem(self, value): # issue (#18586) series = pd.Series([0, 1, 2], dtype='timedelta64[ns]') series.iloc[0] = value expected = pd.Series([pd.NaT, 1, 2], dtype='timedelta64[ns]') tm.assert_series_equal(series, expected) @pytest.mark.parametrize('start,stop, expected_slice', [ [np.timedelta64(0, 'ns'), None, slice(0, 11)], [np.timedelta64(1, 'D'), np.timedelta64(6, 'D'), slice(1, 7)], [None, np.timedelta64(4, 'D'), slice(0, 5)]]) def test_numpy_timedelta_scalar_indexing(self, start, stop, expected_slice): # GH 20393 s = pd.Series(range(11), pd.timedelta_range('0 days', '10 days')) result = s.loc[slice(start, stop)] expected = s.iloc[expected_slice] tm.assert_series_equal(result, expected) def test_roundtrip_thru_setitem(self): # PR 23462 dt1 = pd.Timedelta(0) dt2 = pd.Timedelta(28767471428571405) df = pd.DataFrame({'dt': pd.Series([dt1, dt2])}) df_copy = df.copy() s = pd.Series([dt1]) expected = df['dt'].iloc[1].value df.loc[[True, False]] = s result = df['dt'].iloc[1].value assert expected == result tm.assert_frame_equal(df, df_copy)
MJuddBooth/pandas
pandas/tests/indexing/test_timedelta.py
pandas/core/dtypes/api.py
# -*- coding: utf-8 -*- from collections import defaultdict from functools import partial import itertools import operator import re import numpy as np from pandas._libs import internals as libinternals, lib from pandas.compat import map, range, zip from pandas.util._validators import validate_bool_kwarg from pandas.core.dtypes.cast import ( find_common_type, infer_dtype_from_scalar, maybe_convert_objects, maybe_promote) from pandas.core.dtypes.common import ( _NS_DTYPE, is_datetimelike_v_numeric, is_extension_array_dtype, is_extension_type, is_list_like, is_numeric_v_string_like, is_scalar) import pandas.core.dtypes.concat as _concat from pandas.core.dtypes.generic import ABCExtensionArray, ABCSeries from pandas.core.dtypes.missing import isna import pandas.core.algorithms as algos from pandas.core.arrays.sparse import _maybe_to_sparse from pandas.core.base import PandasObject from pandas.core.index import Index, MultiIndex, ensure_index from pandas.core.indexing import maybe_convert_indices from pandas.io.formats.printing import pprint_thing from .blocks import ( Block, CategoricalBlock, DatetimeTZBlock, ExtensionBlock, ObjectValuesExtensionBlock, _extend_blocks, _merge_blocks, _safe_reshape, get_block_type, make_block) from .concat import ( # all for concatenate_block_managers combine_concat_plans, concatenate_join_units, get_mgr_concatenation_plan, is_uniform_join_units) # TODO: flexible with index=None and/or items=None class BlockManager(PandasObject): """ Core internal data structure to implement DataFrame, Series, Panel, etc. Manage a bunch of labeled 2D mixed-type ndarrays. Essentially it's a lightweight blocked set of labeled data to be manipulated by the DataFrame public API class Attributes ---------- shape ndim axes values items Methods ------- set_axis(axis, new_labels) copy(deep=True) get_dtype_counts get_ftype_counts get_dtypes get_ftypes apply(func, axes, block_filter_fn) get_bool_data get_numeric_data get_slice(slice_like, axis) get(label) iget(loc) take(indexer, axis) reindex_axis(new_labels, axis) reindex_indexer(new_labels, indexer, axis) delete(label) insert(loc, label, value) set(label, value) Parameters ---------- Notes ----- This is *not* a public API class """ __slots__ = ['axes', 'blocks', '_ndim', '_shape', '_known_consolidated', '_is_consolidated', '_blknos', '_blklocs'] def __init__(self, blocks, axes, do_integrity_check=True): self.axes = [ensure_index(ax) for ax in axes] self.blocks = tuple(blocks) for block in blocks: if block.is_sparse: if len(block.mgr_locs) != 1: raise AssertionError("Sparse block refers to multiple " "items") else: if self.ndim != block.ndim: raise AssertionError( 'Number of Block dimensions ({block}) must equal ' 'number of axes ({self})'.format(block=block.ndim, self=self.ndim)) if do_integrity_check: self._verify_integrity() self._consolidate_check() self._rebuild_blknos_and_blklocs() def make_empty(self, axes=None): """ return an empty BlockManager with the items axis of len 0 """ if axes is None: axes = [ensure_index([])] + [ensure_index(a) for a in self.axes[1:]] # preserve dtype if possible if self.ndim == 1: blocks = np.array([], dtype=self.array_dtype) else: blocks = [] return self.__class__(blocks, axes) def __nonzero__(self): return True # Python3 compat __bool__ = __nonzero__ @property def shape(self): return tuple(len(ax) for ax in self.axes) @property def ndim(self): return len(self.axes) def set_axis(self, axis, new_labels): new_labels = ensure_index(new_labels) old_len = len(self.axes[axis]) new_len = len(new_labels) if new_len != old_len: raise ValueError( 'Length mismatch: Expected axis has {old} elements, new ' 'values have {new} elements'.format(old=old_len, new=new_len)) self.axes[axis] = new_labels def rename_axis(self, mapper, axis, copy=True, level=None): """ Rename one of axes. Parameters ---------- mapper : unary callable axis : int copy : boolean, default True level : int, default None """ obj = self.copy(deep=copy) obj.set_axis(axis, _transform_index(self.axes[axis], mapper, level)) return obj @property def _is_single_block(self): if self.ndim == 1: return True if len(self.blocks) != 1: return False blk = self.blocks[0] return (blk.mgr_locs.is_slice_like and blk.mgr_locs.as_slice == slice(0, len(self), 1)) def _rebuild_blknos_and_blklocs(self): """ Update mgr._blknos / mgr._blklocs. """ new_blknos = np.empty(self.shape[0], dtype=np.int64) new_blklocs = np.empty(self.shape[0], dtype=np.int64) new_blknos.fill(-1) new_blklocs.fill(-1) for blkno, blk in enumerate(self.blocks): rl = blk.mgr_locs new_blknos[rl.indexer] = blkno new_blklocs[rl.indexer] = np.arange(len(rl)) if (new_blknos == -1).any(): raise AssertionError("Gaps in blk ref_locs") self._blknos = new_blknos self._blklocs = new_blklocs @property def items(self): return self.axes[0] def _get_counts(self, f): """ return a dict of the counts of the function in BlockManager """ self._consolidate_inplace() counts = dict() for b in self.blocks: v = f(b) counts[v] = counts.get(v, 0) + b.shape[0] return counts def get_dtype_counts(self): return self._get_counts(lambda b: b.dtype.name) def get_ftype_counts(self): return self._get_counts(lambda b: b.ftype) def get_dtypes(self): dtypes = np.array([blk.dtype for blk in self.blocks]) return algos.take_1d(dtypes, self._blknos, allow_fill=False) def get_ftypes(self): ftypes = np.array([blk.ftype for blk in self.blocks]) return algos.take_1d(ftypes, self._blknos, allow_fill=False) def __getstate__(self): block_values = [b.values for b in self.blocks] block_items = [self.items[b.mgr_locs.indexer] for b in self.blocks] axes_array = [ax for ax in self.axes] extra_state = { '0.14.1': { 'axes': axes_array, 'blocks': [dict(values=b.values, mgr_locs=b.mgr_locs.indexer) for b in self.blocks] } } # First three elements of the state are to maintain forward # compatibility with 0.13.1. return axes_array, block_values, block_items, extra_state def __setstate__(self, state): def unpickle_block(values, mgr_locs): return make_block(values, placement=mgr_locs) if (isinstance(state, tuple) and len(state) >= 4 and '0.14.1' in state[3]): state = state[3]['0.14.1'] self.axes = [ensure_index(ax) for ax in state['axes']] self.blocks = tuple(unpickle_block(b['values'], b['mgr_locs']) for b in state['blocks']) else: # discard anything after 3rd, support beta pickling format for a # little while longer ax_arrays, bvalues, bitems = state[:3] self.axes = [ensure_index(ax) for ax in ax_arrays] if len(bitems) == 1 and self.axes[0].equals(bitems[0]): # This is a workaround for pre-0.14.1 pickles that didn't # support unpickling multi-block frames/panels with non-unique # columns/items, because given a manager with items ["a", "b", # "a"] there's no way of knowing which block's "a" is where. # # Single-block case can be supported under the assumption that # block items corresponded to manager items 1-to-1. all_mgr_locs = [slice(0, len(bitems[0]))] else: all_mgr_locs = [self.axes[0].get_indexer(blk_items) for blk_items in bitems] self.blocks = tuple( unpickle_block(values, mgr_locs) for values, mgr_locs in zip(bvalues, all_mgr_locs)) self._post_setstate() def _post_setstate(self): self._is_consolidated = False self._known_consolidated = False self._rebuild_blknos_and_blklocs() def __len__(self): return len(self.items) def __unicode__(self): output = pprint_thing(self.__class__.__name__) for i, ax in enumerate(self.axes): if i == 0: output += u'\nItems: {ax}'.format(ax=ax) else: output += u'\nAxis {i}: {ax}'.format(i=i, ax=ax) for block in self.blocks: output += u'\n{block}'.format(block=pprint_thing(block)) return output def _verify_integrity(self): mgr_shape = self.shape tot_items = sum(len(x.mgr_locs) for x in self.blocks) for block in self.blocks: if block._verify_integrity and block.shape[1:] != mgr_shape[1:]: construction_error(tot_items, block.shape[1:], self.axes) if len(self.items) != tot_items: raise AssertionError('Number of manager items must equal union of ' 'block items\n# manager items: {0}, # ' 'tot_items: {1}'.format( len(self.items), tot_items)) def apply(self, f, axes=None, filter=None, do_integrity_check=False, consolidate=True, **kwargs): """ iterate over the blocks, collect and create a new block manager Parameters ---------- f : the callable or function name to operate on at the block level axes : optional (if not supplied, use self.axes) filter : list, if supplied, only call the block if the filter is in the block do_integrity_check : boolean, default False. Do the block manager integrity check consolidate: boolean, default True. Join together blocks having same dtype Returns ------- Block Manager (new object) """ result_blocks = [] # filter kwarg is used in replace-* family of methods if filter is not None: filter_locs = set(self.items.get_indexer_for(filter)) if len(filter_locs) == len(self.items): # All items are included, as if there were no filtering filter = None else: kwargs['filter'] = filter_locs if consolidate: self._consolidate_inplace() if f == 'where': align_copy = True if kwargs.get('align', True): align_keys = ['other', 'cond'] else: align_keys = ['cond'] elif f == 'putmask': align_copy = False if kwargs.get('align', True): align_keys = ['new', 'mask'] else: align_keys = ['mask'] elif f == 'fillna': # fillna internally does putmask, maybe it's better to do this # at mgr, not block level? align_copy = False align_keys = ['value'] else: align_keys = [] # TODO(EA): may interfere with ExtensionBlock.setitem for blocks # with a .values attribute. aligned_args = {k: kwargs[k] for k in align_keys if hasattr(kwargs[k], 'values') and not isinstance(kwargs[k], ABCExtensionArray)} for b in self.blocks: if filter is not None: if not b.mgr_locs.isin(filter_locs).any(): result_blocks.append(b) continue if aligned_args: b_items = self.items[b.mgr_locs.indexer] for k, obj in aligned_args.items(): axis = getattr(obj, '_info_axis_number', 0) kwargs[k] = obj.reindex(b_items, axis=axis, copy=align_copy) applied = getattr(b, f)(**kwargs) result_blocks = _extend_blocks(applied, result_blocks) if len(result_blocks) == 0: return self.make_empty(axes or self.axes) bm = self.__class__(result_blocks, axes or self.axes, do_integrity_check=do_integrity_check) bm._consolidate_inplace() return bm def quantile(self, axis=0, consolidate=True, transposed=False, interpolation='linear', qs=None, numeric_only=None): """ Iterate over blocks applying quantile reduction. This routine is intended for reduction type operations and will do inference on the generated blocks. Parameters ---------- axis: reduction axis, default 0 consolidate: boolean, default True. Join together blocks having same dtype transposed: boolean, default False we are holding transposed data interpolation : type of interpolation, default 'linear' qs : a scalar or list of the quantiles to be computed numeric_only : ignored Returns ------- Block Manager (new object) """ # Series dispatches to DataFrame for quantile, which allows us to # simplify some of the code here and in the blocks assert self.ndim >= 2 if consolidate: self._consolidate_inplace() def get_axe(block, qs, axes): from pandas import Float64Index if is_list_like(qs): ax = Float64Index(qs) elif block.ndim == 1: ax = Float64Index([qs]) else: ax = axes[0] return ax axes, blocks = [], [] for b in self.blocks: block = b.quantile(axis=axis, qs=qs, interpolation=interpolation) axe = get_axe(b, qs, axes=self.axes) axes.append(axe) blocks.append(block) # note that some DatetimeTZ, Categorical are always ndim==1 ndim = {b.ndim for b in blocks} assert 0 not in ndim, ndim if 2 in ndim: new_axes = list(self.axes) # multiple blocks that are reduced if len(blocks) > 1: new_axes[1] = axes[0] # reset the placement to the original for b, sb in zip(blocks, self.blocks): b.mgr_locs = sb.mgr_locs else: new_axes[axis] = Index(np.concatenate( [ax.values for ax in axes])) if transposed: new_axes = new_axes[::-1] blocks = [b.make_block(b.values.T, placement=np.arange(b.shape[1]) ) for b in blocks] return self.__class__(blocks, new_axes) # single block, i.e. ndim == {1} values = _concat._concat_compat([b.values for b in blocks]) # compute the orderings of our original data if len(self.blocks) > 1: indexer = np.empty(len(self.axes[0]), dtype=np.intp) i = 0 for b in self.blocks: for j in b.mgr_locs: indexer[j] = i i = i + 1 values = values.take(indexer) return SingleBlockManager( [make_block(values, ndim=1, placement=np.arange(len(values)))], axes[0]) def isna(self, func, **kwargs): return self.apply('apply', func=func, **kwargs) def where(self, **kwargs): return self.apply('where', **kwargs) def setitem(self, **kwargs): return self.apply('setitem', **kwargs) def putmask(self, **kwargs): return self.apply('putmask', **kwargs) def diff(self, **kwargs): return self.apply('diff', **kwargs) def interpolate(self, **kwargs): return self.apply('interpolate', **kwargs) def shift(self, **kwargs): return self.apply('shift', **kwargs) def fillna(self, **kwargs): return self.apply('fillna', **kwargs) def downcast(self, **kwargs): return self.apply('downcast', **kwargs) def astype(self, dtype, **kwargs): return self.apply('astype', dtype=dtype, **kwargs) def convert(self, **kwargs): return self.apply('convert', **kwargs) def replace(self, **kwargs): return self.apply('replace', **kwargs) def replace_list(self, src_list, dest_list, inplace=False, regex=False): """ do a list replace """ inplace = validate_bool_kwarg(inplace, 'inplace') # figure out our mask a-priori to avoid repeated replacements values = self.as_array() def comp(s, regex=False): """ Generate a bool array by perform an equality check, or perform an element-wise regular expression matching """ if isna(s): return isna(values) if hasattr(s, 'asm8'): return _compare_or_regex_search(maybe_convert_objects(values), getattr(s, 'asm8'), regex) return _compare_or_regex_search(values, s, regex) masks = [comp(s, regex) for i, s in enumerate(src_list)] result_blocks = [] src_len = len(src_list) - 1 for blk in self.blocks: # its possible to get multiple result blocks here # replace ALWAYS will return a list rb = [blk if inplace else blk.copy()] for i, (s, d) in enumerate(zip(src_list, dest_list)): new_rb = [] for b in rb: m = masks[i][b.mgr_locs.indexer] convert = i == src_len result = b._replace_coerce(mask=m, to_replace=s, value=d, inplace=inplace, convert=convert, regex=regex) if m.any(): new_rb = _extend_blocks(result, new_rb) else: new_rb.append(b) rb = new_rb result_blocks.extend(rb) bm = self.__class__(result_blocks, self.axes) bm._consolidate_inplace() return bm def is_consolidated(self): """ Return True if more than one block with the same dtype """ if not self._known_consolidated: self._consolidate_check() return self._is_consolidated def _consolidate_check(self): ftypes = [blk.ftype for blk in self.blocks] self._is_consolidated = len(ftypes) == len(set(ftypes)) self._known_consolidated = True @property def is_mixed_type(self): # Warning, consolidation needs to get checked upstairs self._consolidate_inplace() return len(self.blocks) > 1 @property def is_numeric_mixed_type(self): # Warning, consolidation needs to get checked upstairs self._consolidate_inplace() return all(block.is_numeric for block in self.blocks) @property def is_datelike_mixed_type(self): # Warning, consolidation needs to get checked upstairs self._consolidate_inplace() return any(block.is_datelike for block in self.blocks) @property def any_extension_types(self): """Whether any of the blocks in this manager are extension blocks""" return any(block.is_extension for block in self.blocks) @property def is_view(self): """ return a boolean if we are a single block and are a view """ if len(self.blocks) == 1: return self.blocks[0].is_view # It is technically possible to figure out which blocks are views # e.g. [ b.values.base is not None for b in self.blocks ] # but then we have the case of possibly some blocks being a view # and some blocks not. setting in theory is possible on the non-view # blocks w/o causing a SettingWithCopy raise/warn. But this is a bit # complicated return False def get_bool_data(self, copy=False): """ Parameters ---------- copy : boolean, default False Whether to copy the blocks """ self._consolidate_inplace() return self.combine([b for b in self.blocks if b.is_bool], copy) def get_numeric_data(self, copy=False): """ Parameters ---------- copy : boolean, default False Whether to copy the blocks """ self._consolidate_inplace() return self.combine([b for b in self.blocks if b.is_numeric], copy) def combine(self, blocks, copy=True): """ return a new manager with the blocks """ if len(blocks) == 0: return self.make_empty() # FIXME: optimization potential indexer = np.sort(np.concatenate([b.mgr_locs.as_array for b in blocks])) inv_indexer = lib.get_reverse_indexer(indexer, self.shape[0]) new_blocks = [] for b in blocks: b = b.copy(deep=copy) b.mgr_locs = algos.take_1d(inv_indexer, b.mgr_locs.as_array, axis=0, allow_fill=False) new_blocks.append(b) axes = list(self.axes) axes[0] = self.items.take(indexer) return self.__class__(new_blocks, axes, do_integrity_check=False) def get_slice(self, slobj, axis=0): if axis >= self.ndim: raise IndexError("Requested axis not found in manager") if axis == 0: new_blocks = self._slice_take_blocks_ax0(slobj) else: slicer = [slice(None)] * (axis + 1) slicer[axis] = slobj slicer = tuple(slicer) new_blocks = [blk.getitem_block(slicer) for blk in self.blocks] new_axes = list(self.axes) new_axes[axis] = new_axes[axis][slobj] bm = self.__class__(new_blocks, new_axes, do_integrity_check=False) bm._consolidate_inplace() return bm def __contains__(self, item): return item in self.items @property def nblocks(self): return len(self.blocks) def copy(self, deep=True): """ Make deep or shallow copy of BlockManager Parameters ---------- deep : boolean o rstring, default True If False, return shallow copy (do not copy data) If 'all', copy data and a deep copy of the index Returns ------- copy : BlockManager """ # this preserves the notion of view copying of axes if deep: if deep == 'all': copy = lambda ax: ax.copy(deep=True) else: copy = lambda ax: ax.view() new_axes = [copy(ax) for ax in self.axes] else: new_axes = list(self.axes) return self.apply('copy', axes=new_axes, deep=deep, do_integrity_check=False) def as_array(self, transpose=False, items=None): """Convert the blockmanager data into an numpy array. Parameters ---------- transpose : boolean, default False If True, transpose the return array items : list of strings or None Names of block items that will be included in the returned array. ``None`` means that all block items will be used Returns ------- arr : ndarray """ if len(self.blocks) == 0: arr = np.empty(self.shape, dtype=float) return arr.transpose() if transpose else arr if items is not None: mgr = self.reindex_axis(items, axis=0) else: mgr = self if self._is_single_block and mgr.blocks[0].is_datetimetz: # TODO(Block.get_values): Make DatetimeTZBlock.get_values # always be object dtype. Some callers seem to want the # DatetimeArray (previously DTI) arr = mgr.blocks[0].get_values(dtype=object) elif self._is_single_block or not self.is_mixed_type: arr = np.asarray(mgr.blocks[0].get_values()) else: arr = mgr._interleave() return arr.transpose() if transpose else arr def _interleave(self): """ Return ndarray from blocks with specified item order Items must be contained in the blocks """ from pandas.core.dtypes.common import is_sparse dtype = _interleaved_dtype(self.blocks) # TODO: https://github.com/pandas-dev/pandas/issues/22791 # Give EAs some input on what happens here. Sparse needs this. if is_sparse(dtype): dtype = dtype.subtype elif is_extension_array_dtype(dtype): dtype = 'object' result = np.empty(self.shape, dtype=dtype) itemmask = np.zeros(self.shape[0]) for blk in self.blocks: rl = blk.mgr_locs result[rl.indexer] = blk.get_values(dtype) itemmask[rl.indexer] = 1 if not itemmask.all(): raise AssertionError('Some items were not contained in blocks') return result def to_dict(self, copy=True): """ Return a dict of str(dtype) -> BlockManager Parameters ---------- copy : boolean, default True Returns ------- values : a dict of dtype -> BlockManager Notes ----- This consolidates based on str(dtype) """ self._consolidate_inplace() bd = {} for b in self.blocks: bd.setdefault(str(b.dtype), []).append(b) return {dtype: self.combine(blocks, copy=copy) for dtype, blocks in bd.items()} def xs(self, key, axis=1, copy=True, takeable=False): if axis < 1: raise AssertionError( 'Can only take xs across axis >= 1, got {ax}'.format(ax=axis)) # take by position if takeable: loc = key else: loc = self.axes[axis].get_loc(key) slicer = [slice(None, None) for _ in range(self.ndim)] slicer[axis] = loc slicer = tuple(slicer) new_axes = list(self.axes) # could be an array indexer! if isinstance(loc, (slice, np.ndarray)): new_axes[axis] = new_axes[axis][loc] else: new_axes.pop(axis) new_blocks = [] if len(self.blocks) > 1: # we must copy here as we are mixed type for blk in self.blocks: newb = make_block(values=blk.values[slicer], klass=blk.__class__, placement=blk.mgr_locs) new_blocks.append(newb) elif len(self.blocks) == 1: block = self.blocks[0] vals = block.values[slicer] if copy: vals = vals.copy() new_blocks = [make_block(values=vals, placement=block.mgr_locs, klass=block.__class__)] return self.__class__(new_blocks, new_axes) def fast_xs(self, loc): """ get a cross sectional for a given location in the items ; handle dups return the result, is *could* be a view in the case of a single block """ if len(self.blocks) == 1: return self.blocks[0].iget((slice(None), loc)) items = self.items # non-unique (GH4726) if not items.is_unique: result = self._interleave() if self.ndim == 2: result = result.T return result[loc] # unique dtype = _interleaved_dtype(self.blocks) n = len(items) if is_extension_array_dtype(dtype): # we'll eventually construct an ExtensionArray. result = np.empty(n, dtype=object) else: result = np.empty(n, dtype=dtype) for blk in self.blocks: # Such assignment may incorrectly coerce NaT to None # result[blk.mgr_locs] = blk._slice((slice(None), loc)) for i, rl in enumerate(blk.mgr_locs): result[rl] = blk._try_coerce_result(blk.iget((i, loc))) if is_extension_array_dtype(dtype): result = dtype.construct_array_type()._from_sequence( result, dtype=dtype ) return result def consolidate(self): """ Join together blocks having same dtype Returns ------- y : BlockManager """ if self.is_consolidated(): return self bm = self.__class__(self.blocks, self.axes) bm._is_consolidated = False bm._consolidate_inplace() return bm def _consolidate_inplace(self): if not self.is_consolidated(): self.blocks = tuple(_consolidate(self.blocks)) self._is_consolidated = True self._known_consolidated = True self._rebuild_blknos_and_blklocs() def get(self, item, fastpath=True): """ Return values for selected item (ndarray or BlockManager). """ if self.items.is_unique: if not isna(item): loc = self.items.get_loc(item) else: indexer = np.arange(len(self.items))[isna(self.items)] # allow a single nan location indexer if not is_scalar(indexer): if len(indexer) == 1: loc = indexer.item() else: raise ValueError("cannot label index with a null key") return self.iget(loc, fastpath=fastpath) else: if isna(item): raise TypeError("cannot label index with a null key") indexer = self.items.get_indexer_for([item]) return self.reindex_indexer(new_axis=self.items[indexer], indexer=indexer, axis=0, allow_dups=True) def iget(self, i, fastpath=True): """ Return the data as a SingleBlockManager if fastpath=True and possible Otherwise return as a ndarray """ block = self.blocks[self._blknos[i]] values = block.iget(self._blklocs[i]) if not fastpath or not block._box_to_block_values or values.ndim != 1: return values # fastpath shortcut for select a single-dim from a 2-dim BM return SingleBlockManager( [block.make_block_same_class(values, placement=slice(0, len(values)), ndim=1)], self.axes[1]) def delete(self, item): """ Delete selected item (items if non-unique) in-place. """ indexer = self.items.get_loc(item) is_deleted = np.zeros(self.shape[0], dtype=np.bool_) is_deleted[indexer] = True ref_loc_offset = -is_deleted.cumsum() is_blk_deleted = [False] * len(self.blocks) if isinstance(indexer, int): affected_start = indexer else: affected_start = is_deleted.nonzero()[0][0] for blkno, _ in _fast_count_smallints(self._blknos[affected_start:]): blk = self.blocks[blkno] bml = blk.mgr_locs blk_del = is_deleted[bml.indexer].nonzero()[0] if len(blk_del) == len(bml): is_blk_deleted[blkno] = True continue elif len(blk_del) != 0: blk.delete(blk_del) bml = blk.mgr_locs blk.mgr_locs = bml.add(ref_loc_offset[bml.indexer]) # FIXME: use Index.delete as soon as it uses fastpath=True self.axes[0] = self.items[~is_deleted] self.blocks = tuple(b for blkno, b in enumerate(self.blocks) if not is_blk_deleted[blkno]) self._shape = None self._rebuild_blknos_and_blklocs() def set(self, item, value): """ Set new item in-place. Does not consolidate. Adds new Block if not contained in the current set of items """ # FIXME: refactor, clearly separate broadcasting & zip-like assignment # can prob also fix the various if tests for sparse/categorical # TODO(EA): Remove an is_extension_ when all extension types satisfy # the interface value_is_extension_type = (is_extension_type(value) or is_extension_array_dtype(value)) # categorical/spares/datetimetz if value_is_extension_type: def value_getitem(placement): return value else: if value.ndim == self.ndim - 1: value = _safe_reshape(value, (1,) + value.shape) def value_getitem(placement): return value else: def value_getitem(placement): return value[placement.indexer] if value.shape[1:] != self.shape[1:]: raise AssertionError('Shape of new values must be compatible ' 'with manager shape') try: loc = self.items.get_loc(item) except KeyError: # This item wasn't present, just insert at end self.insert(len(self.items), item, value) return if isinstance(loc, int): loc = [loc] blknos = self._blknos[loc] blklocs = self._blklocs[loc].copy() unfit_mgr_locs = [] unfit_val_locs = [] removed_blknos = [] for blkno, val_locs in libinternals.get_blkno_placements(blknos, self.nblocks, group=True): blk = self.blocks[blkno] blk_locs = blklocs[val_locs.indexer] if blk.should_store(value): blk.set(blk_locs, value_getitem(val_locs)) else: unfit_mgr_locs.append(blk.mgr_locs.as_array[blk_locs]) unfit_val_locs.append(val_locs) # If all block items are unfit, schedule the block for removal. if len(val_locs) == len(blk.mgr_locs): removed_blknos.append(blkno) else: self._blklocs[blk.mgr_locs.indexer] = -1 blk.delete(blk_locs) self._blklocs[blk.mgr_locs.indexer] = np.arange(len(blk)) if len(removed_blknos): # Remove blocks & update blknos accordingly is_deleted = np.zeros(self.nblocks, dtype=np.bool_) is_deleted[removed_blknos] = True new_blknos = np.empty(self.nblocks, dtype=np.int64) new_blknos.fill(-1) new_blknos[~is_deleted] = np.arange(self.nblocks - len(removed_blknos)) self._blknos = algos.take_1d(new_blknos, self._blknos, axis=0, allow_fill=False) self.blocks = tuple(blk for i, blk in enumerate(self.blocks) if i not in set(removed_blknos)) if unfit_val_locs: unfit_mgr_locs = np.concatenate(unfit_mgr_locs) unfit_count = len(unfit_mgr_locs) new_blocks = [] if value_is_extension_type: # This code (ab-)uses the fact that sparse blocks contain only # one item. new_blocks.extend( make_block(values=value.copy(), ndim=self.ndim, placement=slice(mgr_loc, mgr_loc + 1)) for mgr_loc in unfit_mgr_locs) self._blknos[unfit_mgr_locs] = (np.arange(unfit_count) + len(self.blocks)) self._blklocs[unfit_mgr_locs] = 0 else: # unfit_val_locs contains BlockPlacement objects unfit_val_items = unfit_val_locs[0].append(unfit_val_locs[1:]) new_blocks.append( make_block(values=value_getitem(unfit_val_items), ndim=self.ndim, placement=unfit_mgr_locs)) self._blknos[unfit_mgr_locs] = len(self.blocks) self._blklocs[unfit_mgr_locs] = np.arange(unfit_count) self.blocks += tuple(new_blocks) # Newly created block's dtype may already be present. self._known_consolidated = False def insert(self, loc, item, value, allow_duplicates=False): """ Insert item at selected position. Parameters ---------- loc : int item : hashable value : array_like allow_duplicates: bool If False, trying to insert non-unique item will raise """ if not allow_duplicates and item in self.items: # Should this be a different kind of error?? raise ValueError('cannot insert {}, already exists'.format(item)) if not isinstance(loc, int): raise TypeError("loc must be int") # insert to the axis; this could possibly raise a TypeError new_axis = self.items.insert(loc, item) block = make_block(values=value, ndim=self.ndim, placement=slice(loc, loc + 1)) for blkno, count in _fast_count_smallints(self._blknos[loc:]): blk = self.blocks[blkno] if count == len(blk.mgr_locs): blk.mgr_locs = blk.mgr_locs.add(1) else: new_mgr_locs = blk.mgr_locs.as_array.copy() new_mgr_locs[new_mgr_locs >= loc] += 1 blk.mgr_locs = new_mgr_locs if loc == self._blklocs.shape[0]: # np.append is a lot faster, let's use it if we can. self._blklocs = np.append(self._blklocs, 0) self._blknos = np.append(self._blknos, len(self.blocks)) else: self._blklocs = np.insert(self._blklocs, loc, 0) self._blknos = np.insert(self._blknos, loc, len(self.blocks)) self.axes[0] = new_axis self.blocks += (block,) self._shape = None self._known_consolidated = False if len(self.blocks) > 100: self._consolidate_inplace() def reindex_axis(self, new_index, axis, method=None, limit=None, fill_value=None, copy=True): """ Conform block manager to new index. """ new_index = ensure_index(new_index) new_index, indexer = self.axes[axis].reindex(new_index, method=method, limit=limit) return self.reindex_indexer(new_index, indexer, axis=axis, fill_value=fill_value, copy=copy) def reindex_indexer(self, new_axis, indexer, axis, fill_value=None, allow_dups=False, copy=True): """ Parameters ---------- new_axis : Index indexer : ndarray of int64 or None axis : int fill_value : object allow_dups : bool pandas-indexer with -1's only. """ if indexer is None: if new_axis is self.axes[axis] and not copy: return self result = self.copy(deep=copy) result.axes = list(self.axes) result.axes[axis] = new_axis return result self._consolidate_inplace() # some axes don't allow reindexing with dups if not allow_dups: self.axes[axis]._can_reindex(indexer) if axis >= self.ndim: raise IndexError("Requested axis not found in manager") if axis == 0: new_blocks = self._slice_take_blocks_ax0(indexer, fill_tuple=(fill_value,)) else: new_blocks = [blk.take_nd(indexer, axis=axis, fill_tuple=( fill_value if fill_value is not None else blk.fill_value,)) for blk in self.blocks] new_axes = list(self.axes) new_axes[axis] = new_axis return self.__class__(new_blocks, new_axes) def _slice_take_blocks_ax0(self, slice_or_indexer, fill_tuple=None): """ Slice/take blocks along axis=0. Overloaded for SingleBlock Returns ------- new_blocks : list of Block """ allow_fill = fill_tuple is not None sl_type, slobj, sllen = _preprocess_slice_or_indexer( slice_or_indexer, self.shape[0], allow_fill=allow_fill) if self._is_single_block: blk = self.blocks[0] if sl_type in ('slice', 'mask'): return [blk.getitem_block(slobj, new_mgr_locs=slice(0, sllen))] elif not allow_fill or self.ndim == 1: if allow_fill and fill_tuple[0] is None: _, fill_value = maybe_promote(blk.dtype) fill_tuple = (fill_value, ) return [blk.take_nd(slobj, axis=0, new_mgr_locs=slice(0, sllen), fill_tuple=fill_tuple)] if sl_type in ('slice', 'mask'): blknos = self._blknos[slobj] blklocs = self._blklocs[slobj] else: blknos = algos.take_1d(self._blknos, slobj, fill_value=-1, allow_fill=allow_fill) blklocs = algos.take_1d(self._blklocs, slobj, fill_value=-1, allow_fill=allow_fill) # When filling blknos, make sure blknos is updated before appending to # blocks list, that way new blkno is exactly len(blocks). # # FIXME: mgr_groupby_blknos must return mgr_locs in ascending order, # pytables serialization will break otherwise. blocks = [] for blkno, mgr_locs in libinternals.get_blkno_placements(blknos, self.nblocks, group=True): if blkno == -1: # If we've got here, fill_tuple was not None. fill_value = fill_tuple[0] blocks.append(self._make_na_block(placement=mgr_locs, fill_value=fill_value)) else: blk = self.blocks[blkno] # Otherwise, slicing along items axis is necessary. if not blk._can_consolidate: # A non-consolidatable block, it's easy, because there's # only one item and each mgr loc is a copy of that single # item. for mgr_loc in mgr_locs: newblk = blk.copy(deep=True) newblk.mgr_locs = slice(mgr_loc, mgr_loc + 1) blocks.append(newblk) else: blocks.append(blk.take_nd(blklocs[mgr_locs.indexer], axis=0, new_mgr_locs=mgr_locs, fill_tuple=None)) return blocks def _make_na_block(self, placement, fill_value=None): # TODO: infer dtypes other than float64 from fill_value if fill_value is None: fill_value = np.nan block_shape = list(self.shape) block_shape[0] = len(placement) dtype, fill_value = infer_dtype_from_scalar(fill_value) block_values = np.empty(block_shape, dtype=dtype) block_values.fill(fill_value) return make_block(block_values, placement=placement) def take(self, indexer, axis=1, verify=True, convert=True): """ Take items along any axis. """ self._consolidate_inplace() indexer = (np.arange(indexer.start, indexer.stop, indexer.step, dtype='int64') if isinstance(indexer, slice) else np.asanyarray(indexer, dtype='int64')) n = self.shape[axis] if convert: indexer = maybe_convert_indices(indexer, n) if verify: if ((indexer == -1) | (indexer >= n)).any(): raise Exception('Indices must be nonzero and less than ' 'the axis length') new_labels = self.axes[axis].take(indexer) return self.reindex_indexer(new_axis=new_labels, indexer=indexer, axis=axis, allow_dups=True) def merge(self, other, lsuffix='', rsuffix=''): # We assume at this point that the axes of self and other match. # This is only called from Panel.join, which reindexes prior # to calling to ensure this assumption holds. l, r = items_overlap_with_suffix(left=self.items, lsuffix=lsuffix, right=other.items, rsuffix=rsuffix) new_items = _concat_indexes([l, r]) new_blocks = [blk.copy(deep=False) for blk in self.blocks] offset = self.shape[0] for blk in other.blocks: blk = blk.copy(deep=False) blk.mgr_locs = blk.mgr_locs.add(offset) new_blocks.append(blk) new_axes = list(self.axes) new_axes[0] = new_items return self.__class__(_consolidate(new_blocks), new_axes) def equals(self, other): self_axes, other_axes = self.axes, other.axes if len(self_axes) != len(other_axes): return False if not all(ax1.equals(ax2) for ax1, ax2 in zip(self_axes, other_axes)): return False self._consolidate_inplace() other._consolidate_inplace() if len(self.blocks) != len(other.blocks): return False # canonicalize block order, using a tuple combining the type # name and then mgr_locs because there might be unconsolidated # blocks (say, Categorical) which can only be distinguished by # the iteration order def canonicalize(block): return (block.dtype.name, block.mgr_locs.as_array.tolist()) self_blocks = sorted(self.blocks, key=canonicalize) other_blocks = sorted(other.blocks, key=canonicalize) return all(block.equals(oblock) for block, oblock in zip(self_blocks, other_blocks)) def unstack(self, unstacker_func, fill_value): """Return a blockmanager with all blocks unstacked. Parameters ---------- unstacker_func : callable A (partially-applied) ``pd.core.reshape._Unstacker`` class. fill_value : Any fill_value for newly introduced missing values. Returns ------- unstacked : BlockManager """ n_rows = self.shape[-1] dummy = unstacker_func(np.empty((0, 0)), value_columns=self.items) new_columns = dummy.get_new_columns() new_index = dummy.get_new_index() new_blocks = [] columns_mask = [] for blk in self.blocks: blocks, mask = blk._unstack( partial(unstacker_func, value_columns=self.items[blk.mgr_locs.indexer]), new_columns, n_rows, fill_value ) new_blocks.extend(blocks) columns_mask.extend(mask) new_columns = new_columns[columns_mask] bm = BlockManager(new_blocks, [new_columns, new_index]) return bm class SingleBlockManager(BlockManager): """ manage a single block with """ ndim = 1 _is_consolidated = True _known_consolidated = True __slots__ = () def __init__(self, block, axis, do_integrity_check=False, fastpath=False): if isinstance(axis, list): if len(axis) != 1: raise ValueError("cannot create SingleBlockManager with more " "than 1 axis") axis = axis[0] # passed from constructor, single block, single axis if fastpath: self.axes = [axis] if isinstance(block, list): # empty block if len(block) == 0: block = [np.array([])] elif len(block) != 1: raise ValueError('Cannot create SingleBlockManager with ' 'more than 1 block') block = block[0] else: self.axes = [ensure_index(axis)] # create the block here if isinstance(block, list): # provide consolidation to the interleaved_dtype if len(block) > 1: dtype = _interleaved_dtype(block) block = [b.astype(dtype) for b in block] block = _consolidate(block) if len(block) != 1: raise ValueError('Cannot create SingleBlockManager with ' 'more than 1 block') block = block[0] if not isinstance(block, Block): block = make_block(block, placement=slice(0, len(axis)), ndim=1) self.blocks = [block] def _post_setstate(self): pass @property def _block(self): return self.blocks[0] @property def _values(self): return self._block.values @property def _blknos(self): """ compat with BlockManager """ return None @property def _blklocs(self): """ compat with BlockManager """ return None def get_slice(self, slobj, axis=0): if axis >= self.ndim: raise IndexError("Requested axis not found in manager") return self.__class__(self._block._slice(slobj), self.index[slobj], fastpath=True) @property def index(self): return self.axes[0] def convert(self, **kwargs): """ convert the whole block as one """ kwargs['by_item'] = False return self.apply('convert', **kwargs) @property def dtype(self): return self._block.dtype @property def array_dtype(self): return self._block.array_dtype @property def ftype(self): return self._block.ftype def get_dtype_counts(self): return {self.dtype.name: 1} def get_ftype_counts(self): return {self.ftype: 1} def get_dtypes(self): return np.array([self._block.dtype]) def get_ftypes(self): return np.array([self._block.ftype]) def external_values(self): return self._block.external_values() def internal_values(self): return self._block.internal_values() def formatting_values(self): """Return the internal values used by the DataFrame/SeriesFormatter""" return self._block.formatting_values() def get_values(self): """ return a dense type view """ return np.array(self._block.to_dense(), copy=False) @property def asobject(self): """ return a object dtype array. datetime/timedelta like values are boxed to Timestamp/Timedelta instances. """ return self._block.get_values(dtype=object) @property def _can_hold_na(self): return self._block._can_hold_na def is_consolidated(self): return True def _consolidate_check(self): pass def _consolidate_inplace(self): pass def delete(self, item): """ Delete single item from SingleBlockManager. Ensures that self.blocks doesn't become empty. """ loc = self.items.get_loc(item) self._block.delete(loc) self.axes[0] = self.axes[0].delete(loc) def fast_xs(self, loc): """ fast path for getting a cross-section return a view of the data """ return self._block.values[loc] def concat(self, to_concat, new_axis): """ Concatenate a list of SingleBlockManagers into a single SingleBlockManager. Used for pd.concat of Series objects with axis=0. Parameters ---------- to_concat : list of SingleBlockManagers new_axis : Index of the result Returns ------- SingleBlockManager """ non_empties = [x for x in to_concat if len(x) > 0] # check if all series are of the same block type: if len(non_empties) > 0: blocks = [obj.blocks[0] for obj in non_empties] if len({b.dtype for b in blocks}) == 1: new_block = blocks[0].concat_same_type(blocks) else: values = [x.values for x in blocks] values = _concat._concat_compat(values) new_block = make_block( values, placement=slice(0, len(values), 1)) else: values = [x._block.values for x in to_concat] values = _concat._concat_compat(values) new_block = make_block( values, placement=slice(0, len(values), 1)) mgr = SingleBlockManager(new_block, new_axis) return mgr # -------------------------------------------------------------------- # Constructor Helpers def create_block_manager_from_blocks(blocks, axes): try: if len(blocks) == 1 and not isinstance(blocks[0], Block): # if blocks[0] is of length 0, return empty blocks if not len(blocks[0]): blocks = [] else: # It's OK if a single block is passed as values, its placement # is basically "all items", but if there're many, don't bother # converting, it's an error anyway. blocks = [make_block(values=blocks[0], placement=slice(0, len(axes[0])))] mgr = BlockManager(blocks, axes) mgr._consolidate_inplace() return mgr except (ValueError) as e: blocks = [getattr(b, 'values', b) for b in blocks] tot_items = sum(b.shape[0] for b in blocks) construction_error(tot_items, blocks[0].shape[1:], axes, e) def create_block_manager_from_arrays(arrays, names, axes): try: blocks = form_blocks(arrays, names, axes) mgr = BlockManager(blocks, axes) mgr._consolidate_inplace() return mgr except ValueError as e: construction_error(len(arrays), arrays[0].shape, axes, e) def construction_error(tot_items, block_shape, axes, e=None): """ raise a helpful message about our construction """ passed = tuple(map(int, [tot_items] + list(block_shape))) # Correcting the user facing error message during dataframe construction if len(passed) <= 2: passed = passed[::-1] implied = tuple(len(ax) for ax in axes) # Correcting the user facing error message during dataframe construction if len(implied) <= 2: implied = implied[::-1] if passed == implied and e is not None: raise e if block_shape[0] == 0: raise ValueError("Empty data passed with indices specified.") raise ValueError("Shape of passed values is {0}, indices imply {1}".format( passed, implied)) # ----------------------------------------------------------------------- def form_blocks(arrays, names, axes): # put "leftover" items in float bucket, where else? # generalize? items_dict = defaultdict(list) extra_locs = [] names_idx = ensure_index(names) if names_idx.equals(axes[0]): names_indexer = np.arange(len(names_idx)) else: assert names_idx.intersection(axes[0]).is_unique names_indexer = names_idx.get_indexer_for(axes[0]) for i, name_idx in enumerate(names_indexer): if name_idx == -1: extra_locs.append(i) continue k = names[name_idx] v = arrays[name_idx] block_type = get_block_type(v) items_dict[block_type.__name__].append((i, k, v)) blocks = [] if len(items_dict['FloatBlock']): float_blocks = _multi_blockify(items_dict['FloatBlock']) blocks.extend(float_blocks) if len(items_dict['ComplexBlock']): complex_blocks = _multi_blockify(items_dict['ComplexBlock']) blocks.extend(complex_blocks) if len(items_dict['TimeDeltaBlock']): timedelta_blocks = _multi_blockify(items_dict['TimeDeltaBlock']) blocks.extend(timedelta_blocks) if len(items_dict['IntBlock']): int_blocks = _multi_blockify(items_dict['IntBlock']) blocks.extend(int_blocks) if len(items_dict['DatetimeBlock']): datetime_blocks = _simple_blockify(items_dict['DatetimeBlock'], _NS_DTYPE) blocks.extend(datetime_blocks) if len(items_dict['DatetimeTZBlock']): dttz_blocks = [make_block(array, klass=DatetimeTZBlock, placement=[i]) for i, _, array in items_dict['DatetimeTZBlock']] blocks.extend(dttz_blocks) if len(items_dict['BoolBlock']): bool_blocks = _simple_blockify(items_dict['BoolBlock'], np.bool_) blocks.extend(bool_blocks) if len(items_dict['ObjectBlock']) > 0: object_blocks = _simple_blockify(items_dict['ObjectBlock'], np.object_) blocks.extend(object_blocks) if len(items_dict['SparseBlock']) > 0: sparse_blocks = _sparse_blockify(items_dict['SparseBlock']) blocks.extend(sparse_blocks) if len(items_dict['CategoricalBlock']) > 0: cat_blocks = [make_block(array, klass=CategoricalBlock, placement=[i]) for i, _, array in items_dict['CategoricalBlock']] blocks.extend(cat_blocks) if len(items_dict['ExtensionBlock']): external_blocks = [ make_block(array, klass=ExtensionBlock, placement=[i]) for i, _, array in items_dict['ExtensionBlock'] ] blocks.extend(external_blocks) if len(items_dict['ObjectValuesExtensionBlock']): external_blocks = [ make_block(array, klass=ObjectValuesExtensionBlock, placement=[i]) for i, _, array in items_dict['ObjectValuesExtensionBlock'] ] blocks.extend(external_blocks) if len(extra_locs): shape = (len(extra_locs),) + tuple(len(x) for x in axes[1:]) # empty items -> dtype object block_values = np.empty(shape, dtype=object) block_values.fill(np.nan) na_block = make_block(block_values, placement=extra_locs) blocks.append(na_block) return blocks def _simple_blockify(tuples, dtype): """ return a single array of a block that has a single dtype; if dtype is not None, coerce to this dtype """ values, placement = _stack_arrays(tuples, dtype) # CHECK DTYPE? if dtype is not None and values.dtype != dtype: # pragma: no cover values = values.astype(dtype) block = make_block(values, placement=placement) return [block] def _multi_blockify(tuples, dtype=None): """ return an array of blocks that potentially have different dtypes """ # group by dtype grouper = itertools.groupby(tuples, lambda x: x[2].dtype) new_blocks = [] for dtype, tup_block in grouper: values, placement = _stack_arrays(list(tup_block), dtype) block = make_block(values, placement=placement) new_blocks.append(block) return new_blocks def _sparse_blockify(tuples, dtype=None): """ return an array of blocks that potentially have different dtypes (and are sparse) """ new_blocks = [] for i, names, array in tuples: array = _maybe_to_sparse(array) block = make_block(array, placement=[i]) new_blocks.append(block) return new_blocks def _stack_arrays(tuples, dtype): # fml def _asarray_compat(x): if isinstance(x, ABCSeries): return x._values else: return np.asarray(x) def _shape_compat(x): if isinstance(x, ABCSeries): return len(x), else: return x.shape placement, names, arrays = zip(*tuples) first = arrays[0] shape = (len(arrays),) + _shape_compat(first) stacked = np.empty(shape, dtype=dtype) for i, arr in enumerate(arrays): stacked[i] = _asarray_compat(arr) return stacked, placement def _interleaved_dtype(blocks): # type: (List[Block]) -> Optional[Union[np.dtype, ExtensionDtype]] """Find the common dtype for `blocks`. Parameters ---------- blocks : List[Block] Returns ------- dtype : Optional[Union[np.dtype, ExtensionDtype]] None is returned when `blocks` is empty. """ if not len(blocks): return None return find_common_type([b.dtype for b in blocks]) def _consolidate(blocks): """ Merge blocks having same dtype, exclude non-consolidating blocks """ # sort by _can_consolidate, dtype gkey = lambda x: x._consolidate_key grouper = itertools.groupby(sorted(blocks, key=gkey), gkey) new_blocks = [] for (_can_consolidate, dtype), group_blocks in grouper: merged_blocks = _merge_blocks(list(group_blocks), dtype=dtype, _can_consolidate=_can_consolidate) new_blocks = _extend_blocks(merged_blocks, new_blocks) return new_blocks def _compare_or_regex_search(a, b, regex=False): """ Compare two array_like inputs of the same shape or two scalar values Calls operator.eq or re.search, depending on regex argument. If regex is True, perform an element-wise regex matching. Parameters ---------- a : array_like or scalar b : array_like or scalar regex : bool, default False Returns ------- mask : array_like of bool """ if not regex: op = lambda x: operator.eq(x, b) else: op = np.vectorize(lambda x: bool(re.search(b, x)) if isinstance(x, str) else False) is_a_array = isinstance(a, np.ndarray) is_b_array = isinstance(b, np.ndarray) # numpy deprecation warning to have i8 vs integer comparisons if is_datetimelike_v_numeric(a, b): result = False # numpy deprecation warning if comparing numeric vs string-like elif is_numeric_v_string_like(a, b): result = False else: result = op(a) if is_scalar(result) and (is_a_array or is_b_array): type_names = [type(a).__name__, type(b).__name__] if is_a_array: type_names[0] = 'ndarray(dtype={dtype})'.format(dtype=a.dtype) if is_b_array: type_names[1] = 'ndarray(dtype={dtype})'.format(dtype=b.dtype) raise TypeError( "Cannot compare types {a!r} and {b!r}".format(a=type_names[0], b=type_names[1])) return result def _concat_indexes(indexes): return indexes[0].append(indexes[1:]) def items_overlap_with_suffix(left, lsuffix, right, rsuffix): """ If two indices overlap, add suffixes to overlapping entries. If corresponding suffix is empty, the entry is simply converted to string. """ to_rename = left.intersection(right) if len(to_rename) == 0: return left, right else: if not lsuffix and not rsuffix: raise ValueError('columns overlap but no suffix specified: ' '{rename}'.format(rename=to_rename)) def renamer(x, suffix): """Rename the left and right indices. If there is overlap, and suffix is not None, add suffix, otherwise, leave it as-is. Parameters ---------- x : original column name suffix : str or None Returns ------- x : renamed column name """ if x in to_rename and suffix is not None: return '{x}{suffix}'.format(x=x, suffix=suffix) return x lrenamer = partial(renamer, suffix=lsuffix) rrenamer = partial(renamer, suffix=rsuffix) return (_transform_index(left, lrenamer), _transform_index(right, rrenamer)) def _transform_index(index, func, level=None): """ Apply function to all values found in index. This includes transforming multiindex entries separately. Only apply function to one level of the MultiIndex if level is specified. """ if isinstance(index, MultiIndex): if level is not None: items = [tuple(func(y) if i == level else y for i, y in enumerate(x)) for x in index] else: items = [tuple(func(y) for y in x) for x in index] return MultiIndex.from_tuples(items, names=index.names) else: items = [func(x) for x in index] return Index(items, name=index.name, tupleize_cols=False) def _fast_count_smallints(arr): """Faster version of set(arr) for sequences of small numbers.""" counts = np.bincount(arr.astype(np.int_)) nz = counts.nonzero()[0] return np.c_[nz, counts[nz]] def _preprocess_slice_or_indexer(slice_or_indexer, length, allow_fill): if isinstance(slice_or_indexer, slice): return ('slice', slice_or_indexer, libinternals.slice_len(slice_or_indexer, length)) elif (isinstance(slice_or_indexer, np.ndarray) and slice_or_indexer.dtype == np.bool_): return 'mask', slice_or_indexer, slice_or_indexer.sum() else: indexer = np.asanyarray(slice_or_indexer, dtype=np.int64) if not allow_fill: indexer = maybe_convert_indices(indexer, length) return 'fancy', indexer, len(indexer) def concatenate_block_managers(mgrs_indexers, axes, concat_axis, copy): """ Concatenate block managers into one. Parameters ---------- mgrs_indexers : list of (BlockManager, {axis: indexer,...}) tuples axes : list of Index concat_axis : int copy : bool """ concat_plans = [get_mgr_concatenation_plan(mgr, indexers) for mgr, indexers in mgrs_indexers] concat_plan = combine_concat_plans(concat_plans, concat_axis) blocks = [] for placement, join_units in concat_plan: if len(join_units) == 1 and not join_units[0].indexers: b = join_units[0].block values = b.values if copy: values = values.copy() elif not copy: values = values.view() b = b.make_block_same_class(values, placement=placement) elif is_uniform_join_units(join_units): b = join_units[0].block.concat_same_type( [ju.block for ju in join_units], placement=placement) else: b = make_block( concatenate_join_units(join_units, concat_axis, copy=copy), placement=placement) blocks.append(b) return BlockManager(blocks, axes)
import numpy as np import pytest import pandas as pd from pandas.util import testing as tm class TestTimedeltaIndexing(object): def test_boolean_indexing(self): # GH 14946 df = pd.DataFrame({'x': range(10)}) df.index = pd.to_timedelta(range(10), unit='s') conditions = [df['x'] > 3, df['x'] == 3, df['x'] < 3] expected_data = [[0, 1, 2, 3, 10, 10, 10, 10, 10, 10], [0, 1, 2, 10, 4, 5, 6, 7, 8, 9], [10, 10, 10, 3, 4, 5, 6, 7, 8, 9]] for cond, data in zip(conditions, expected_data): result = df.assign(x=df.mask(cond, 10).astype('int64')) expected = pd.DataFrame(data, index=pd.to_timedelta(range(10), unit='s'), columns=['x'], dtype='int64') tm.assert_frame_equal(expected, result) @pytest.mark.parametrize( "indexer, expected", [(0, [20, 1, 2, 3, 4, 5, 6, 7, 8, 9]), (slice(4, 8), [0, 1, 2, 3, 20, 20, 20, 20, 8, 9]), ([3, 5], [0, 1, 2, 20, 4, 20, 6, 7, 8, 9])]) def test_list_like_indexing(self, indexer, expected): # GH 16637 df = pd.DataFrame({'x': range(10)}, dtype="int64") df.index = pd.to_timedelta(range(10), unit='s') df.loc[df.index[indexer], 'x'] = 20 expected = pd.DataFrame(expected, index=pd.to_timedelta(range(10), unit='s'), columns=['x'], dtype="int64") tm.assert_frame_equal(expected, df) def test_string_indexing(self): # GH 16896 df = pd.DataFrame({'x': range(3)}, index=pd.to_timedelta(range(3), unit='days')) expected = df.iloc[0] sliced = df.loc['0 days'] tm.assert_series_equal(sliced, expected) @pytest.mark.parametrize( "value", [None, pd.NaT, np.nan]) def test_masked_setitem(self, value): # issue (#18586) series = pd.Series([0, 1, 2], dtype='timedelta64[ns]') series[series == series[0]] = value expected = pd.Series([pd.NaT, 1, 2], dtype='timedelta64[ns]') tm.assert_series_equal(series, expected) @pytest.mark.parametrize( "value", [None, pd.NaT, np.nan]) def test_listlike_setitem(self, value): # issue (#18586) series = pd.Series([0, 1, 2], dtype='timedelta64[ns]') series.iloc[0] = value expected = pd.Series([pd.NaT, 1, 2], dtype='timedelta64[ns]') tm.assert_series_equal(series, expected) @pytest.mark.parametrize('start,stop, expected_slice', [ [np.timedelta64(0, 'ns'), None, slice(0, 11)], [np.timedelta64(1, 'D'), np.timedelta64(6, 'D'), slice(1, 7)], [None, np.timedelta64(4, 'D'), slice(0, 5)]]) def test_numpy_timedelta_scalar_indexing(self, start, stop, expected_slice): # GH 20393 s = pd.Series(range(11), pd.timedelta_range('0 days', '10 days')) result = s.loc[slice(start, stop)] expected = s.iloc[expected_slice] tm.assert_series_equal(result, expected) def test_roundtrip_thru_setitem(self): # PR 23462 dt1 = pd.Timedelta(0) dt2 = pd.Timedelta(28767471428571405) df = pd.DataFrame({'dt': pd.Series([dt1, dt2])}) df_copy = df.copy() s = pd.Series([dt1]) expected = df['dt'].iloc[1].value df.loc[[True, False]] = s result = df['dt'].iloc[1].value assert expected == result tm.assert_frame_equal(df, df_copy)
MJuddBooth/pandas
pandas/tests/indexing/test_timedelta.py
pandas/core/internals/managers.py
# -*- coding: utf-8 -*- from datetime import timedelta from pandas.compat import zip from pandas import compat import re import numpy as np from pandas.core.dtypes.generic import ABCSeries from pandas.core.dtypes.common import ( is_period_arraylike, is_timedelta64_dtype, is_datetime64_dtype) from pandas.tseries.offsets import DateOffset from pandas._libs.tslib import Timedelta import pandas._libs.tslibs.frequencies as libfreqs from pandas._libs.tslibs.frequencies import ( # noqa, semi-public API get_freq, get_base_alias, get_to_timestamp_base, get_freq_code, FreqGroup, is_subperiod, is_superperiod) from pandas._libs.tslibs.resolution import (Resolution, _FrequencyInferer, _TimedeltaFrequencyInferer) from pytz import AmbiguousTimeError RESO_NS = 0 RESO_US = 1 RESO_MS = 2 RESO_SEC = 3 RESO_MIN = 4 RESO_HR = 5 RESO_DAY = 6 # --------------------------------------------------------------------- # Offset names ("time rules") and related functions from pandas._libs.tslibs.offsets import _offset_to_period_map # noqa:E402 from pandas.tseries.offsets import (Nano, Micro, Milli, Second, # noqa Minute, Hour, Day, BDay, CDay, Week, MonthBegin, MonthEnd, BMonthBegin, BMonthEnd, QuarterBegin, QuarterEnd, BQuarterBegin, BQuarterEnd, YearBegin, YearEnd, BYearBegin, BYearEnd, prefix_mapping) try: cday = CDay() except NotImplementedError: cday = None #: cache of previously seen offsets _offset_map = {} def get_period_alias(offset_str): """ alias to closest period strings BQ->Q etc""" return _offset_to_period_map.get(offset_str, None) _name_to_offset_map = {'days': Day(1), 'hours': Hour(1), 'minutes': Minute(1), 'seconds': Second(1), 'milliseconds': Milli(1), 'microseconds': Micro(1), 'nanoseconds': Nano(1)} def to_offset(freq): """ Return DateOffset object from string or tuple representation or datetime.timedelta object Parameters ---------- freq : str, tuple, datetime.timedelta, DateOffset or None Returns ------- delta : DateOffset None if freq is None Raises ------ ValueError If freq is an invalid frequency See Also -------- pandas.DateOffset Examples -------- >>> to_offset('5min') <5 * Minutes> >>> to_offset('1D1H') <25 * Hours> >>> to_offset(('W', 2)) <2 * Weeks: weekday=6> >>> to_offset((2, 'B')) <2 * BusinessDays> >>> to_offset(datetime.timedelta(days=1)) <Day> >>> to_offset(Hour()) <Hour> """ if freq is None: return None if isinstance(freq, DateOffset): return freq if isinstance(freq, tuple): name = freq[0] stride = freq[1] if isinstance(stride, compat.string_types): name, stride = stride, name name, _ = libfreqs._base_and_stride(name) delta = get_offset(name) * stride elif isinstance(freq, timedelta): delta = None freq = Timedelta(freq) try: for name in freq.components._fields: offset = _name_to_offset_map[name] stride = getattr(freq.components, name) if stride != 0: offset = stride * offset if delta is None: delta = offset else: delta = delta + offset except Exception: raise ValueError(libfreqs._INVALID_FREQ_ERROR.format(freq)) else: delta = None stride_sign = None try: splitted = re.split(libfreqs.opattern, freq) if splitted[-1] != '' and not splitted[-1].isspace(): # the last element must be blank raise ValueError('last element must be blank') for sep, stride, name in zip(splitted[0::4], splitted[1::4], splitted[2::4]): if sep != '' and not sep.isspace(): raise ValueError('separator must be spaces') prefix = libfreqs._lite_rule_alias.get(name) or name if stride_sign is None: stride_sign = -1 if stride.startswith('-') else 1 if not stride: stride = 1 if prefix in Resolution._reso_str_bump_map.keys(): stride, name = Resolution.get_stride_from_decimal( float(stride), prefix ) stride = int(stride) offset = get_offset(name) offset = offset * int(np.fabs(stride) * stride_sign) if delta is None: delta = offset else: delta = delta + offset except Exception: raise ValueError(libfreqs._INVALID_FREQ_ERROR.format(freq)) if delta is None: raise ValueError(libfreqs._INVALID_FREQ_ERROR.format(freq)) return delta def get_offset(name): """ Return DateOffset object associated with rule name Examples -------- get_offset('EOM') --> BMonthEnd(1) """ if name not in libfreqs._dont_uppercase: name = name.upper() name = libfreqs._lite_rule_alias.get(name, name) name = libfreqs._lite_rule_alias.get(name.lower(), name) else: name = libfreqs._lite_rule_alias.get(name, name) if name not in _offset_map: try: split = name.split('-') klass = prefix_mapping[split[0]] # handles case where there's no suffix (and will TypeError if too # many '-') offset = klass._from_name(*split[1:]) except (ValueError, TypeError, KeyError): # bad prefix or suffix raise ValueError(libfreqs._INVALID_FREQ_ERROR.format(name)) # cache _offset_map[name] = offset # do not return cache because it's mutable return _offset_map[name].copy() getOffset = get_offset # --------------------------------------------------------------------- # Period codes def infer_freq(index, warn=True): """ Infer the most likely frequency given the input index. If the frequency is uncertain, a warning will be printed. Parameters ---------- index : DatetimeIndex or TimedeltaIndex if passed a Series will use the values of the series (NOT THE INDEX) warn : boolean, default True Returns ------- freq : string or None None if no discernible frequency TypeError if the index is not datetime-like ValueError if there are less than three values. """ import pandas as pd if isinstance(index, ABCSeries): values = index._values if not (is_datetime64_dtype(values) or is_timedelta64_dtype(values) or values.dtype == object): raise TypeError("cannot infer freq from a non-convertible dtype " "on a Series of {dtype}".format(dtype=index.dtype)) index = values if is_period_arraylike(index): raise TypeError("PeriodIndex given. Check the `freq` attribute " "instead of using infer_freq.") elif isinstance(index, pd.TimedeltaIndex): inferer = _TimedeltaFrequencyInferer(index, warn=warn) return inferer.get_freq() if isinstance(index, pd.Index) and not isinstance(index, pd.DatetimeIndex): if isinstance(index, (pd.Int64Index, pd.Float64Index)): raise TypeError("cannot infer freq from a non-convertible index " "type {type}".format(type=type(index))) index = index.values if not isinstance(index, pd.DatetimeIndex): try: index = pd.DatetimeIndex(index) except AmbiguousTimeError: index = pd.DatetimeIndex(index.asi8) inferer = _FrequencyInferer(index, warn=warn) return inferer.get_freq()
import warnings import pytest import numpy as np from datetime import timedelta import pandas as pd import pandas.util.testing as tm from pandas import (timedelta_range, date_range, Series, Timedelta, TimedeltaIndex, Index, DataFrame, Int64Index) from pandas.util.testing import (assert_almost_equal, assert_series_equal, assert_index_equal) from ..datetimelike import DatetimeLike randn = np.random.randn class TestTimedeltaIndex(DatetimeLike): _holder = TimedeltaIndex def setup_method(self, method): self.indices = dict(index=tm.makeTimedeltaIndex(10)) self.setup_indices() def create_index(self): return pd.to_timedelta(range(5), unit='d') + pd.offsets.Hour(1) def test_numeric_compat(self): # Dummy method to override super's version; this test is now done # in test_arithmetic.py pass def test_shift(self): pass # this is handled in test_arithmetic.py def test_pickle_compat_construction(self): pass def test_fillna_timedelta(self): # GH 11343 idx = pd.TimedeltaIndex(['1 day', pd.NaT, '3 day']) exp = pd.TimedeltaIndex(['1 day', '2 day', '3 day']) tm.assert_index_equal(idx.fillna(pd.Timedelta('2 day')), exp) exp = pd.TimedeltaIndex(['1 day', '3 hour', '3 day']) idx.fillna(pd.Timedelta('3 hour')) exp = pd.Index( [pd.Timedelta('1 day'), 'x', pd.Timedelta('3 day')], dtype=object) tm.assert_index_equal(idx.fillna('x'), exp) def test_difference_freq(self): # GH14323: Difference of TimedeltaIndex should not preserve frequency index = timedelta_range("0 days", "5 days", freq="D") other = timedelta_range("1 days", "4 days", freq="D") expected = TimedeltaIndex(["0 days", "5 days"], freq=None) idx_diff = index.difference(other) tm.assert_index_equal(idx_diff, expected) tm.assert_attr_equal('freq', idx_diff, expected) other = timedelta_range("2 days", "5 days", freq="D") idx_diff = index.difference(other) expected = TimedeltaIndex(["0 days", "1 days"], freq=None) tm.assert_index_equal(idx_diff, expected) tm.assert_attr_equal('freq', idx_diff, expected) def test_isin(self): index = tm.makeTimedeltaIndex(4) result = index.isin(index) assert result.all() result = index.isin(list(index)) assert result.all() assert_almost_equal(index.isin([index[2], 5]), np.array([False, False, True, False])) def test_factorize(self): idx1 = TimedeltaIndex(['1 day', '1 day', '2 day', '2 day', '3 day', '3 day']) exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp) exp_idx = TimedeltaIndex(['1 day', '2 day', '3 day']) arr, idx = idx1.factorize() tm.assert_numpy_array_equal(arr, exp_arr) tm.assert_index_equal(idx, exp_idx) arr, idx = idx1.factorize(sort=True) tm.assert_numpy_array_equal(arr, exp_arr) tm.assert_index_equal(idx, exp_idx) # freq must be preserved idx3 = timedelta_range('1 day', periods=4, freq='s') exp_arr = np.array([0, 1, 2, 3], dtype=np.intp) arr, idx = idx3.factorize() tm.assert_numpy_array_equal(arr, exp_arr) tm.assert_index_equal(idx, idx3) def test_join_self(self, join_type): index = timedelta_range('1 day', periods=10) joined = index.join(index, how=join_type) tm.assert_index_equal(index, joined) def test_does_not_convert_mixed_integer(self): df = tm.makeCustomDataframe(10, 10, data_gen_f=lambda *args, **kwargs: randn(), r_idx_type='i', c_idx_type='td') str(df) cols = df.columns.join(df.index, how='outer') joined = cols.join(df.columns) assert cols.dtype == np.dtype('O') assert cols.dtype == joined.dtype tm.assert_index_equal(cols, joined) def test_sort_values(self): idx = TimedeltaIndex(['4d', '1d', '2d']) ordered = idx.sort_values() assert ordered.is_monotonic ordered = idx.sort_values(ascending=False) assert ordered[::-1].is_monotonic ordered, dexer = idx.sort_values(return_indexer=True) assert ordered.is_monotonic tm.assert_numpy_array_equal(dexer, np.array([1, 2, 0]), check_dtype=False) ordered, dexer = idx.sort_values(return_indexer=True, ascending=False) assert ordered[::-1].is_monotonic tm.assert_numpy_array_equal(dexer, np.array([0, 2, 1]), check_dtype=False) def test_get_duplicates(self): idx = TimedeltaIndex(['1 day', '2 day', '2 day', '3 day', '3day', '4day']) with warnings.catch_warnings(record=True): # Deprecated - see GH20239 result = idx.get_duplicates() ex = TimedeltaIndex(['2 day', '3day']) tm.assert_index_equal(result, ex) def test_argmin_argmax(self): idx = TimedeltaIndex(['1 day 00:00:05', '1 day 00:00:01', '1 day 00:00:02']) assert idx.argmin() == 1 assert idx.argmax() == 0 def test_misc_coverage(self): rng = timedelta_range('1 day', periods=5) result = rng.groupby(rng.days) assert isinstance(list(result.values())[0][0], Timedelta) idx = TimedeltaIndex(['3d', '1d', '2d']) assert not idx.equals(list(idx)) non_td = Index(list('abc')) assert not idx.equals(list(non_td)) def test_map(self): # test_map_dictlike generally tests rng = timedelta_range('1 day', periods=10) f = lambda x: x.days result = rng.map(f) exp = Int64Index([f(x) for x in rng]) tm.assert_index_equal(result, exp) def test_pass_TimedeltaIndex_to_index(self): rng = timedelta_range('1 days', '10 days') idx = Index(rng, dtype=object) expected = Index(rng.to_pytimedelta(), dtype=object) tm.assert_numpy_array_equal(idx.values, expected.values) def test_pickle(self): rng = timedelta_range('1 days', periods=10) rng_p = tm.round_trip_pickle(rng) tm.assert_index_equal(rng, rng_p) def test_hash_error(self): index = timedelta_range('1 days', periods=10) with tm.assert_raises_regex(TypeError, "unhashable type: %r" % type(index).__name__): hash(index) def test_append_join_nondatetimeindex(self): rng = timedelta_range('1 days', periods=10) idx = Index(['a', 'b', 'c', 'd']) result = rng.append(idx) assert isinstance(result[0], Timedelta) # it works rng.join(idx, how='outer') def test_append_numpy_bug_1681(self): td = timedelta_range('1 days', '10 days', freq='2D') a = DataFrame() c = DataFrame({'A': 'foo', 'B': td}, index=td) str(c) result = a.append(c) assert (result['B'] == td).all() def test_fields(self): rng = timedelta_range('1 days, 10:11:12.100123456', periods=2, freq='s') tm.assert_index_equal(rng.days, Index([1, 1], dtype='int64')) tm.assert_index_equal( rng.seconds, Index([10 * 3600 + 11 * 60 + 12, 10 * 3600 + 11 * 60 + 13], dtype='int64')) tm.assert_index_equal( rng.microseconds, Index([100 * 1000 + 123, 100 * 1000 + 123], dtype='int64')) tm.assert_index_equal(rng.nanoseconds, Index([456, 456], dtype='int64')) pytest.raises(AttributeError, lambda: rng.hours) pytest.raises(AttributeError, lambda: rng.minutes) pytest.raises(AttributeError, lambda: rng.milliseconds) # with nat s = Series(rng) s[1] = np.nan tm.assert_series_equal(s.dt.days, Series([1, np.nan], index=[0, 1])) tm.assert_series_equal(s.dt.seconds, Series( [10 * 3600 + 11 * 60 + 12, np.nan], index=[0, 1])) # preserve name (GH15589) rng.name = 'name' assert rng.days.name == 'name' def test_freq_conversion(self): # doc example # series td = Series(date_range('20130101', periods=4)) - \ Series(date_range('20121201', periods=4)) td[2] += timedelta(minutes=5, seconds=3) td[3] = np.nan result = td / np.timedelta64(1, 'D') expected = Series([31, 31, (31 * 86400 + 5 * 60 + 3) / 86400.0, np.nan ]) assert_series_equal(result, expected) result = td.astype('timedelta64[D]') expected = Series([31, 31, 31, np.nan]) assert_series_equal(result, expected) result = td / np.timedelta64(1, 's') expected = Series([31 * 86400, 31 * 86400, 31 * 86400 + 5 * 60 + 3, np.nan]) assert_series_equal(result, expected) result = td.astype('timedelta64[s]') assert_series_equal(result, expected) # tdi td = TimedeltaIndex(td) result = td / np.timedelta64(1, 'D') expected = Index([31, 31, (31 * 86400 + 5 * 60 + 3) / 86400.0, np.nan]) assert_index_equal(result, expected) result = td.astype('timedelta64[D]') expected = Index([31, 31, 31, np.nan]) assert_index_equal(result, expected) result = td / np.timedelta64(1, 's') expected = Index([31 * 86400, 31 * 86400, 31 * 86400 + 5 * 60 + 3, np.nan]) assert_index_equal(result, expected) result = td.astype('timedelta64[s]') assert_index_equal(result, expected) class TestTimeSeries(object): def test_series_box_timedelta(self): rng = timedelta_range('1 day 1 s', periods=5, freq='h') s = Series(rng) assert isinstance(s[1], Timedelta) assert isinstance(s.iat[2], Timedelta)
louispotok/pandas
pandas/tests/indexes/timedeltas/test_timedelta.py
pandas/tseries/frequencies.py
""" Support for Sesame, by CANDY HOUSE. For more details about this platform, please refer to the documentation https://home-assistant.io/components/lock.sesame/ """ from typing import Callable import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.lock import LockDevice, PLATFORM_SCHEMA from homeassistant.const import ( ATTR_BATTERY_LEVEL, CONF_EMAIL, CONF_PASSWORD, STATE_LOCKED, STATE_UNLOCKED) from homeassistant.helpers.typing import ConfigType REQUIREMENTS = ['pysesame==0.1.0'] ATTR_DEVICE_ID = 'device_id' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_EMAIL): cv.string, vol.Required(CONF_PASSWORD): cv.string }) def setup_platform( hass, config: ConfigType, add_entities: Callable[[list], None], discovery_info=None): """Set up the Sesame platform.""" import pysesame email = config.get(CONF_EMAIL) password = config.get(CONF_PASSWORD) add_entities([SesameDevice(sesame) for sesame in pysesame.get_sesames(email, password)], update_before_add=True) class SesameDevice(LockDevice): """Representation of a Sesame device.""" def __init__(self, sesame: object) -> None: """Initialize the Sesame device.""" self._sesame = sesame # Cached properties from pysesame object. self._device_id = None self._nickname = None self._is_unlocked = False self._api_enabled = False self._battery = -1 @property def name(self) -> str: """Return the name of the device.""" return self._nickname @property def available(self) -> bool: """Return True if entity is available.""" return self._api_enabled @property def is_locked(self) -> bool: """Return True if the device is currently locked, else False.""" return not self._is_unlocked @property def state(self) -> str: """Get the state of the device.""" if self._is_unlocked: return STATE_UNLOCKED return STATE_LOCKED def lock(self, **kwargs) -> None: """Lock the device.""" self._sesame.lock() def unlock(self, **kwargs) -> None: """Unlock the device.""" self._sesame.unlock() def update(self) -> None: """Update the internal state of the device.""" self._sesame.update_state() self._nickname = self._sesame.nickname self._api_enabled = self._sesame.api_enabled self._is_unlocked = self._sesame.is_unlocked self._device_id = self._sesame.device_id self._battery = self._sesame.battery @property def device_state_attributes(self) -> dict: """Return the state attributes.""" attributes = {} attributes[ATTR_DEVICE_ID] = self._device_id attributes[ATTR_BATTERY_LEVEL] = self._battery return attributes
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
nugget/home-assistant
tests/components/updater/test_init.py
homeassistant/components/lock/sesame.py
"""Constants in smhi component.""" import logging from homeassistant.components.weather import DOMAIN as WEATHER_DOMAIN ATTR_SMHI_CLOUDINESS = 'cloudiness' DOMAIN = 'smhi' HOME_LOCATION_NAME = 'Home' ENTITY_ID_SENSOR_FORMAT = WEATHER_DOMAIN + ".smhi_{}" ENTITY_ID_SENSOR_FORMAT_HOME = ENTITY_ID_SENSOR_FORMAT.format( HOME_LOCATION_NAME) LOGGER = logging.getLogger('homeassistant.components.smhi')
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
nugget/home-assistant
tests/components/updater/test_init.py
homeassistant/components/smhi/const.py
""" Support for ANEL PwrCtrl switches. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.pwrctrl/ """ import logging import socket from datetime import timedelta import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA) from homeassistant.const import (CONF_HOST, CONF_PASSWORD, CONF_USERNAME) from homeassistant.util import Throttle REQUIREMENTS = ['anel_pwrctrl-homeassistant==0.0.1.dev2'] _LOGGER = logging.getLogger(__name__) CONF_PORT_RECV = 'port_recv' CONF_PORT_SEND = 'port_send' MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_PORT_RECV): cv.port, vol.Required(CONF_PORT_SEND): cv.port, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_HOST): cv.string, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up PwrCtrl devices/switches.""" host = config.get(CONF_HOST, None) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) port_recv = config.get(CONF_PORT_RECV) port_send = config.get(CONF_PORT_SEND) from anel_pwrctrl import DeviceMaster try: master = DeviceMaster( username=username, password=password, read_port=port_send, write_port=port_recv) master.query(ip_addr=host) except socket.error as ex: _LOGGER.error("Unable to discover PwrCtrl device: %s", str(ex)) return False devices = [] for device in master.devices.values(): parent_device = PwrCtrlDevice(device) devices.extend( PwrCtrlSwitch(switch, parent_device) for switch in device.switches.values() ) add_entities(devices) class PwrCtrlSwitch(SwitchDevice): """Representation of a PwrCtrl switch.""" def __init__(self, port, parent_device): """Initialize the PwrCtrl switch.""" self._port = port self._parent_device = parent_device @property def should_poll(self): """Return the polling state.""" return True @property def unique_id(self): """Return the unique ID of the device.""" return '{device}-{switch_idx}'.format( device=self._port.device.host, switch_idx=self._port.get_index() ) @property def name(self): """Return the name of the device.""" return self._port.label @property def is_on(self): """Return true if the device is on.""" return self._port.get_state() def update(self): """Trigger update for all switches on the parent device.""" self._parent_device.update() def turn_on(self, **kwargs): """Turn the switch on.""" self._port.on() def turn_off(self, **kwargs): """Turn the switch off.""" self._port.off() class PwrCtrlDevice: """Device representation for per device throttling.""" def __init__(self, device): """Initialize the PwrCtrl device.""" self._device = device @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Update the device and all its switches.""" self._device.update()
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
nugget/home-assistant
tests/components/updater/test_init.py
homeassistant/components/switch/anel_pwrctrl.py
"""Provide configuration end points for Automations.""" from collections import OrderedDict import uuid from homeassistant.components.config import EditIdBasedConfigView from homeassistant.const import CONF_ID, SERVICE_RELOAD from homeassistant.components.automation import DOMAIN, PLATFORM_SCHEMA import homeassistant.helpers.config_validation as cv CONFIG_PATH = 'automations.yaml' async def async_setup(hass): """Set up the Automation config API.""" async def hook(hass): """post_write_hook for Config View that reloads automations.""" await hass.services.async_call(DOMAIN, SERVICE_RELOAD) hass.http.register_view(EditAutomationConfigView( DOMAIN, 'config', CONFIG_PATH, cv.string, PLATFORM_SCHEMA, post_write_hook=hook )) return True class EditAutomationConfigView(EditIdBasedConfigView): """Edit automation config.""" def _write_value(self, hass, data, config_key, new_value): """Set value.""" index = None for index, cur_value in enumerate(data): # When people copy paste their automations to the config file, # they sometimes forget to add IDs. Fix it here. if CONF_ID not in cur_value: cur_value[CONF_ID] = uuid.uuid4().hex elif cur_value[CONF_ID] == config_key: break else: cur_value = OrderedDict() cur_value[CONF_ID] = config_key index = len(data) data.append(cur_value) # Iterate through some keys that we want to have ordered in the output updated_value = OrderedDict() for key in ('id', 'alias', 'trigger', 'condition', 'action'): if key in cur_value: updated_value[key] = cur_value[key] if key in new_value: updated_value[key] = new_value[key] # We cover all current fields above, but just in case we start # supporting more fields in the future. updated_value.update(cur_value) updated_value.update(new_value) data[index] = updated_value
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
nugget/home-assistant
tests/components/updater/test_init.py
homeassistant/components/config/automation.py
"""Support for IHC binary sensors.""" from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.components.ihc import IHC_CONTROLLER, IHC_DATA, IHC_INFO from homeassistant.components.ihc.const import CONF_INVERTING from homeassistant.components.ihc.ihcdevice import IHCDevice from homeassistant.const import CONF_TYPE DEPENDENCIES = ['ihc'] def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the IHC binary sensor platform.""" if discovery_info is None: return devices = [] for name, device in discovery_info.items(): ihc_id = device['ihc_id'] product_cfg = device['product_cfg'] product = device['product'] # Find controller that corresponds with device id ctrl_id = device['ctrl_id'] ihc_key = IHC_DATA.format(ctrl_id) info = hass.data[ihc_key][IHC_INFO] ihc_controller = hass.data[ihc_key][IHC_CONTROLLER] sensor = IHCBinarySensor( ihc_controller, name, ihc_id, info, product_cfg.get(CONF_TYPE), product_cfg[CONF_INVERTING], product) devices.append(sensor) add_entities(devices) class IHCBinarySensor(IHCDevice, BinarySensorDevice): """IHC Binary Sensor. The associated IHC resource can be any in or output from a IHC product or function block, but it must be a boolean ON/OFF resources. """ def __init__(self, ihc_controller, name, ihc_id: int, info: bool, sensor_type: str, inverting: bool, product=None) -> None: """Initialize the IHC binary sensor.""" super().__init__(ihc_controller, name, ihc_id, info, product) self._state = None self._sensor_type = sensor_type self.inverting = inverting @property def device_class(self): """Return the class of this sensor.""" return self._sensor_type @property def is_on(self): """Return true if the binary sensor is on/open.""" return self._state def on_ihc_change(self, ihc_id, value): """IHC resource has changed.""" if self.inverting: self._state = not value else: self._state = value self.schedule_update_ha_state()
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
nugget/home-assistant
tests/components/updater/test_init.py
homeassistant/components/ihc/binary_sensor.py
""" Support for Pilight binary sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.pilight/ """ import datetime import logging import voluptuous as vol from homeassistant.components import pilight from homeassistant.components.binary_sensor import ( PLATFORM_SCHEMA, BinarySensorDevice, ) from homeassistant.const import ( CONF_DISARM_AFTER_TRIGGER, CONF_NAME, CONF_PAYLOAD, CONF_PAYLOAD_OFF, CONF_PAYLOAD_ON ) from homeassistant.helpers import config_validation as cv from homeassistant.helpers.event import track_point_in_time from homeassistant.util import dt as dt_util _LOGGER = logging.getLogger(__name__) CONF_VARIABLE = 'variable' CONF_RESET_DELAY_SEC = 'reset_delay_sec' DEFAULT_NAME = 'Pilight Binary Sensor' DEPENDENCIES = ['pilight'] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_VARIABLE): cv.string, vol.Required(CONF_PAYLOAD): vol.Schema(dict), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PAYLOAD_ON, default='on'): vol.Any( cv.positive_int, cv.small_float, cv.string), vol.Optional(CONF_PAYLOAD_OFF, default='off'): vol.Any( cv.positive_int, cv.small_float, cv.string), vol.Optional(CONF_DISARM_AFTER_TRIGGER, default=False): cv.boolean, vol.Optional(CONF_RESET_DELAY_SEC, default=30): cv.positive_int }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up Pilight Binary Sensor.""" disarm = config.get(CONF_DISARM_AFTER_TRIGGER) if disarm: add_entities([PilightTriggerSensor( hass=hass, name=config.get(CONF_NAME), variable=config.get(CONF_VARIABLE), payload=config.get(CONF_PAYLOAD), on_value=config.get(CONF_PAYLOAD_ON), off_value=config.get(CONF_PAYLOAD_OFF), rst_dly_sec=config.get(CONF_RESET_DELAY_SEC), )]) else: add_entities([PilightBinarySensor( hass=hass, name=config.get(CONF_NAME), variable=config.get(CONF_VARIABLE), payload=config.get(CONF_PAYLOAD), on_value=config.get(CONF_PAYLOAD_ON), off_value=config.get(CONF_PAYLOAD_OFF), )]) class PilightBinarySensor(BinarySensorDevice): """Representation of a binary sensor that can be updated using Pilight.""" def __init__(self, hass, name, variable, payload, on_value, off_value): """Initialize the sensor.""" self._state = False self._hass = hass self._name = name self._variable = variable self._payload = payload self._on_value = on_value self._off_value = off_value hass.bus.listen(pilight.EVENT, self._handle_code) @property def name(self): """Return the name of the sensor.""" return self._name @property def is_on(self): """Return True if the binary sensor is on.""" return self._state def _handle_code(self, call): """Handle received code by the pilight-daemon. If the code matches the defined payload of this sensor the sensor state is changed accordingly. """ # Check if received code matches defined playoad # True if payload is contained in received code dict payload_ok = True for key in self._payload: if key not in call.data: payload_ok = False continue if self._payload[key] != call.data[key]: payload_ok = False # Read out variable if payload ok if payload_ok: if self._variable not in call.data: return value = call.data[self._variable] self._state = (value == self._on_value) self.schedule_update_ha_state() class PilightTriggerSensor(BinarySensorDevice): """Representation of a binary sensor that can be updated using Pilight.""" def __init__( self, hass, name, variable, payload, on_value, off_value, rst_dly_sec=30): """Initialize the sensor.""" self._state = False self._hass = hass self._name = name self._variable = variable self._payload = payload self._on_value = on_value self._off_value = off_value self._reset_delay_sec = rst_dly_sec self._delay_after = None self._hass = hass hass.bus.listen(pilight.EVENT, self._handle_code) @property def name(self): """Return the name of the sensor.""" return self._name @property def is_on(self): """Return True if the binary sensor is on.""" return self._state def _reset_state(self, call): self._state = False self._delay_after = None self.schedule_update_ha_state() def _handle_code(self, call): """Handle received code by the pilight-daemon. If the code matches the defined payload of this sensor the sensor state is changed accordingly. """ # Check if received code matches defined payload # True if payload is contained in received code dict payload_ok = True for key in self._payload: if key not in call.data: payload_ok = False continue if self._payload[key] != call.data[key]: payload_ok = False # Read out variable if payload ok if payload_ok: if self._variable not in call.data: return value = call.data[self._variable] self._state = (value == self._on_value) if self._delay_after is None: self._delay_after = dt_util.utcnow() + datetime.timedelta( seconds=self._reset_delay_sec) track_point_in_time( self._hass, self._reset_state, self._delay_after) self.schedule_update_ha_state()
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
nugget/home-assistant
tests/components/updater/test_init.py
homeassistant/components/pilight/binary_sensor.py
""" Support for an exposed aREST RESTful API of a device. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.arest/ """ import logging import requests import voluptuous as vol from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA) from homeassistant.const import (CONF_NAME, CONF_RESOURCE) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_FUNCTIONS = 'functions' CONF_PINS = 'pins' CONF_INVERT = 'invert' DEFAULT_NAME = 'aREST switch' PIN_FUNCTION_SCHEMA = vol.Schema({ vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_INVERT, default=False): cv.boolean, }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_RESOURCE): cv.url, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PINS, default={}): vol.Schema({cv.string: PIN_FUNCTION_SCHEMA}), vol.Optional(CONF_FUNCTIONS, default={}): vol.Schema({cv.string: PIN_FUNCTION_SCHEMA}), }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the aREST switches.""" resource = config.get(CONF_RESOURCE) try: response = requests.get(resource, timeout=10) except requests.exceptions.MissingSchema: _LOGGER.error("Missing resource or schema in configuration. " "Add http:// to your URL") return False except requests.exceptions.ConnectionError: _LOGGER.error("No route to device at %s", resource) return False dev = [] pins = config.get(CONF_PINS) for pinnum, pin in pins.items(): dev.append(ArestSwitchPin( resource, config.get(CONF_NAME, response.json()[CONF_NAME]), pin.get(CONF_NAME), pinnum, pin.get(CONF_INVERT))) functions = config.get(CONF_FUNCTIONS) for funcname, func in functions.items(): dev.append(ArestSwitchFunction( resource, config.get(CONF_NAME, response.json()[CONF_NAME]), func.get(CONF_NAME), funcname)) add_entities(dev) class ArestSwitchBase(SwitchDevice): """Representation of an aREST switch.""" def __init__(self, resource, location, name): """Initialize the switch.""" self._resource = resource self._name = '{} {}'.format(location.title(), name.title()) self._state = None self._available = True @property def name(self): """Return the name of the switch.""" return self._name @property def is_on(self): """Return true if device is on.""" return self._state @property def available(self): """Could the device be accessed during the last update call.""" return self._available class ArestSwitchFunction(ArestSwitchBase): """Representation of an aREST switch.""" def __init__(self, resource, location, name, func): """Initialize the switch.""" super().__init__(resource, location, name) self._func = func request = requests.get( '{}/{}'.format(self._resource, self._func), timeout=10) if request.status_code != 200: _LOGGER.error("Can't find function") return try: request.json()['return_value'] except KeyError: _LOGGER.error("No return_value received") except ValueError: _LOGGER.error("Response invalid") def turn_on(self, **kwargs): """Turn the device on.""" request = requests.get( '{}/{}'.format(self._resource, self._func), timeout=10, params={'params': '1'}) if request.status_code == 200: self._state = True else: _LOGGER.error( "Can't turn on function %s at %s", self._func, self._resource) def turn_off(self, **kwargs): """Turn the device off.""" request = requests.get( '{}/{}'.format(self._resource, self._func), timeout=10, params={'params': '0'}) if request.status_code == 200: self._state = False else: _LOGGER.error( "Can't turn off function %s at %s", self._func, self._resource) def update(self): """Get the latest data from aREST API and update the state.""" try: request = requests.get( '{}/{}'.format(self._resource, self._func), timeout=10) self._state = request.json()['return_value'] != 0 self._available = True except requests.exceptions.ConnectionError: _LOGGER.warning("No route to device %s", self._resource) self._available = False class ArestSwitchPin(ArestSwitchBase): """Representation of an aREST switch. Based on digital I/O.""" def __init__(self, resource, location, name, pin, invert): """Initialize the switch.""" super().__init__(resource, location, name) self._pin = pin self.invert = invert request = requests.get( '{}/mode/{}/o'.format(self._resource, self._pin), timeout=10) if request.status_code != 200: _LOGGER.error("Can't set mode") self._available = False def turn_on(self, **kwargs): """Turn the device on.""" turn_on_payload = int(not self.invert) request = requests.get( '{}/digital/{}/{}'.format(self._resource, self._pin, turn_on_payload), timeout=10) if request.status_code == 200: self._state = True else: _LOGGER.error( "Can't turn on pin %s at %s", self._pin, self._resource) def turn_off(self, **kwargs): """Turn the device off.""" turn_off_payload = int(self.invert) request = requests.get( '{}/digital/{}/{}'.format(self._resource, self._pin, turn_off_payload), timeout=10) if request.status_code == 200: self._state = False else: _LOGGER.error( "Can't turn off pin %s at %s", self._pin, self._resource) def update(self): """Get the latest data from aREST API and update the state.""" try: request = requests.get( '{}/digital/{}'.format(self._resource, self._pin), timeout=10) status_value = int(self.invert) self._state = request.json()['return_value'] != status_value self._available = True except requests.exceptions.ConnectionError: _LOGGER.warning("No route to device %s", self._resource) self._available = False
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
nugget/home-assistant
tests/components/updater/test_init.py
homeassistant/components/switch/arest.py
""" Support for Washington State Department of Transportation (WSDOT) data. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.wsdot/ """ import logging import re from datetime import datetime, timezone, timedelta import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_API_KEY, CONF_NAME, ATTR_ATTRIBUTION, CONF_ID, ATTR_NAME) from homeassistant.helpers.entity import Entity import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) ATTR_ACCESS_CODE = 'AccessCode' ATTR_AVG_TIME = 'AverageTime' ATTR_CURRENT_TIME = 'CurrentTime' ATTR_DESCRIPTION = 'Description' ATTR_TIME_UPDATED = 'TimeUpdated' ATTR_TRAVEL_TIME_ID = 'TravelTimeID' ATTRIBUTION = "Data provided by WSDOT" CONF_TRAVEL_TIMES = 'travel_time' ICON = 'mdi:car' RESOURCE = 'http://www.wsdot.wa.gov/Traffic/api/TravelTimes/' \ 'TravelTimesREST.svc/GetTravelTimeAsJson' SCAN_INTERVAL = timedelta(minutes=3) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_TRAVEL_TIMES): [{ vol.Required(CONF_ID): cv.string, vol.Optional(CONF_NAME): cv.string}] }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the WSDOT sensor.""" sensors = [] for travel_time in config.get(CONF_TRAVEL_TIMES): name = (travel_time.get(CONF_NAME) or travel_time.get(CONF_ID)) sensors.append( WashingtonStateTravelTimeSensor( name, config.get(CONF_API_KEY), travel_time.get(CONF_ID))) add_entities(sensors, True) class WashingtonStateTransportSensor(Entity): """ Sensor that reads the WSDOT web API. WSDOT provides ferry schedules, toll rates, weather conditions, mountain pass conditions, and more. Subclasses of this can read them and make them available. """ def __init__(self, name, access_code): """Initialize the sensor.""" self._data = {} self._access_code = access_code self._name = name self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def icon(self): """Icon to use in the frontend, if any.""" return ICON class WashingtonStateTravelTimeSensor(WashingtonStateTransportSensor): """Travel time sensor from WSDOT.""" def __init__(self, name, access_code, travel_time_id): """Construct a travel time sensor.""" self._travel_time_id = travel_time_id WashingtonStateTransportSensor.__init__(self, name, access_code) def update(self): """Get the latest data from WSDOT.""" params = { ATTR_ACCESS_CODE: self._access_code, ATTR_TRAVEL_TIME_ID: self._travel_time_id, } response = requests.get(RESOURCE, params, timeout=10) if response.status_code != 200: _LOGGER.warning("Invalid response from WSDOT API") else: self._data = response.json() self._state = self._data.get(ATTR_CURRENT_TIME) @property def device_state_attributes(self): """Return other details about the sensor state.""" if self._data is not None: attrs = {ATTR_ATTRIBUTION: ATTRIBUTION} for key in [ATTR_AVG_TIME, ATTR_NAME, ATTR_DESCRIPTION, ATTR_TRAVEL_TIME_ID]: attrs[key] = self._data.get(key) attrs[ATTR_TIME_UPDATED] = _parse_wsdot_timestamp( self._data.get(ATTR_TIME_UPDATED)) return attrs @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" return 'min' def _parse_wsdot_timestamp(timestamp): """Convert WSDOT timestamp to datetime.""" if not timestamp: return None # ex: Date(1485040200000-0800) milliseconds, tzone = re.search( r'Date\((\d+)([+-]\d\d)\d\d\)', timestamp).groups() return datetime.fromtimestamp( int(milliseconds) / 1000, tz=timezone(timedelta(hours=int(tzone))))
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
nugget/home-assistant
tests/components/updater/test_init.py
homeassistant/components/sensor/wsdot.py
"""Update the IP addresses of your Route53 DNS records.""" from datetime import timedelta import logging from typing import List import voluptuous as vol from homeassistant.const import CONF_DOMAIN, CONF_TTL, CONF_ZONE import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import track_time_interval REQUIREMENTS = ['boto3==1.9.16', 'ipify==1.0.0'] _LOGGER = logging.getLogger(__name__) CONF_ACCESS_KEY_ID = 'aws_access_key_id' CONF_SECRET_ACCESS_KEY = 'aws_secret_access_key' CONF_RECORDS = 'records' DOMAIN = 'route53' INTERVAL = timedelta(minutes=60) DEFAULT_TTL = 300 CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_ACCESS_KEY_ID): cv.string, vol.Required(CONF_DOMAIN): cv.string, vol.Required(CONF_RECORDS): vol.All(cv.ensure_list, [cv.string]), vol.Required(CONF_SECRET_ACCESS_KEY): cv.string, vol.Required(CONF_ZONE): cv.string, vol.Optional(CONF_TTL, default=DEFAULT_TTL): cv.positive_int, }) }, extra=vol.ALLOW_EXTRA) def setup(hass, config): """Set up the Route53 component.""" domain = config[DOMAIN][CONF_DOMAIN] records = config[DOMAIN][CONF_RECORDS] zone = config[DOMAIN][CONF_ZONE] aws_access_key_id = config[DOMAIN][CONF_ACCESS_KEY_ID] aws_secret_access_key = config[DOMAIN][CONF_SECRET_ACCESS_KEY] ttl = config[DOMAIN][CONF_TTL] def update_records_interval(now): """Set up recurring update.""" _update_route53( aws_access_key_id, aws_secret_access_key, zone, domain, records, ttl ) def update_records_service(now): """Set up service for manual trigger.""" _update_route53( aws_access_key_id, aws_secret_access_key, zone, domain, records, ttl ) track_time_interval(hass, update_records_interval, INTERVAL) hass.services.register(DOMAIN, 'update_records', update_records_service) return True def _update_route53( aws_access_key_id: str, aws_secret_access_key: str, zone: str, domain: str, records: List[str], ttl: int, ): import boto3 from ipify import get_ip from ipify import exceptions _LOGGER.debug("Starting update for zone %s", zone) client = boto3.client( DOMAIN, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, ) # Get the IP Address and build an array of changes try: ipaddress = get_ip() except exceptions.ConnectionError: _LOGGER.warning("Unable to reach the ipify service") return except exceptions.ServiceError: _LOGGER.warning("Unable to complete the ipfy request") return changes = [] for record in records: _LOGGER.debug("Processing record: %s", record) changes.append({ 'Action': 'UPSERT', 'ResourceRecordSet': { 'Name': '{}.{}'.format(record, domain), 'Type': 'A', 'TTL': ttl, 'ResourceRecords': [ {'Value': ipaddress}, ], } }) _LOGGER.debug("Submitting the following changes to Route53") _LOGGER.debug(changes) response = client.change_resource_record_sets( HostedZoneId=zone, ChangeBatch={'Changes': changes}) _LOGGER.debug("Response is %s", response) if response['ResponseMetadata']['HTTPStatusCode'] != 200: _LOGGER.warning(response)
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
nugget/home-assistant
tests/components/updater/test_init.py
homeassistant/components/route53/__init__.py
"""Support for the GPSLogger device tracking.""" import logging from homeassistant.components.device_tracker import DOMAIN as \ DEVICE_TRACKER_DOMAIN from homeassistant.components.gpslogger import DOMAIN as GPSLOGGER_DOMAIN, \ TRACKER_UPDATE from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.typing import HomeAssistantType _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['gpslogger'] DATA_KEY = '{}.{}'.format(GPSLOGGER_DOMAIN, DEVICE_TRACKER_DOMAIN) async def async_setup_entry(hass: HomeAssistantType, entry, async_see): """Configure a dispatcher connection based on a config entry.""" async def _set_location(device, gps_location, battery, accuracy, attrs): """Fire HA event to set location.""" await async_see( dev_id=device, gps=gps_location, battery=battery, gps_accuracy=accuracy, attributes=attrs ) hass.data[DATA_KEY] = async_dispatcher_connect( hass, TRACKER_UPDATE, _set_location ) return True async def async_unload_entry(hass: HomeAssistantType, entry): """Unload the config entry and remove the dispatcher connection.""" hass.data[DATA_KEY]() return True
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
nugget/home-assistant
tests/components/updater/test_init.py
homeassistant/components/gpslogger/device_tracker.py
"""Support for Google Calendar Search binary sensors.""" import logging from datetime import timedelta from homeassistant.components.calendar import CalendarEventDevice from homeassistant.components.google import ( CONF_CAL_ID, CONF_ENTITIES, CONF_TRACK, TOKEN_FILE, CONF_IGNORE_AVAILABILITY, CONF_SEARCH, GoogleCalendarService) from homeassistant.util import Throttle, dt _LOGGER = logging.getLogger(__name__) DEFAULT_GOOGLE_SEARCH_PARAMS = { 'orderBy': 'startTime', 'maxResults': 5, 'singleEvents': True, } MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15) def setup_platform(hass, config, add_entities, disc_info=None): """Set up the calendar platform for event devices.""" if disc_info is None: return if not any(data[CONF_TRACK] for data in disc_info[CONF_ENTITIES]): return calendar_service = GoogleCalendarService(hass.config.path(TOKEN_FILE)) add_entities([GoogleCalendarEventDevice(hass, calendar_service, disc_info[CONF_CAL_ID], data) for data in disc_info[CONF_ENTITIES] if data[CONF_TRACK]]) class GoogleCalendarEventDevice(CalendarEventDevice): """A calendar event device.""" def __init__(self, hass, calendar_service, calendar, data): """Create the Calendar event device.""" self.data = GoogleCalendarData(calendar_service, calendar, data.get(CONF_SEARCH), data.get(CONF_IGNORE_AVAILABILITY)) super().__init__(hass, data) async def async_get_events(self, hass, start_date, end_date): """Get all events in a specific time frame.""" return await self.data.async_get_events(hass, start_date, end_date) class GoogleCalendarData: """Class to utilize calendar service object to get next event.""" def __init__(self, calendar_service, calendar_id, search, ignore_availability): """Set up how we are going to search the google calendar.""" self.calendar_service = calendar_service self.calendar_id = calendar_id self.search = search self.ignore_availability = ignore_availability self.event = None def _prepare_query(self): # pylint: disable=import-error from httplib2 import ServerNotFoundError try: service = self.calendar_service.get() except ServerNotFoundError: _LOGGER.warning("Unable to connect to Google, using cached data") return False params = dict(DEFAULT_GOOGLE_SEARCH_PARAMS) params['calendarId'] = self.calendar_id if self.search: params['q'] = self.search return service, params async def async_get_events(self, hass, start_date, end_date): """Get all events in a specific time frame.""" service, params = await hass.async_add_job(self._prepare_query) params['timeMin'] = start_date.isoformat('T') params['timeMax'] = end_date.isoformat('T') events = await hass.async_add_job(service.events) result = await hass.async_add_job(events.list(**params).execute) items = result.get('items', []) event_list = [] for item in items: if (not self.ignore_availability and 'transparency' in item.keys()): if item['transparency'] == 'opaque': event_list.append(item) else: event_list.append(item) return event_list @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data.""" service, params = self._prepare_query() params['timeMin'] = dt.now().isoformat('T') events = service.events() result = events.list(**params).execute() items = result.get('items', []) new_event = None for item in items: if (not self.ignore_availability and 'transparency' in item.keys()): if item['transparency'] == 'opaque': new_event = item break else: new_event = item break self.event = new_event return True
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
nugget/home-assistant
tests/components/updater/test_init.py
homeassistant/components/google/calendar.py
""" Component to interface with various sensors that can be monitored. For more details about this component, please refer to the documentation at https://home-assistant.io/components/sensor/ """ from datetime import timedelta import logging import voluptuous as vol from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.config_validation import ( # noqa PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE) from homeassistant.const import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_TIMESTAMP, DEVICE_CLASS_PRESSURE) _LOGGER = logging.getLogger(__name__) DOMAIN = 'sensor' ENTITY_ID_FORMAT = DOMAIN + '.{}' SCAN_INTERVAL = timedelta(seconds=30) DEVICE_CLASSES = [ DEVICE_CLASS_BATTERY, # % of battery that is left DEVICE_CLASS_HUMIDITY, # % of humidity in the air DEVICE_CLASS_ILLUMINANCE, # current light level (lx/lm) DEVICE_CLASS_TEMPERATURE, # temperature (C/F) DEVICE_CLASS_TIMESTAMP, # timestamp (ISO8601) DEVICE_CLASS_PRESSURE, # pressure (hPa/mbar) ] DEVICE_CLASSES_SCHEMA = vol.All(vol.Lower, vol.In(DEVICE_CLASSES)) async def async_setup(hass, config): """Track states and offer events for sensors.""" component = hass.data[DOMAIN] = EntityComponent( _LOGGER, DOMAIN, hass, SCAN_INTERVAL) await component.async_setup(config) return True async def async_setup_entry(hass, entry): """Set up a config entry.""" return await hass.data[DOMAIN].async_setup_entry(entry) async def async_unload_entry(hass, entry): """Unload a config entry.""" return await hass.data[DOMAIN].async_unload_entry(entry)
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
nugget/home-assistant
tests/components/updater/test_init.py
homeassistant/components/sensor/__init__.py
""" Support for Pioneer Network Receivers. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.pioneer/ """ import logging import telnetlib import voluptuous as vol from homeassistant.components.media_player import ( MediaPlayerDevice, PLATFORM_SCHEMA) from homeassistant.components.media_player.const import ( SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET) from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PORT, CONF_TIMEOUT, STATE_OFF, STATE_ON) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'Pioneer AVR' DEFAULT_PORT = 23 # telnet default. Some Pioneer AVRs use 8102 DEFAULT_TIMEOUT = None SUPPORT_PIONEER = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \ SUPPORT_TURN_ON | SUPPORT_TURN_OFF | \ SUPPORT_SELECT_SOURCE | SUPPORT_PLAY MAX_VOLUME = 185 MAX_SOURCE_NUMBERS = 60 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.socket_timeout, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Pioneer platform.""" pioneer = PioneerDevice( config.get(CONF_NAME), config.get(CONF_HOST), config.get(CONF_PORT), config.get(CONF_TIMEOUT)) if pioneer.update(): add_entities([pioneer]) class PioneerDevice(MediaPlayerDevice): """Representation of a Pioneer device.""" def __init__(self, name, host, port, timeout): """Initialize the Pioneer device.""" self._name = name self._host = host self._port = port self._timeout = timeout self._pwstate = 'PWR1' self._volume = 0 self._muted = False self._selected_source = '' self._source_name_to_number = {} self._source_number_to_name = {} @classmethod def telnet_request(cls, telnet, command, expected_prefix): """Execute `command` and return the response.""" try: telnet.write(command.encode("ASCII") + b"\r") except telnetlib.socket.timeout: _LOGGER.debug("Pioneer command %s timed out", command) return None # The receiver will randomly send state change updates, make sure # we get the response we are looking for for _ in range(3): result = telnet.read_until(b"\r\n", timeout=0.2).decode("ASCII") \ .strip() if result.startswith(expected_prefix): return result return None def telnet_command(self, command): """Establish a telnet connection and sends command.""" try: try: telnet = telnetlib.Telnet( self._host, self._port, self._timeout) except (ConnectionRefusedError, OSError): _LOGGER.warning("Pioneer %s refused connection", self._name) return telnet.write(command.encode("ASCII") + b"\r") telnet.read_very_eager() # skip response telnet.close() except telnetlib.socket.timeout: _LOGGER.debug( "Pioneer %s command %s timed out", self._name, command) def update(self): """Get the latest details from the device.""" try: telnet = telnetlib.Telnet(self._host, self._port, self._timeout) except (ConnectionRefusedError, OSError): _LOGGER.warning("Pioneer %s refused connection", self._name) return False pwstate = self.telnet_request(telnet, "?P", "PWR") if pwstate: self._pwstate = pwstate volume_str = self.telnet_request(telnet, "?V", "VOL") self._volume = int(volume_str[3:]) / MAX_VOLUME if volume_str else None muted_value = self.telnet_request(telnet, "?M", "MUT") self._muted = (muted_value == "MUT0") if muted_value else None # Build the source name dictionaries if necessary if not self._source_name_to_number: for i in range(MAX_SOURCE_NUMBERS): result = self.telnet_request( telnet, "?RGB" + str(i).zfill(2), "RGB") if not result: continue source_name = result[6:] source_number = str(i).zfill(2) self._source_name_to_number[source_name] = source_number self._source_number_to_name[source_number] = source_name source_number = self.telnet_request(telnet, "?F", "FN") if source_number: self._selected_source = self._source_number_to_name \ .get(source_number[2:]) else: self._selected_source = None telnet.close() return True @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the state of the device.""" if self._pwstate == "PWR1": return STATE_OFF if self._pwstate == "PWR0": return STATE_ON return None @property def volume_level(self): """Volume level of the media player (0..1).""" return self._volume @property def is_volume_muted(self): """Boolean if volume is currently muted.""" return self._muted @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_PIONEER @property def source(self): """Return the current input source.""" return self._selected_source @property def source_list(self): """List of available input sources.""" return list(self._source_name_to_number.keys()) @property def media_title(self): """Title of current playing media.""" return self._selected_source def turn_off(self): """Turn off media player.""" self.telnet_command("PF") def volume_up(self): """Volume up media player.""" self.telnet_command("VU") def volume_down(self): """Volume down media player.""" self.telnet_command("VD") def set_volume_level(self, volume): """Set volume level, range 0..1.""" # 60dB max self.telnet_command(str(round(volume * MAX_VOLUME)).zfill(3) + "VL") def mute_volume(self, mute): """Mute (true) or unmute (false) media player.""" self.telnet_command("MO" if mute else "MF") def turn_on(self): """Turn the media player on.""" self.telnet_command("PO") def select_source(self, source): """Select input source.""" self.telnet_command(self._source_name_to_number.get(source) + "FN")
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
nugget/home-assistant
tests/components/updater/test_init.py
homeassistant/components/media_player/pioneer.py
"""Ibis configuration module.""" # This file has been adapted from pandas/core/config.py. pandas 3-clause BSD # license. See LICENSES/pandas # # Further modifications: # # Copyright 2014 Cloudera Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pprint import re import warnings from collections import namedtuple from contextlib import contextmanager from typing import Callable DeprecatedOption = namedtuple('DeprecatedOption', 'key msg rkey removal_ver') RegisteredOption = namedtuple( 'RegisteredOption', 'key defval doc validator cb' ) _deprecated_options = {} # holds deprecated option metdata _registered_options = {} # holds registered option metdata _global_config = {} # holds the current values for registered options _reserved_keys = ['all'] # keys which have a special meaning class OptionError(AttributeError, KeyError): """Exception for ibis.options. Backwards compatible with KeyError checks. """ pass # User API def _get_single_key(pat, silent): keys = _select_options(pat) if len(keys) == 0: if not silent: _warn_if_deprecated(pat) raise OptionError('No such keys(s): %r' % pat) if len(keys) > 1: raise OptionError('Pattern matched multiple keys') key = keys[0] if not silent: _warn_if_deprecated(key) key = _translate_key(key) return key def _get_option(pat, silent=False): key = _get_single_key(pat, silent) # walk the nested dict root, k = _get_root(key) return root[k] def _set_option(*args, **kwargs): # must at least 1 arg deal with constraints later nargs = len(args) if not nargs or nargs % 2 != 0: raise ValueError( "Must provide an even number of non-keyword " "arguments" ) # default to false silent = kwargs.get('silent', False) for k, v in zip(args[::2], args[1::2]): key = _get_single_key(k, silent) o = _get_registered_option(key) if o and o.validator: o.validator(v) # walk the nested dict root, k = _get_root(key) root[k] = v if o.cb: o.cb(key) def _describe_option(pat='', _print_desc=True): keys = _select_options(pat) if len(keys) == 0: raise OptionError('No such keys(s)') s = '' for k in keys: # filter by pat s += _build_option_description(k) if _print_desc: print(s) else: return s def _reset_option(pat, silent=False): keys = _select_options(pat) if len(keys) == 0: raise OptionError('No such keys(s)') if len(keys) > 1 and len(pat) < 4 and pat != 'all': raise ValueError( 'You must specify at least 4 characters when ' 'resetting multiple keys, use the special keyword ' '"all" to reset all the options to their default ' 'value' ) for k in keys: _set_option(k, _registered_options[k].defval, silent=silent) def get_default_val(pat): """Return the default value for given pattern. Parameters ---------- pat : string Returns ------- RegisteredOption (namedtuple) if key is deprecated, None otherwise """ key = _get_single_key(pat, silent=True) return _get_registered_option(key).defval class DictWrapper: """Provide attribute-style access to a nested dict.""" def __init__(self, d, prefix=""): object.__setattr__(self, "d", d) object.__setattr__(self, "prefix", prefix) def __repr__(self): """Return the dictionary as formatted string.""" return pprint.pformat(self.d) def __setattr__(self, key, val): """Set given value for the given attribute name (key). Parameters ---------- key : string val : object """ prefix = self.prefix if prefix: prefix += "." prefix += key # you can't set new keys and you can't overwrite subtrees if key in self.d and not isinstance(self.d[key], dict): _set_option(prefix, val) else: raise OptionError("You can only set the value of existing options") def __getattr__(self, key): """Get value for the given attribute name. Parameters ---------- key : str Returns ------- object """ prefix = self.prefix if prefix: prefix += "." prefix += key try: v = self.d[key] except KeyError as e: raise AttributeError(*e.args) if isinstance(v, dict): return DictWrapper(v, prefix) else: return _get_option(prefix) def __dir__(self): """Return all dictionary keys sorted.""" return sorted(self.d.keys()) class CallableDynamicDoc: """Convert __doc__ into a property function. For user convenience, we'd like to have the available options described in the docstring. For dev convenience we'd like to generate the docstrings dynamically instead of maintaining them by hand. To this, we use this class which wraps functions inside a callable, and converts __doc__ into a property function. The doctsrings below are templates using the py2.6+ advanced formatting syntax to plug in a concise list of options, and option descriptions. """ def __init__(self, func, doc_tmpl): self.__doc_tmpl__ = doc_tmpl self.__func__ = func def __call__(self, *args, **kwds): """Call the the function defined when the object was initialized.""" return self.__func__(*args, **kwds) @property def __doc__(self) -> str: """Create automatically a documentation using a template. Returns ------- string """ opts_desc = _describe_option('all', _print_desc=False) opts_list = pp_options_list(list(_registered_options.keys())) return self.__doc_tmpl__.format( opts_desc=opts_desc, opts_list=opts_list ) _get_option_tmpl = """ get_option(pat) Retrieves the value of the specified option. Available options: {opts_list} Parameters ---------- pat : str Regexp which should match a single option. Note: partial matches are supported for convenience, but unless you use the full option name (e.g. x.y.z.option_name), your code may break in future versions if new options with similar names are introduced. Returns ------- result : the value of the option Raises ------ OptionError : if no such option exists Notes ----- The available options with its descriptions: {opts_desc} """ _set_option_tmpl = """ set_option(pat, value) Sets the value of the specified option. Available options: {opts_list} Parameters ---------- pat : str Regexp which should match a single option. Note: partial matches are supported for convenience, but unless you use the full option name (e.g. x.y.z.option_name), your code may break in future versions if new options with similar names are introduced. value : new value of option. Returns ------- None Raises ------ OptionError if no such option exists Notes ----- The available options with its descriptions: {opts_desc} """ _describe_option_tmpl = """ describe_option(pat, _print_desc=False) Prints the description for one or more registered options. Call with not arguments to get a listing for all registered options. Available options: {opts_list} Parameters ---------- pat : str Regexp pattern. All matching keys will have their description displayed. _print_desc : bool, default True If True (default) the description(s) will be printed to stdout. Otherwise, the description(s) will be returned as a unicode string (for testing). Returns ------- None by default, the description(s) as a unicode string if _print_desc is False Notes ----- The available options with its descriptions: {opts_desc} """ _reset_option_tmpl = """ reset_option(pat) Reset one or more options to their default value. Pass "all" as argument to reset all options. Available options: {opts_list} Parameters ---------- pat : str/regex If specified only options matching `prefix*` will be reset. Note: partial matches are supported for convenience, but unless you use the full option name (e.g. x.y.z.option_name), your code may break in future versions if new options with similar names are introduced. Returns ------- None Notes ----- The available options with its descriptions: {opts_desc} """ # bind the functions with their docstrings into a Callable # and use that as the functions exposed in pd.api get_option = CallableDynamicDoc(_get_option, _get_option_tmpl) set_option = CallableDynamicDoc(_set_option, _set_option_tmpl) reset_option = CallableDynamicDoc(_reset_option, _reset_option_tmpl) describe_option = CallableDynamicDoc(_describe_option, _describe_option_tmpl) options = DictWrapper(_global_config) # # Functions for use by pandas developers, in addition to User - api class option_context: """ Context manager to temporarily set options in the `with` statement context. You need to invoke as ``option_context(pat, val, [(pat, val), ...])``. Examples -------- >>> with option_context('interactive', True): ... print(options.interactive) True >>> options.interactive False """ def __init__(self, *args): if not (len(args) % 2 == 0 and len(args) >= 2): raise ValueError( 'Need to invoke as' 'option_context(pat, val, [(pat, val), ...)).' ) self.ops = list(zip(args[::2], args[1::2])) def __enter__(self): """Create a backup of current options and define new ones.""" undo = [] for pat, val in self.ops: undo.append((pat, _get_option(pat, silent=True))) self.undo = undo for pat, val in self.ops: _set_option(pat, val, silent=True) def __exit__(self, *args): """Rollback the options values defined before `with` statement.""" if self.undo: for pat, val in self.undo: _set_option(pat, val, silent=True) def register_option(key, defval, doc='', validator=None, cb=None): """Register an option in the package-wide ibis config object. Parameters ---------- key a fully-qualified key, e.g. "x.y.option - z". defval the default value of the option doc a string description of the option validator a function of a single argument, should raise `ValueError` if called with a value which is not a legal value for the option. cb a function of a single argument "key", which is called immediately after an option value is set/reset. key is the full name of the option. Raises ------ ValueError if `validator` is specified and `defval` is not a valid value. """ import keyword import tokenize key = key.lower() if key in _registered_options: raise OptionError("Option '%s' has already been registered" % key) if key in _reserved_keys: raise OptionError("Option '%s' is a reserved key" % key) # the default value should be legal if validator: validator(defval) # walk the nested dict, creating dicts as needed along the path path = key.split('.') for k in path: if not bool(re.match('^' + tokenize.Name + '$', k)): raise ValueError("%s is not a valid identifier" % k) if keyword.iskeyword(k): raise ValueError("%s is a python keyword" % k) cursor = _global_config for i, p in enumerate(path[:-1]): if not isinstance(cursor, dict): raise OptionError( "Path prefix to option '%s' is already an option" % '.'.join(path[:i]) ) if p not in cursor: cursor[p] = {} cursor = cursor[p] if not isinstance(cursor, dict): raise OptionError( "Path prefix to option '%s' is already an option" % '.'.join(path[:-1]) ) cursor[path[-1]] = defval # initialize # save the option metadata _registered_options[key] = RegisteredOption( key=key, defval=defval, doc=doc, validator=validator, cb=cb ) def deprecate_option( key: str, msg: str = None, rkey: str = None, removal_ver: str = None ): """Mark option `key` as deprecated. If code attempts to access this option, a warning will be produced, using `msg` if given, or a default message if not. if `rkey` is given, any access to the key will be re-routed to `rkey`. Neither the existence of `key` nor that if `rkey` is checked. If they do not exist, any subsequence access will fail as usual, after the deprecation warning is given. Parameters ---------- key : string the name of the option to be deprecated. must be a fully-qualified option name (e.g "x.y.z.rkey"). msg : string, optional a warning message to output when the key is referenced. if no message is given a default message will be emitted. rkey : string, optional the name of an option to reroute access to. If specified, any referenced `key` will be re-routed to `rkey` including set/get/reset. rkey must be a fully-qualified option name (e.g "x.y.z.rkey"). used by the default message if no `msg` is specified. removal_ver : string, optional specifies the version in which this option will be removed. used by the default message if no `msg` is specified. Raises ------ OptionError - if key has already been deprecated. """ key = key.lower() if key in _deprecated_options: raise OptionError( "Option '%s' has already been defined as deprecated." % key ) _deprecated_options[key] = DeprecatedOption(key, msg, rkey, removal_ver) # functions internal to the module def _select_options(pat: str) -> list: """Return a list of keys matching `pat`. Parameters ---------- pat : string if pat=="all", returns all registered options Returns ------- list """ # short-circuit for exact key if pat in _registered_options: return [pat] # else look through all of them keys = sorted(_registered_options.keys()) if pat == 'all': # reserved key return keys return [k for k in keys if re.search(pat, k, re.I)] def _get_root(key: str) -> tuple: """Return the parent node of an option. Parameters ---------- key : string Returns ------- tuple """ path = key.split('.') cursor = _global_config for p in path[:-1]: cursor = cursor[p] return cursor, path[-1] def _is_deprecated(key: str) -> bool: """Check if the option is deprecated. Parameters ---------- key : string Returns ------- bool Return True if the given option has been deprecated """ key = key.lower() return key in _deprecated_options def _get_deprecated_option(key: str): """ Retrieve the metadata for a deprecated option, if `key` is deprecated. Parameters ---------- key : string Returns ------- DeprecatedOption (namedtuple) if key is deprecated, None otherwise """ try: d = _deprecated_options[key] except KeyError: return None else: return d def _get_registered_option(key: str): """ Retrieve the option metadata if `key` is a registered option. Parameters ---------- key : string Returns ------- RegisteredOption (namedtuple) if key is deprecated, None otherwise """ return _registered_options.get(key) def _translate_key(key: str): """Translate a key if necessary. If key id deprecated and a replacement key defined, will return the replacement key, otherwise returns `key` as - is Parameters ---------- key : string """ d = _get_deprecated_option(key) if d: return d.rkey or key else: return key def _warn_if_deprecated(key): """ Check if `key` is a deprecated option and if so, prints a warning. Returns ------- bool True if `key` is deprecated, False otherwise. """ d = _get_deprecated_option(key) if d: if d.msg: print(d.msg) warnings.warn(d.msg, DeprecationWarning) else: msg = "'%s' is deprecated" % key if d.removal_ver: msg += ' and will be removed in %s' % d.removal_ver if d.rkey: msg += ", please use '%s' instead." % d.rkey else: msg += ', please refrain from using it.' warnings.warn(msg, DeprecationWarning) return True return False def _build_option_description(k: str) -> str: """Build a formatted description of a registered option and prints it. Parameters ---------- k : string Returns ------- str """ o = _get_registered_option(k) d = _get_deprecated_option(k) buf = ['{} '.format(k)] if o.doc: doc = '\n'.join(o.doc.strip().splitlines()) else: doc = 'No description available.' buf.append(doc) if o: buf.append( '\n [default: {}] [currently: {}]'.format( o.defval, _get_option(k, True) ) ) if d: buf.append( '\n (Deprecated{})'.format( ', use `{}` instead.'.format(d.rkey) if d.rkey else '' ) ) buf.append('\n\n') return ''.join(buf) def pp_options_list(keys: str, width: int = 80, _print: bool = False) -> str: """ Build a concise listing of available options, grouped by prefix. Parameters ---------- keys : string width : int _print : bool Returns ------- string """ from itertools import groupby from textwrap import wrap def pp(name, ks): pfx = '- ' + name + '.[' if name else '' ls = wrap( ', '.join(ks), width, initial_indent=pfx, subsequent_indent=' ', break_long_words=False, ) if ls and ls[-1] and name: ls[-1] = ls[-1] + ']' return ls ls = [] singles = [x for x in sorted(keys) if x.find('.') < 0] if singles: ls += pp('', singles) keys = [x for x in keys if x.find('.') >= 0] for k, g in groupby(sorted(keys), lambda x: x[: x.rfind('.')]): ks = [x[len(k) + 1 :] for x in list(g)] ls += pp(k, ks) s = '\n'.join(ls) if _print: print(s) else: return s # helpers @contextmanager def config_prefix(prefix): """Create a Context Manager for multiple invocations using a common prefix. Context Manager for multiple invocations of API with a common prefix supported API functions: (register / get / set )__option Warning: This is not thread - safe, and won't work properly if you import the API functions into your module using the "from x import y" construct. Examples -------- import ibis.config as cf with cf.config_prefix("display.font"): cf.register_option("color", "red") cf.register_option("size", " 5 pt") cf.set_option(size, " 6 pt") cf.get_option(size) ... etc' will register options "display.font.color", "display.font.size", set the value of "display.font.size"... and so on. """ # Note: reset_option relies on set_option, and on key directly # it does not fit in to this monkey-patching scheme global register_option, get_option, set_option, reset_option def wrap(func): def inner(key, *args, **kwds): pkey = '%s.%s' % (prefix, key) return func(pkey, *args, **kwds) return inner _register_option = register_option _get_option = get_option _set_option = set_option set_option = wrap(set_option) get_option = wrap(get_option) register_option = wrap(register_option) yield None set_option = _set_option get_option = _get_option register_option = _register_option # These factories and methods are handy for use as the validator # arg in register_option def is_type_factory(_type) -> Callable: """Create a function that checks the type of an object. The function returned check if the type of a given object is the same of the type `_type` given to the function factory. Parameters ---------- _type a type to be compared against (e.g. type(x) == `_type`) Returns ------- validator : function a function of a single argument x , which returns the True if type(x) is equal to `_type`. """ # checking function def inner(x): """Check if the type of a given object is equals to the given type.""" if type(x) != _type: raise ValueError("Value must have type '%s'" % str(_type)) return inner def is_instance_factory(_type) -> Callable: """Create a function that checks if an object is instance of a given type. Parameters ---------- `_type` - the type to be checked against Returns ------- validator : function a function of a single argument x , which returns the True if x is an instance of `_type` """ if isinstance(_type, (tuple, list)): _type = tuple(_type) type_repr = "|".join(map(str, _type)) else: type_repr = "'%s'" % _type def inner(x): if not isinstance(x, _type): raise ValueError("Value must be an instance of %s" % type_repr) return inner def is_one_of_factory(legal_values: list) -> Callable: """ Create a function that check if a given value is in the given list. Parameters ---------- legal_values : list Returns ------- validator : function """ # checking function def inner(x): """ Check if the given value is in the list given to the factory function. Parameters ---------- x : object Raises ------ ValueError If the given value is not in the list given to the factory function. """ if x not in legal_values: pp_values = map(str, legal_values) raise ValueError( "Value must be one of %s" % str("|".join(pp_values)) ) return inner # common type validators, for convenience # usage: register_option(... , validator = is_int) is_int = is_type_factory(int) is_bool = is_type_factory(bool) is_float = is_type_factory(float) is_str = is_type_factory(str) is_text = is_instance_factory((str, bytes))
import pytest import ibis pytestmark = pytest.mark.spark def test_double_format(client): expr = ibis.literal(1.0) assert client.compile(expr) == 'SELECT 1.0d AS `tmp`' def test_float_format(client): expr = ibis.literal(1.0, type='float') assert client.compile(expr) == 'SELECT CAST(1.0 AS FLOAT) AS `tmp`'
cloudera/ibis
ibis/backends/spark/tests/test_numeric.py
ibis/config.py
"""The pandas client implementation.""" from __future__ import absolute_import import re from functools import partial import dateutil.parser import numpy as np import pandas as pd import pytz import toolz from multipledispatch import Dispatcher from pandas.api.types import CategoricalDtype, DatetimeTZDtype from pkg_resources import parse_version import ibis.client as client import ibis.common.exceptions as com import ibis.expr.datatypes as dt import ibis.expr.operations as ops import ibis.expr.schema as sch import ibis.expr.types as ir from .core import execute_and_reset infer_pandas_dtype = pd.api.types.infer_dtype _ibis_dtypes = toolz.valmap( np.dtype, { dt.Boolean: np.bool_, dt.Null: np.object_, dt.Array: np.object_, dt.String: np.object_, dt.Binary: np.object_, dt.Date: 'datetime64[ns]', dt.Time: 'timedelta64[ns]', dt.Timestamp: 'datetime64[ns]', dt.Int8: np.int8, dt.Int16: np.int16, dt.Int32: np.int32, dt.Int64: np.int64, dt.UInt8: np.uint8, dt.UInt16: np.uint16, dt.UInt32: np.uint32, dt.UInt64: np.uint64, dt.Float32: np.float32, dt.Float64: np.float64, dt.Decimal: np.object_, dt.Struct: np.object_, }, ) _numpy_dtypes = toolz.keymap( np.dtype, { 'bool': dt.boolean, 'int8': dt.int8, 'int16': dt.int16, 'int32': dt.int32, 'int64': dt.int64, 'uint8': dt.uint8, 'uint16': dt.uint16, 'uint32': dt.uint32, 'uint64': dt.uint64, 'float16': dt.float16, 'float32': dt.float32, 'float64': dt.float64, 'double': dt.double, 'unicode': dt.string, 'str': dt.string, 'datetime64': dt.timestamp, 'datetime64[ns]': dt.timestamp, 'timedelta64': dt.interval, 'timedelta64[ns]': dt.Interval('ns'), }, ) _inferable_pandas_dtypes = { 'boolean': dt.boolean, 'string': dt.string, 'unicode': dt.string, 'bytes': dt.string, 'empty': dt.string, } @dt.dtype.register(np.dtype) def from_numpy_dtype(value): try: return _numpy_dtypes[value] except KeyError: raise TypeError( 'numpy dtype {!r} is not supported in the pandas backend'.format( value ) ) @dt.dtype.register(DatetimeTZDtype) def from_pandas_tzdtype(value): return dt.Timestamp(timezone=str(value.tz)) @dt.dtype.register(CategoricalDtype) def from_pandas_categorical(value): return dt.Category() @dt.infer.register( (np.generic,) + tuple( frozenset( np.signedinteger.__subclasses__() + np.unsignedinteger.__subclasses__() # np.int64, np.uint64, etc. ) ) # we need this because in Python 2 int is a parent of np.integer ) def infer_numpy_scalar(value): return dt.dtype(value.dtype) @dt.infer.register(pd.Timestamp) def infer_pandas_timestamp(value): if value.tz is not None: return dt.Timestamp(timezone=str(value.tz)) else: return dt.timestamp @dt.infer.register(np.ndarray) def infer_array(value): # TODO(kszucs): infer series return dt.Array(dt.dtype(value.dtype.name)) @sch.schema.register(pd.Series) def schema_from_series(s): return sch.schema(tuple(s.iteritems())) @sch.infer.register(pd.DataFrame) def infer_pandas_schema(df, schema=None): schema = schema if schema is not None else {} pairs = [] for column_name, pandas_dtype in df.dtypes.iteritems(): if not isinstance(column_name, str): raise TypeError( 'Column names must be strings to use the pandas backend' ) if column_name in schema: ibis_dtype = dt.dtype(schema[column_name]) elif pandas_dtype == np.object_: inferred_dtype = infer_pandas_dtype(df[column_name], skipna=True) if inferred_dtype in {'mixed', 'decimal'}: # TODO: in principal we can handle decimal (added in pandas # 0.23) raise TypeError( 'Unable to infer type of column {0!r}. Try instantiating ' 'your table from the client with client.table(' "'my_table', schema={{{0!r}: <explicit type>}})".format( column_name ) ) ibis_dtype = _inferable_pandas_dtypes[inferred_dtype] else: ibis_dtype = dt.dtype(pandas_dtype) pairs.append((column_name, ibis_dtype)) return sch.schema(pairs) def ibis_dtype_to_pandas(ibis_dtype): """Convert ibis dtype to the pandas / numpy alternative""" assert isinstance(ibis_dtype, dt.DataType) if isinstance(ibis_dtype, dt.Timestamp) and ibis_dtype.timezone: return DatetimeTZDtype('ns', ibis_dtype.timezone) elif isinstance(ibis_dtype, dt.Interval): return np.dtype('timedelta64[{}]'.format(ibis_dtype.unit)) elif isinstance(ibis_dtype, dt.Category): return CategoricalDtype() elif type(ibis_dtype) in _ibis_dtypes: return _ibis_dtypes[type(ibis_dtype)] else: return np.dtype(np.object_) def ibis_schema_to_pandas(schema): return list(zip(schema.names, map(ibis_dtype_to_pandas, schema.types))) convert = Dispatcher( 'convert', doc="""\ Convert `column` to the pandas dtype corresponding to `out_dtype`, where the dtype of `column` is `in_dtype`. Parameters ---------- in_dtype : Union[np.dtype, pandas_dtype] The dtype of `column`, used for dispatching out_dtype : ibis.expr.datatypes.DataType The requested ibis type of the output column : pd.Series The column to convert Returns ------- result : pd.Series The converted column """, ) @convert.register(DatetimeTZDtype, dt.Timestamp, pd.Series) def convert_datetimetz_to_timestamp(in_dtype, out_dtype, column): output_timezone = out_dtype.timezone if output_timezone is not None: return column.dt.tz_convert(output_timezone) return column.astype(out_dtype.to_pandas(), errors='ignore') def convert_timezone(obj, timezone): """Convert `obj` to the timezone `timezone`. Parameters ---------- obj : datetime.date or datetime.datetime Returns ------- type(obj) """ if timezone is None: return obj.replace(tzinfo=None) return pytz.timezone(timezone).localize(obj) PANDAS_STRING_TYPES = {'string', 'unicode', 'bytes'} PANDAS_DATE_TYPES = {'datetime', 'datetime64', 'date'} @convert.register(np.dtype, dt.Timestamp, pd.Series) def convert_datetime64_to_timestamp(in_dtype, out_dtype, column): if in_dtype.type == np.datetime64: return column.astype(out_dtype.to_pandas(), errors='ignore') try: series = pd.to_datetime(column, utc=True) except pd.errors.OutOfBoundsDatetime: inferred_dtype = infer_pandas_dtype(column, skipna=True) if inferred_dtype in PANDAS_DATE_TYPES: # not great, but not really any other option return column.map( partial(convert_timezone, timezone=out_dtype.timezone) ) if inferred_dtype not in PANDAS_STRING_TYPES: raise TypeError( ( 'Conversion to timestamp not supported for Series of type ' '{!r}' ).format(inferred_dtype) ) return column.map(dateutil.parser.parse) else: utc_dtype = DatetimeTZDtype('ns', 'UTC') return series.astype(utc_dtype).dt.tz_convert(out_dtype.timezone) @convert.register(np.dtype, dt.Interval, pd.Series) def convert_any_to_interval(_, out_dtype, column): return column.values.astype(out_dtype.to_pandas()) @convert.register(np.dtype, dt.String, pd.Series) def convert_any_to_string(_, out_dtype, column): result = column.astype(out_dtype.to_pandas(), errors='ignore') return result @convert.register(np.dtype, dt.Boolean, pd.Series) def convert_boolean_to_series(in_dtype, out_dtype, column): # XXX: this is a workaround until #1595 can be addressed in_dtype_type = in_dtype.type out_dtype_type = out_dtype.to_pandas().type if in_dtype_type != np.object_ and in_dtype_type != out_dtype_type: return column.astype(out_dtype_type) return column @convert.register(object, dt.DataType, pd.Series) def convert_any_to_any(_, out_dtype, column): return column.astype(out_dtype.to_pandas(), errors='ignore') def ibis_schema_apply_to(schema, df): """Applies the Ibis schema to a pandas DataFrame Parameters ---------- schema : ibis.schema.Schema df : pandas.DataFrame Returns ------- df : pandas.DataFrame Notes ----- Mutates `df` """ for column, dtype in schema.items(): pandas_dtype = dtype.to_pandas() col = df[column] col_dtype = col.dtype try: not_equal = pandas_dtype != col_dtype except TypeError: # ugh, we can't compare dtypes coming from pandas, assume not equal not_equal = True if not_equal or isinstance(dtype, dt.String): df[column] = convert(col_dtype, dtype, col) return df dt.DataType.to_pandas = ibis_dtype_to_pandas sch.Schema.to_pandas = ibis_schema_to_pandas sch.Schema.apply_to = ibis_schema_apply_to class PandasTable(ops.DatabaseTable): pass class PandasClient(client.Client): dialect = None # defined in ibis.pandas.api def __init__(self, dictionary): self.dictionary = dictionary def table(self, name, schema=None): df = self.dictionary[name] schema = sch.infer(df, schema=schema) return PandasTable(name, schema, self).to_expr() def execute(self, query, params=None, limit='default', **kwargs): if limit != 'default': raise ValueError( 'limit parameter to execute is not yet implemented in the ' 'pandas backend' ) if not isinstance(query, ir.Expr): raise TypeError( "`query` has type {!r}, expected ibis.expr.types.Expr".format( type(query).__name__ ) ) return execute_and_reset(query, params=params, **kwargs) def compile(self, expr, *args, **kwargs): """Compile `expr`. Notes ----- For the pandas backend this is a no-op. """ return expr def database(self, name=None): """Construct a database called `name`.""" return PandasDatabase(name, self) def list_tables(self, like=None): """List the available tables.""" tables = list(self.dictionary.keys()) if like is not None: pattern = re.compile(like) return list(filter(lambda t: pattern.findall(t), tables)) return tables def load_data(self, table_name, obj, **kwargs): """Load data from `obj` into `table_name`. Parameters ---------- table_name : str obj : pandas.DataFrame """ # kwargs is a catch all for any options required by other backends. self.dictionary[table_name] = pd.DataFrame(obj) def create_table(self, table_name, obj=None, schema=None): """Create a table.""" if obj is None and schema is None: raise com.IbisError('Must pass expr or schema') if obj is not None: df = pd.DataFrame(obj) else: dtypes = ibis_schema_to_pandas(schema) df = schema.apply_to( pd.DataFrame(columns=list(map(toolz.first, dtypes))) ) self.dictionary[table_name] = df def get_schema(self, table_name, database=None): """Return a Schema object for the indicated table and database. Parameters ---------- table_name : str May be fully qualified database : str Returns ------- ibis.expr.schema.Schema """ return sch.infer(self.dictionary[table_name]) def exists_table(self, name): """Determine if the indicated table or view exists. Parameters ---------- name : str database : str Returns ------- bool """ return bool(self.list_tables(like=name)) @property def version(self) -> str: """Return the version of the underlying backend library.""" return parse_version(pd.__version__) class PandasDatabase(client.Database): pass
import pytest import ibis pytestmark = pytest.mark.spark def test_double_format(client): expr = ibis.literal(1.0) assert client.compile(expr) == 'SELECT 1.0d AS `tmp`' def test_float_format(client): expr = ibis.literal(1.0, type='float') assert client.compile(expr) == 'SELECT CAST(1.0 AS FLOAT) AS `tmp`'
cloudera/ibis
ibis/backends/spark/tests/test_numeric.py
ibis/backends/pandas/client.py
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module for signal management functionality.""" import asyncio from contextlib import ExitStack import os import platform import signal import socket import threading from typing import Callable from typing import Optional from typing import Tuple # noqa: F401 from typing import Union class AsyncSafeSignalManager: """ A context manager class for asynchronous handling of signals. Similar in purpose to :func:`asyncio.loop.add_signal_handler` but not limited to Unix platforms. Signal handlers can be registered at any time with a given manager. These will become active for the extent of said manager context. Unlike regular signal handlers, asynchronous signals handlers can safely interact with their event loop. The same manager can be used multiple consecutive times and even be nested with other managers, as these are independent from each other i.e. managers do not override each other's handlers. If used outside of the main thread, a ValueError is raised. The underlying mechanism is built around :func:`signal.set_wakeup_fd` so as to not interfere with regular handlers installed via :func:`signal.signal`. All signals received are forwarded to the previously setup file descriptor, if any. ..warning:: Within (potentially nested) contexts, :func:`signal.set_wakeup_fd` calls are intercepted such that the given file descriptor overrides the previously setup file descriptor for the outermost manager. This ensures the manager's chain of signal wakeup file descriptors is not broken by third-party code or by asyncio itself in some platforms. """ __current = None # type: AsyncSafeSignalManager __set_wakeup_fd = signal.set_wakeup_fd # type: Callable[[int], int] def __init__( self, loop: asyncio.AbstractEventLoop ): """ Instantiate manager. :param loop: event loop that will handle the signals. """ self.__parent = None # type: AsyncSafeSignalManager self.__loop = loop # type: asyncio.AbstractEventLoop self.__background_loop = None # type: Optional[asyncio.AbstractEventLoop] self.__handlers = {} # type: dict self.__prev_wakeup_handle = -1 # type: Union[int, socket.socket] self.__wsock = None self.__rsock = None self.__close_sockets = None def __enter__(self): pair = socket.socketpair() # type: Tuple[socket.socket, socket.socket] # noqa with ExitStack() as stack: self.__wsock = stack.enter_context(pair[0]) self.__rsock = stack.enter_context(pair[1]) self.__wsock.setblocking(False) self.__rsock.setblocking(False) self.__close_sockets = stack.pop_all().close self.__add_signal_readers() try: self.__install_signal_writers() except Exception: self.__remove_signal_readers() self.__close_sockets() self.__rsock = None self.__wsock = None self.__close_sockets = None raise self.__chain() return self def __exit__(self, exc_type, exc_value, exc_traceback): try: try: self.__uninstall_signal_writers() finally: self.__remove_signal_readers() finally: self.__unchain() self.__close_sockets() self.__rsock = None self.__wsock = None self.__close_sockets = None def __add_signal_readers(self): try: self.__loop.add_reader(self.__rsock.fileno(), self.__handle_signal) except NotImplementedError: # Some event loops, like the asyncio.ProactorEventLoop # on Windows, do not support asynchronous socket reads. # Emulate it. self.__background_loop = asyncio.SelectorEventLoop() self.__background_loop.add_reader( self.__rsock.fileno(), self.__loop.call_soon_threadsafe, self.__handle_signal) def run_background_loop(): asyncio.set_event_loop(self.__background_loop) self.__background_loop.run_forever() self.__background_thread = threading.Thread( target=run_background_loop, daemon=True) self.__background_thread.start() def __remove_signal_readers(self): if self.__background_loop: self.__background_loop.call_soon_threadsafe(self.__background_loop.stop) self.__background_thread.join() self.__background_loop.close() self.__background_loop = None else: self.__loop.remove_reader(self.__rsock.fileno()) def __install_signal_writers(self): prev_wakeup_handle = self.__set_wakeup_fd(self.__wsock.fileno()) try: self.__chain_wakeup_handle(prev_wakeup_handle) except Exception: own_wakeup_handle = self.__set_wakeup_fd(prev_wakeup_handle) assert self.__wsock.fileno() == own_wakeup_handle raise def __uninstall_signal_writers(self): prev_wakeup_handle = self.__chain_wakeup_handle(-1) own_wakeup_handle = self.__set_wakeup_fd(prev_wakeup_handle) assert self.__wsock.fileno() == own_wakeup_handle def __chain(self): self.__parent = AsyncSafeSignalManager.__current AsyncSafeSignalManager.__current = self if self.__parent is None: # Do not trust signal.set_wakeup_fd calls within context. # Overwrite handle at the start of the managers' chain. def modified_set_wakeup_fd(signum): if threading.current_thread() is not threading.main_thread(): raise ValueError( 'set_wakeup_fd only works in main' ' thread of the main interpreter' ) return self.__chain_wakeup_handle(signum) signal.set_wakeup_fd = modified_set_wakeup_fd def __unchain(self): if self.__parent is None: signal.set_wakeup_fd = self.__set_wakeup_fd AsyncSafeSignalManager.__current = self.__parent def __chain_wakeup_handle(self, wakeup_handle): prev_wakeup_handle = self.__prev_wakeup_handle if isinstance(prev_wakeup_handle, socket.socket): # Detach (Windows) socket and retrieve the raw OS handle. prev_wakeup_handle = prev_wakeup_handle.detach() if wakeup_handle != -1 and platform.system() == 'Windows': # On Windows, os.write will fail on a WinSock handle. There is no WinSock API # in the standard library either. Thus we wrap it in a socket.socket instance. try: wakeup_handle = socket.socket(fileno=wakeup_handle) except WindowsError as e: if e.winerror != 10038: # WSAENOTSOCK raise self.__prev_wakeup_handle = wakeup_handle return prev_wakeup_handle def __handle_signal(self): while True: try: data = self.__rsock.recv(4096) if not data: break for signum in data: if signum not in self.__handlers: continue self.__handlers[signum](signum) if self.__prev_wakeup_handle != -1: # Send over (Windows) socket or write file. if isinstance(self.__prev_wakeup_handle, socket.socket): self.__prev_wakeup_handle.send(data) else: os.write(self.__prev_wakeup_handle, data) except InterruptedError: continue except BlockingIOError: break def handle( self, signum: Union[signal.Signals, int], handler: Optional[Callable[[int], None]], ) -> Optional[Callable[[int], None]]: """ Register a callback for asynchronous handling of a given signal. :param signum: number of the signal to be handled :param handler: callback taking a signal number as its sole argument, or None :return: previous handler if any, otherwise None """ signum = signal.Signals(signum) if handler is not None: if not callable(handler): raise ValueError('signal handler must be a callable') old_handler = self.__handlers.get(signum, None) self.__handlers[signum] = handler else: old_handler = self.__handlers.pop(signum, None) return old_handler
# Copyright 2019 Apex.AI, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import unittest import ament_index_python import launch import launch.actions import launch_testing import launch_testing.actions from launch_testing.asserts import assertSequentialStdout import pytest def get_test_process_action(): TEST_PROC_PATH = os.path.join( ament_index_python.get_package_prefix('launch_testing'), 'lib/launch_testing', 'good_proc' ) return launch.actions.ExecuteProcess( cmd=[sys.executable, TEST_PROC_PATH], name='good_proc', # This is necessary to get unbuffered output from the process under test additional_env={'PYTHONUNBUFFERED': '1'}, ) # This launch description shows the prefered way to let the tests access launch actions. By # adding them to the test context, it's not necessary to scope them at the module level like in # the good_proc.test.py example @pytest.mark.launch_test def generate_test_description(): dut_process = get_test_process_action() ld = launch.LaunchDescription([ dut_process, # Start tests right away - no need to wait for anything launch_testing.actions.ReadyToTest(), ]) # Items in this dictionary will be added to the test cases as an attribute based on # dictionary key test_context = { 'dut': dut_process, 'int_val': 10 } return ld, test_context class TestProcOutput(unittest.TestCase): def test_process_output(self, launch_service, proc_info, proc_output, dut): # We can use the 'dut' argument here because it's part of the test context # returned by `generate_test_description` It's not necessary for every # test to use every piece of the context proc_output.assertWaitFor('Loop 1', process=dut, timeout=10, stream='stdout') @launch_testing.post_shutdown_test() class TestProcessOutput(unittest.TestCase): def test_full_output(self, proc_output, dut): # Same as the test_process_output test. launch_testing binds the value of # 'dut' from the test_context to the test before it runs with assertSequentialStdout(proc_output, process=dut) as cm: cm.assertInStdout('Starting Up') if os.name != 'nt': # On Windows, process termination is always forced # and thus the last print in good proc never makes it. cm.assertInStdout('Shutting Down') def test_int_val(self, int_val): # Arguments don't have to be part of the LaunchDescription. Any object can # be passed in self.assertEqual(int_val, 10) def test_all_context_objects(self, int_val, dut): # Multiple arguments are supported self.assertEqual(int_val, 10) self.assertIn('good_proc', dut.process_details['name']) def test_all_context_objects_different_order(self, dut, int_val): # Put the arguments in a different order from the above test self.assertEqual(int_val, 10) self.assertIn('good_proc', dut.process_details['name'])
ros2/launch
launch_testing/test/launch_testing/examples/context_launch_test.py
launch/launch/utilities/signal_management.py
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. Naming Conventions ================== registry.somewhere/namespace/image_name:tag |-----------------| registry, reg_uri |---------| namespace |--------------------------------------| repository |--------------------| image name |--| tag |------------------------| image |------------------------------------------| image I've tried to be as much consistent (man pages were source) with docker as possible """ import os import shutil import logging import tempfile import json import docker from docker.errors import APIError from atomic_reactor.constants import CONTAINER_SHARE_PATH, CONTAINER_SHARE_SOURCE_SUBDIR,\ BUILD_JSON, DOCKER_SOCKET_PATH from atomic_reactor.source import get_source_instance_for from atomic_reactor.util import ImageName, wait_for_command, clone_git_repo, figure_out_dockerfile logger = logging.getLogger(__name__) class LastLogger(object): """ provide method for getting last log """ def __init__(self): self._last_logs = [] @property def last_logs(self): """ logs from last operation """ return self._last_logs @last_logs.setter def last_logs(self, value): self._last_logs = value class BuildContainerFactory(object): """ set of methods for building images inside containers """ def __init__(self): self.tasker = DockerTasker() def _check_build_input(self, image, args_path): """ Internal method, validate provided args. :param image: str :param args_path: str, path dir which is mounter inside container :return: None :raises RuntimeError """ try: with open(os.path.join(args_path, BUILD_JSON)) as json_args: logger.debug("build input: image = '%s', args = '%s'", image, json_args.read()) except (IOError, OSError) as ex: logger.error("unable to open json arguments: '%s'", repr(ex)) raise RuntimeError("Unable to open json arguments: '%s'" % repr(ex)) if not self.tasker.image_exists(image): logger.error("provided build image doesn't exist: '%s'", image) raise RuntimeError("Provided build image doesn't exist: '%s'" % image) def _obtain_source_from_path_if_needed(self, local_path, container_path=CONTAINER_SHARE_PATH): # TODO: maybe we should do this for any provider? (if we expand to various providers # like mercurial, we don't to force container to have mercurial installed, etc.) build_json_path = os.path.join(local_path, BUILD_JSON) with open(build_json_path, 'r') as fp: build_json = json.load(fp) source = get_source_instance_for(build_json['source'], tmpdir=local_path) if source.provider == 'path': logger.debug('copying source from %s to %s', source.schemeless_path, local_path) source.get() logger.debug('verifying that %s exists: %s', local_path, os.path.exists(local_path)) # now modify the build json build_json['source']['uri'] =\ 'file://' + os.path.join(container_path, CONTAINER_SHARE_SOURCE_SUBDIR) with open(build_json_path, 'w') as fp: json.dump(build_json, fp) # else we do nothing def build_image_dockerhost(self, build_image, json_args_path): """ Build docker image within a build image using docker from host (mount docker socket inside container). There are possible races here. Use wisely. This operation is asynchronous and you should wait for container to finish. :param build_image: str, name of image where build is performed :param json_args_path: str, this dir is mounted inside build container and used as a way to transport data between host and buildroot; there has to be a file inside this dir with name atomic_reactor.BUILD_JSON which is used to feed build :return: str, container id """ logger.info("building image '%s' in container using docker from host", build_image) self._check_build_input(build_image, json_args_path) self._obtain_source_from_path_if_needed(json_args_path, CONTAINER_SHARE_PATH) if not os.path.exists(DOCKER_SOCKET_PATH): logger.error("looks like docker is not running because there is no socket at: %s", DOCKER_SOCKET_PATH) raise RuntimeError("docker socket not found: %s" % DOCKER_SOCKET_PATH) volume_bindings = { DOCKER_SOCKET_PATH: { 'bind': DOCKER_SOCKET_PATH, 'ro': True, }, json_args_path: { 'bind': CONTAINER_SHARE_PATH, 'rw': True, }, } logger.debug('build json mounted in container: %s', open(os.path.join(json_args_path, BUILD_JSON)).read()) container_id = self.tasker.run( ImageName.parse(build_image), create_kwargs={'volumes': [DOCKER_SOCKET_PATH, json_args_path]}, start_kwargs={'binds': volume_bindings}, ) return container_id def build_image_privileged_container(self, build_image, json_args_path): """ build image inside privileged container: this will run another docker instance inside This operation is asynchronous and you should wait for container to finish. :param build_image: str, name of image where build is performed :param json_args_path: str, this dir is mounted inside build container and used as a way to transport data between host and buildroot; there has to be a file inside this dir with name atomic_reactor.BUILD_JSON which is used to feed build :return: dict, keys container_id and stream """ logger.info("building image '%s' inside privileged container", build_image) self._check_build_input(build_image, json_args_path) self._obtain_source_from_path_if_needed(json_args_path, CONTAINER_SHARE_PATH) logger.debug('build json mounted in container: %s', open(os.path.join(json_args_path, BUILD_JSON)).read()) container_id = self.tasker.run( ImageName.parse(build_image), create_kwargs={'volumes': [json_args_path]}, start_kwargs={'binds': {json_args_path: {'bind': CONTAINER_SHARE_PATH, 'rw': True}}, 'privileged': True} ) return container_id class DockerTasker(LastLogger): def __init__(self, base_url=None, **kwargs): super(DockerTasker, self).__init__(**kwargs) if base_url: self.d = docker.Client(base_url=base_url) elif os.environ.get('DOCKER_CONNECTION'): self.d = docker.Client(base_url=os.environ['DOCKER_CONNECTION']) else: self.d = docker.Client() def build_image_from_path(self, path, image, stream=False, use_cache=False, remove_im=True): """ build image from provided path and tag it this operation is asynchronous and you should consume returned generator in order to wait for build to finish :param path: str :param image: ImageName, name of the resulting image :param stream: bool, True returns generator, False returns str :param use_cache: bool, True if you want to use cache :param remove_im: bool, remove intermediate containers produced during docker build :return: generator """ logger.info("building image '%s' from path '%s'", image, path) try: response = self.d.build(path=path, tag=image.to_str(), stream=stream, nocache=not use_cache, rm=remove_im, pull=False) # returns generator except TypeError: # because changing api is fun response = self.d.build(path=path, tag=image.to_str(), stream=stream, nocache=not use_cache, rm=remove_im) # returns generator return response def build_image_from_git(self, url, image, git_path=None, git_commit=None, copy_dockerfile_to=None, stream=False, use_cache=False): """ build image from provided url and tag it this operation is asynchronous and you should consume returned generator in order to wait for build to finish :param url: str :param image: ImageName, name of the resulting image :param git_path: str, path to dockerfile within gitrepo :param copy_dockerfile_to: str, copy dockerfile to provided path :param stream: bool, True returns generator, False returns str :param use_cache: bool, True if you want to use cache :return: generator """ logger.info("building image '%s' from git repo '%s' specified as URL '%s'", image, git_path, url) logger.info("will copy Dockerfile to '%s'", copy_dockerfile_to) temp_dir = tempfile.mkdtemp() response = None try: clone_git_repo(url, temp_dir, git_commit) df_path, df_dir = figure_out_dockerfile(temp_dir, git_path) if copy_dockerfile_to: # TODO: pre build plugin shutil.copyfile(df_path, copy_dockerfile_to) response = self.build_image_from_path(df_dir, image, stream=stream, use_cache=use_cache) finally: try: shutil.rmtree(temp_dir) except (IOError, OSError) as ex: # no idea why this is happening logger.warning("Failed to remove dir '%s': '%s'", temp_dir, repr(ex)) logger.info("build finished") return response def run(self, image, command=None, create_kwargs=None, start_kwargs=None): """ create container from provided image and start it for more info, see documentation of REST API calls: * containers/{}/start * container/create :param image: ImageName or string, name or id of the image :param command: str :param create_kwargs: dict, kwargs for docker.create_container :param start_kwargs: dict, kwargs for docker.start :return: str, container id """ logger.info("creating container from image '%s' and running it", image) create_kwargs = create_kwargs or {} start_kwargs = start_kwargs or {} logger.debug("image = '%s', command = '%s', create_kwargs = '%s', start_kwargs = '%s'", image, command, create_kwargs, start_kwargs) if isinstance(image, ImageName): image = image.to_str() container_dict = self.d.create_container(image, command=command, **create_kwargs) container_id = container_dict['Id'] logger.debug("container_id = '%s'", container_id) self.d.start(container_id, **start_kwargs) # returns None return container_id def commit_container(self, container_id, image=None, message=None): """ create image from provided container :param container_id: str :param image: ImageName :param message: str :return: image_id """ logger.info("committing container '%s'", container_id) logger.debug("container_id = '%s', image = '%s', message = '%s'", container_id, image, message) tag = None if image: tag = image.tag image = image.to_str(tag=False) response = self.d.commit(container_id, repository=image, tag=tag, message=message) logger.debug("response = '%s'", response) try: return response['Id'] except KeyError: logger.error("ID missing from commit response") raise RuntimeError("ID missing from commit response") def get_image_info_by_image_id(self, image_id): """ using `docker images`, provide information about an image :param image_id: str, hash of image to get info :return: str or None """ logger.info("getting info about provided image specified by image_id '%s'", image_id) logger.debug("image_id = '%s'", image_id) # returns list of # {u'Created': 1414577076, # u'Id': u'3ab9a7ed8a169ab89b09fb3e12a14a390d3c662703b65b4541c0c7bde0ee97eb', # u'ParentId': u'a79ad4dac406fcf85b9c7315fe08de5b620c1f7a12f45c8185c843f4b4a49c4e', # u'RepoTags': [u'buildroot-fedora:latest'], # u'Size': 0, # u'VirtualSize': 856564160} images = self.d.images() try: image_dict = [i for i in images if i['Id'] == image_id][0] except IndexError: logger.info("image not found") return None else: return image_dict def get_image_info_by_image_name(self, image, exact_tag=True): """ using `docker images`, provide information about an image :param image: ImageName, name of image :param exact_tag: bool, if false then return info for all images of the given name regardless what their tag is :return: list of dicts """ logger.info("getting info about provided image specified by name '%s'", image) logger.debug("image_name = '%s'", image) # returns list of # {u'Created': 1414577076, # u'Id': u'3ab9a7ed8a169ab89b09fb3e12a14a390d3c662703b65b4541c0c7bde0ee97eb', # u'ParentId': u'a79ad4dac406fcf85b9c7315fe08de5b620c1f7a12f45c8185c843f4b4a49c4e', # u'RepoTags': [u'buildroot-fedora:latest'], # u'Size': 0, # u'VirtualSize': 856564160} images = self.d.images(name=image.to_str(tag=False)) if exact_tag: # tag is specified, we are looking for the exact image for found_image in images: if image.to_str(explicit_tag=True) in found_image['RepoTags']: logger.debug("image '%s' found", image) return [found_image] images = [] # image not found logger.debug("%d matching images found", len(images)) return images def pull_image(self, image, insecure=False): """ pull provided image from registry :param image_name: ImageName, image to pull :param insecure: bool, allow connecting to registry over plain http :return: str, image (reg.om/img:v1) """ logger.info("pulling image '%s' from registry", image) logger.debug("image = '%s', insecure = '%s'", image, insecure) try: logs_gen = self.d.pull(image.to_str(tag=False), tag=image.tag, insecure_registry=insecure, stream=True) except TypeError: # because changing api is fun logs_gen = self.d.pull(image.to_str(tag=False), tag=image.tag, stream=True) command_result = wait_for_command(logs_gen) self.last_logs = command_result.logs return image.to_str() def tag_image(self, image, target_image, force=False): """ tag provided image with specified image_name, registry and tag :param image: str or ImageName, image to tag :param target_image: ImageName, new name for the image :param force: bool, force tag the image? :return: str, image (reg.om/img:v1) """ logger.info("tagging image '%s' as '%s'", image, target_image) logger.debug("image = '%s', target_image_name = '%s'", image, target_image) if not isinstance(image, ImageName): image = ImageName.parse(image) if image != target_image: response = self.d.tag( image.to_str(), target_image.to_str(tag=False), tag=target_image.tag, force=force) # returns True/False if not response: logger.error("failed to tag image") raise RuntimeError("Failed to tag image '%s': target_image = '%s'" % image.to_str(), target_image) else: logger.debug('image already tagged correctly, nothing to do') return target_image.to_str() # this will be the proper name, not just repo/img def push_image(self, image, insecure=False): """ push provided image to registry :param image: ImageName :param insecure: bool, allow connecting to registry over plain http :return: str, logs from push """ logger.info("pushing image '%s'", image) logger.debug("image: '%s', insecure: '%s'", image, insecure) try: # push returns string composed of newline separated jsons; exactly what 'docker push' outputs logs = self.d.push(image.to_str(tag=False), tag=image.tag, insecure_registry=insecure, stream=False) except TypeError: # because changing api is fun logs = self.d.push(image.to_str(tag=False), tag=image.tag, stream=False) return logs def tag_and_push_image(self, image, target_image, insecure=False, force=False): """ tag provided image and push it to registry :param image: str or ImageName, image id or name :param target_image: ImageName, img :param insecure: bool, allow connecting to registry over plain http :param force: bool, force the tag? :return: str, image (reg.com/img:v1) """ logger.info("tagging and pushing image '%s' as '%s'", image, target_image) logger.debug("image = '%s', target_image = '%s'", image, target_image) self.tag_image(image, target_image, force=force) return self.push_image(target_image, insecure=insecure) def inspect_image(self, image_id): """ return detailed metadata about provided image (see 'man docker-inspect') :param image_id: str or ImageName, id or name of the image :return: dict """ logger.info("inspecting image '%s'", image_id) logger.debug("image_id = '%s'", image_id) if isinstance(image_id, ImageName): image_id = image_id.to_str() image_metadata = self.d.inspect_image(image_id) return image_metadata def remove_image(self, image_id, force=False, noprune=False): """ remove provided image from filesystem :param image_id: str or ImageName :param noprune: bool, keep untagged parents? :param force: bool, force remove -- just trash it no matter what :return: None """ logger.info("removing image '%s' from filesystem", image_id) logger.debug("image_id = '%s'", image_id) if isinstance(image_id, ImageName): image_id = image_id.to_str() self.d.remove_image(image_id, force=force, noprune=noprune) # returns None def remove_container(self, container_id, force=False): """ remove provided container from filesystem :param container_id: str :param force: bool, remove forcefully? :return: None """ logger.info("removing container '%s' from filesystem", container_id) logger.debug("container_id = '%s'", container_id) self.d.remove_container(container_id, force=force) # returns None def logs(self, container_id, stderr=True, stream=True): """ acquire output (stdout, stderr) from provided container :param container_id: str :param stderr: True, False :param stream: if True, return as generator :return: either generator, or list of strings """ logger.info("getting stdout of container '%s'", container_id) logger.debug("container_id = '%s', stream = '%s'", container_id, stream) response = self.d.logs(container_id, stdout=True, stderr=stderr, stream=stream) if not stream: response = response.decode("utf-8") # py2 & 3 compat response = [line for line in response.split('\n') if line] return response def wait(self, container_id): """ wait for container to finish the job (may run infinitely) :param container_id: str :return: int, exit code """ logger.info("waiting for container '%s' to finish", container_id) logger.debug("container = '%s'", container_id) response = self.d.wait(container_id) # returns exit code as int logger.debug("container finished with exit code %s", response) return response def image_exists(self, image_id): """ does provided image exists? :param image_id: str or ImageName :return: True if exists, False if not """ logger.info("checking whether image '%s' exists", image_id) logger.debug("image_id = '%s'", image_id) try: response = self.d.inspect_image(image_id) except APIError as ex: logger.warning(repr(ex)) response = False else: response = response is not None logger.debug("image exists: %s", response) return response
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import print_function, unicode_literals try: from collections import OrderedDict except ImportError: # Python 2.6 from ordereddict import OrderedDict from dockerfile_parse import DockerfileParser from atomic_reactor.core import DockerTasker from atomic_reactor.inner import DockerBuildWorkflow from atomic_reactor.plugin import PreBuildPluginsRunner from atomic_reactor.plugins.pre_add_labels_in_df import AddLabelsPlugin from atomic_reactor.util import ImageName from tests.constants import MOCK_SOURCE import json import pytest class Y(object): pass class X(object): image_id = "xxx" source = Y() source.dockerfile_path = None source.path = None base_image = ImageName(repo="qwe", tag="asd") DF_CONTENT = """\ FROM fedora RUN yum install -y python-django CMD blabla""" LABELS_CONF_BASE = {"Config": {"Labels": {"label1": "base value"}}} LABELS_CONF = OrderedDict({'label1': 'value 1', 'label2': 'long value'}) LABELS_CONF_WRONG = [('label1', 'value1'), ('label2', 'value2')] LABELS_BLANK = {} # Can't be sure of the order of the labels, expect either EXPECTED_OUTPUT = [r"""FROM fedora RUN yum install -y python-django LABEL "label1"="value 1" "label2"="long value" CMD blabla""", r"""FROM fedora RUN yum install -y python-django LABEL "label2"="long value" "label1"="value 1" CMD blabla"""] EXPECTED_OUTPUT2 = [r"""FROM fedora RUN yum install -y python-django LABEL "label2"="long value" CMD blabla"""] EXPECTED_OUTPUT3 = [DF_CONTENT] @pytest.mark.parametrize('labels_conf_base, labels_conf, dont_overwrite, expected_output', [ (LABELS_CONF_BASE, LABELS_CONF, [], EXPECTED_OUTPUT), (LABELS_CONF_BASE, json.dumps(LABELS_CONF), [], EXPECTED_OUTPUT), (LABELS_CONF_BASE, LABELS_CONF_WRONG, [], RuntimeError()), (LABELS_CONF_BASE, LABELS_CONF, ["label1", ], EXPECTED_OUTPUT2), (LABELS_CONF_BASE, LABELS_BLANK, ["label1", ], EXPECTED_OUTPUT3), ]) def test_add_labels_plugin(tmpdir, labels_conf_base, labels_conf, dont_overwrite, expected_output): df = DockerfileParser(str(tmpdir)) df.content = DF_CONTENT tasker = DockerTasker() workflow = DockerBuildWorkflow(MOCK_SOURCE, 'test-image') setattr(workflow, 'builder', X) workflow.base_image_inspect = labels_conf_base setattr(workflow.builder, 'df_path', df.dockerfile_path) runner = PreBuildPluginsRunner( tasker, workflow, [{ 'name': AddLabelsPlugin.key, 'args': {'labels': labels_conf, "dont_overwrite": dont_overwrite} }] ) if isinstance(expected_output, RuntimeError): with pytest.raises(RuntimeError): runner.run() else: runner.run() assert AddLabelsPlugin.key is not None assert df.content in expected_output
shaded-enmity/atomic-reactor
tests/plugins/test_add_labels.py
atomic_reactor/core.py
"""Monitor Memory on a CFME/Miq appliance and builds report&graphs displaying usage per process.""" import json import os import time import traceback from collections import OrderedDict from datetime import datetime from threading import Thread import yaml from yaycl import AttrDict from cfme.utils.conf import cfme_performance from cfme.utils.log import logger from cfme.utils.path import results_path from cfme.utils.version import current_version from cfme.utils.version import get_version miq_workers = [ 'MiqGenericWorker', 'MiqPriorityWorker', 'MiqScheduleWorker', 'MiqUiWorker', 'MiqWebServiceWorker', 'MiqWebsocketWorker', 'MiqReportingWorker', 'MiqReplicationWorker', 'MiqSmartProxyWorker', 'MiqVimBrokerWorker', 'MiqEmsRefreshCoreWorker', # Refresh Workers: 'ManageIQ::Providers::Microsoft::InfraManager::RefreshWorker', 'ManageIQ::Providers::Openstack::InfraManager::RefreshWorker', 'ManageIQ::Providers::Redhat::InfraManager::RefreshWorker', 'ManageIQ::Providers::Vmware::InfraManager::RefreshWorker', 'MiqEmsRefreshWorkerMicrosoft', # 5.4 'MiqEmsRefreshWorkerRedhat', # 5.4 'MiqEmsRefreshWorkerVmware', # 5.4 'ManageIQ::Providers::Amazon::CloudManager::RefreshWorker', 'ManageIQ::Providers::Azure::CloudManager::RefreshWorker', 'ManageIQ::Providers::Google::CloudManager::RefreshWorker', 'ManageIQ::Providers::Openstack::CloudManager::RefreshWorker', 'MiqEmsRefreshWorkerAmazon', # 5.4 'MiqEmsRefreshWorkerOpenstack', # 5.4 'ManageIQ::Providers::AnsibleTower::ConfigurationManager::RefreshWorker', 'ManageIQ::Providers::Foreman::ConfigurationManager::RefreshWorker', 'ManageIQ::Providers::Foreman::ProvisioningManager::RefreshWorker', 'MiqEmsRefreshWorkerForemanConfiguration', # 5.4 'MiqEmsRefreshWorkerForemanProvisioning', # 5.4 'ManageIQ::Providers::Atomic::ContainerManager::RefreshWorker', 'ManageIQ::Providers::AtomicEnterprise::ContainerManager::RefreshWorker', 'ManageIQ::Providers::Kubernetes::ContainerManager::RefreshWorker', 'ManageIQ::Providers::Openshift::ContainerManager::RefreshWorker', 'ManageIQ::Providers::OpenshiftEnterprise::ContainerManager::RefreshWorker', 'ManageIQ::Providers::StorageManager::CinderManager::RefreshWorker', 'ManageIQ::Providers::StorageManager::SwiftManager::RefreshWorker', 'ManageIQ::Providers::Amazon::NetworkManager::RefreshWorker', 'ManageIQ::Providers::Azure::NetworkManager::RefreshWorker', 'ManageIQ::Providers::Google::NetworkManager::RefreshWorker', 'ManageIQ::Providers::Openstack::NetworkManager::RefreshWorker', 'MiqNetappRefreshWorker', 'MiqSmisRefreshWorker', # Event Workers: 'MiqEventHandler', 'ManageIQ::Providers::Openstack::InfraManager::EventCatcher', 'ManageIQ::Providers::StorageManager::CinderManager::EventCatcher', 'ManageIQ::Providers::Redhat::InfraManager::EventCatcher', 'ManageIQ::Providers::Vmware::InfraManager::EventCatcher', 'MiqEventCatcherRedhat', # 5.4 'MiqEventCatcherVmware', # 5.4 'ManageIQ::Providers::Amazon::CloudManager::EventCatcher', 'ManageIQ::Providers::Azure::CloudManager::EventCatcher', 'ManageIQ::Providers::Google::CloudManager::EventCatcher', 'ManageIQ::Providers::Openstack::CloudManager::EventCatcher', 'MiqEventCatcherAmazon', # 5.4 'MiqEventCatcherOpenstack', # 5.4 'ManageIQ::Providers::Atomic::ContainerManager::EventCatcher', 'ManageIQ::Providers::AtomicEnterprise::ContainerManager::EventCatcher', 'ManageIQ::Providers::Kubernetes::ContainerManager::EventCatcher', 'ManageIQ::Providers::Openshift::ContainerManager::EventCatcher', 'ManageIQ::Providers::OpenshiftEnterprise::ContainerManager::EventCatcher', 'ManageIQ::Providers::Openstack::NetworkManager::EventCatcher', # Metrics Processor/Collector Workers 'MiqEmsMetricsProcessorWorker', 'ManageIQ::Providers::Openstack::InfraManager::MetricsCollectorWorker', 'ManageIQ::Providers::Redhat::InfraManager::MetricsCollectorWorker', 'ManageIQ::Providers::Vmware::InfraManager::MetricsCollectorWorker', 'MiqEmsMetricsCollectorWorkerRedhat', # 5.4 'MiqEmsMetricsCollectorWorkerVmware', # 5.4 'ManageIQ::Providers::Amazon::CloudManager::MetricsCollectorWorker', 'ManageIQ::Providers::Azure::CloudManager::MetricsCollectorWorker', 'ManageIQ::Providers::Openstack::CloudManager::MetricsCollectorWorker', 'MiqEmsMetricsCollectorWorkerAmazon', # 5.4 'MiqEmsMetricsCollectorWorkerOpenstack', # 5.4 'ManageIQ::Providers::Atomic::ContainerManager::MetricsCollectorWorker', 'ManageIQ::Providers::AtomicEnterprise::ContainerManager::MetricsCollectorWorker', 'ManageIQ::Providers::Kubernetes::ContainerManager::MetricsCollectorWorker', 'ManageIQ::Providers::Openshift::ContainerManager::MetricsCollectorWorker', 'ManageIQ::Providers::OpenshiftEnterprise::ContainerManager::MetricsCollectorWorker', 'ManageIQ::Providers::Openstack::NetworkManager::MetricsCollectorWorker', 'MiqStorageMetricsCollectorWorker', 'MiqVmdbStorageBridgeWorker'] ruby_processes = list(miq_workers) ruby_processes.extend(['evm:dbsync:replicate', 'MIQ Server (evm_server.rb)', 'evm_watchdog.rb', 'appliance_console.rb']) process_order = list(ruby_processes) process_order.extend(['memcached', 'postgres', 'httpd', 'collectd']) # Timestamp created at first import, thus grouping all reports of like workload test_ts = time.strftime('%Y%m%d%H%M%S') # 10s sample interval (occasionally sampling can take almost 4s on an appliance doing a lot of work) SAMPLE_INTERVAL = 10 class SmemMemoryMonitor(Thread): def __init__(self, ssh_client, scenario_data): super(SmemMemoryMonitor, self).__init__() self.ssh_client = ssh_client self.scenario_data = scenario_data self.grafana_urls = {} self.miq_server_id = '' self.use_slab = False self.signal = True def create_process_result(self, process_results, starttime, process_pid, process_name, memory_by_pid): if process_pid in list(memory_by_pid.keys()): if process_name not in process_results: process_results[process_name] = OrderedDict() process_results[process_name][process_pid] = OrderedDict() if process_pid not in process_results[process_name]: process_results[process_name][process_pid] = OrderedDict() process_results[process_name][process_pid][starttime] = {} rss_mem = memory_by_pid[process_pid]['rss'] pss_mem = memory_by_pid[process_pid]['pss'] uss_mem = memory_by_pid[process_pid]['uss'] vss_mem = memory_by_pid[process_pid]['vss'] swap_mem = memory_by_pid[process_pid]['swap'] process_results[process_name][process_pid][starttime]['rss'] = rss_mem process_results[process_name][process_pid][starttime]['pss'] = pss_mem process_results[process_name][process_pid][starttime]['uss'] = uss_mem process_results[process_name][process_pid][starttime]['vss'] = vss_mem process_results[process_name][process_pid][starttime]['swap'] = swap_mem del memory_by_pid[process_pid] else: logger.warning('Process {} PID, not found: {}'.format(process_name, process_pid)) def get_appliance_memory(self, appliance_results, plottime): # 5.5/5.6 - RHEL 7 / Centos 7 # Application Memory Used : MemTotal - (MemFree + Slab + Cached) # 5.4 - RHEL 6 / Centos 6 # Application Memory Used : MemTotal - (MemFree + Buffers + Cached) # Available memory could potentially be better metric appliance_results[plottime] = {} result = self.ssh_client.run_command('cat /proc/meminfo') if result.failed: logger.error('Exit_status nonzero in get_appliance_memory: {}, {}' .format(result.rc, result.output)) del appliance_results[plottime] else: meminfo_raw = result.output.replace('kB', '').strip() meminfo = OrderedDict((k.strip(), v.strip()) for k, v in (value.strip().split(':') for value in meminfo_raw.split('\n'))) appliance_results[plottime]['total'] = float(meminfo['MemTotal']) / 1024 appliance_results[plottime]['free'] = float(meminfo['MemFree']) / 1024 if 'MemAvailable' in meminfo: # 5.5, RHEL 7/Centos 7 self.use_slab = True mem_used = (float(meminfo['MemTotal']) - (float(meminfo['MemFree']) + float( meminfo['Slab']) + float(meminfo['Cached']))) / 1024 else: # 5.4, RHEL 6/Centos 6 mem_used = (float(meminfo['MemTotal']) - (float(meminfo['MemFree']) + float( meminfo['Buffers']) + float(meminfo['Cached']))) / 1024 appliance_results[plottime]['used'] = mem_used appliance_results[plottime]['buffers'] = float(meminfo['Buffers']) / 1024 appliance_results[plottime]['cached'] = float(meminfo['Cached']) / 1024 appliance_results[plottime]['slab'] = float(meminfo['Slab']) / 1024 appliance_results[plottime]['swap_total'] = float(meminfo['SwapTotal']) / 1024 appliance_results[plottime]['swap_free'] = float(meminfo['SwapFree']) / 1024 def get_evm_workers(self): result = self.ssh_client.run_command( 'psql -t -q -d vmdb_production -c ' '\"select pid,type from miq_workers where miq_server_id = \'{}\'\"'.format( self.miq_server_id)) if result.output.strip(): workers = {} for worker in result.output.strip().split('\n'): pid_worker = worker.strip().split('|') if len(pid_worker) == 2: workers[pid_worker[0].strip()] = pid_worker[1].strip() else: logger.error('Unexpected output from psql: {}'.format(worker)) return workers else: return {} # Old method of obtaining per process memory (Appliances without smem) # def get_pids_memory(self): # result = self.ssh_client.run_command( # 'ps -A -o pid,rss,vsz,comm,cmd | sed 1d') # pids_memory = result.output.strip().split('\n') # memory_by_pid = {} # for line in pids_memory: # values = [s for s in line.strip().split(' ') if s] # pid = values[0] # memory_by_pid[pid] = {} # memory_by_pid[pid]['rss'] = float(values[1]) / 1024 # memory_by_pid[pid]['vss'] = float(values[2]) / 1024 # memory_by_pid[pid]['name'] = values[3] # memory_by_pid[pid]['cmd'] = ' '.join(values[4:]) # return memory_by_pid def get_miq_server_id(self): # Obtain the Miq Server GUID: result = self.ssh_client.run_command('cat /var/www/miq/vmdb/GUID') logger.info('Obtained appliance GUID: {}'.format(result.output.strip())) # Get server id: result = self.ssh_client.run_command( 'psql -t -q -d vmdb_production -c "select id from miq_servers where guid = \'{}\'"' ''.format(result.output.strip())) logger.info('Obtained miq_server_id: {}'.format(result.output.strip())) self.miq_server_id = result.output.strip() def get_pids_memory(self): result = self.ssh_client.run_command( 'smem -c \'pid rss pss uss vss swap name command\' | sed 1d') pids_memory = result.output.strip().split('\n') memory_by_pid = {} for line in pids_memory: if line.strip(): try: values = [s for s in line.strip().split(' ') if s] pid = values[0] int(pid) memory_by_pid[pid] = {} memory_by_pid[pid]['rss'] = float(values[1]) / 1024 memory_by_pid[pid]['pss'] = float(values[2]) / 1024 memory_by_pid[pid]['uss'] = float(values[3]) / 1024 memory_by_pid[pid]['vss'] = float(values[4]) / 1024 memory_by_pid[pid]['swap'] = float(values[5]) / 1024 memory_by_pid[pid]['name'] = values[6] memory_by_pid[pid]['cmd'] = ' '.join(values[7:]) except Exception as e: logger.error('Processing smem output error: {}'.format(e.__class__.__name__, e)) logger.error('Issue with pid: {} line: {}'.format(pid, line)) logger.error('Complete smem output: {}'.format(result.output)) return memory_by_pid def _real_run(self): """ Result dictionaries: appliance_results[timestamp][measurement] = value appliance_results[timestamp]['total'] = value appliance_results[timestamp]['free'] = value appliance_results[timestamp]['used'] = value appliance_results[timestamp]['buffers'] = value appliance_results[timestamp]['cached'] = value appliance_results[timestamp]['slab'] = value appliance_results[timestamp]['swap_total'] = value appliance_results[timestamp]['swap_free'] = value appliance measurements: total/free/used/buffers/cached/slab/swap_total/swap_free process_results[name][pid][timestamp][measurement] = value process_results[name][pid][timestamp]['rss'] = value process_results[name][pid][timestamp]['pss'] = value process_results[name][pid][timestamp]['uss'] = value process_results[name][pid][timestamp]['vss'] = value process_results[name][pid][timestamp]['swap'] = value """ appliance_results = OrderedDict() process_results = OrderedDict() install_smem(self.ssh_client) self.get_miq_server_id() logger.info('Starting Monitoring Thread.') while self.signal: starttime = time.time() plottime = datetime.now() self.get_appliance_memory(appliance_results, plottime) workers = self.get_evm_workers() memory_by_pid = self.get_pids_memory() for worker_pid in workers: self.create_process_result(process_results, plottime, worker_pid, workers[worker_pid], memory_by_pid) for pid in sorted(memory_by_pid.keys()): if memory_by_pid[pid]['name'] == 'httpd': self.create_process_result(process_results, plottime, pid, 'httpd', memory_by_pid) elif memory_by_pid[pid]['name'] == 'postgres': self.create_process_result(process_results, plottime, pid, 'postgres', memory_by_pid) elif memory_by_pid[pid]['name'] == 'postmaster': self.create_process_result(process_results, plottime, pid, 'postgres', memory_by_pid) elif memory_by_pid[pid]['name'] == 'memcached': self.create_process_result(process_results, plottime, pid, 'memcached', memory_by_pid) elif memory_by_pid[pid]['name'] == 'collectd': self.create_process_result(process_results, plottime, pid, 'collectd', memory_by_pid) elif memory_by_pid[pid]['name'] == 'ruby': if 'evm_server.rb' in memory_by_pid[pid]['cmd']: self.create_process_result(process_results, plottime, pid, 'MIQ Server (evm_server.rb)', memory_by_pid) elif 'MIQ Server' in memory_by_pid[pid]['cmd']: self.create_process_result(process_results, plottime, pid, 'MIQ Server (evm_server.rb)', memory_by_pid) elif 'evm_watchdog.rb' in memory_by_pid[pid]['cmd']: self.create_process_result(process_results, plottime, pid, 'evm_watchdog.rb', memory_by_pid) elif 'appliance_console.rb' in memory_by_pid[pid]['cmd']: self.create_process_result(process_results, plottime, pid, 'appliance_console.rb', memory_by_pid) elif 'evm:dbsync:replicate' in memory_by_pid[pid]['cmd']: self.create_process_result(process_results, plottime, pid, 'evm:dbsync:replicate', memory_by_pid) else: logger.debug('Unaccounted for ruby pid: {}'.format(pid)) timediff = time.time() - starttime logger.debug('Monitoring sampled in {}s'.format(round(timediff, 4))) # Sleep Monitoring interval # Roughly 10s samples, accounts for collection of memory measurements time_to_sleep = abs(SAMPLE_INTERVAL - timediff) time.sleep(time_to_sleep) logger.info('Monitoring CFME Memory Terminating') create_report(self.scenario_data, appliance_results, process_results, self.use_slab, self.grafana_urls) def run(self): try: self._real_run() except Exception as e: logger.error('Error in Monitoring Thread: {}'.format(e)) logger.error('{}'.format(traceback.format_exc())) def install_smem(ssh_client): # smem is included by default in 5.6 appliances logger.info('Installing smem.') ver = get_version() if ver == '55': ssh_client.run_command('rpm -i {}'.format(cfme_performance['tools']['rpms']['epel7_rpm'])) ssh_client.run_command('yum install -y smem') # Patch smem to display longer command line names logger.info('Patching smem') ssh_client.run_command(r'sed -i s/\.27s/\.200s/g /usr/bin/smem') def create_report(scenario_data, appliance_results, process_results, use_slab, grafana_urls): logger.info('Creating Memory Monitoring Report.') ver = current_version() provider_names = 'No Providers' if 'providers' in scenario_data['scenario']: provider_names = ', '.join(scenario_data['scenario']['providers']) workload_path = results_path.join('{}-{}-{}'.format(test_ts, scenario_data['test_dir'], ver)) if not os.path.exists(str(workload_path)): os.makedirs(str(workload_path)) scenario_path = workload_path.join(scenario_data['scenario']['name']) if os.path.exists(str(scenario_path)): logger.warning('Duplicate Workload-Scenario Name: {}'.format(scenario_path)) scenario_path = workload_path.join('{}-{}'.format(time.strftime('%Y%m%d%H%M%S'), scenario_data['scenario']['name'])) logger.warning('Using: {}'.format(scenario_path)) os.mkdir(str(scenario_path)) mem_graphs_path = scenario_path.join('graphs') if not os.path.exists(str(mem_graphs_path)): os.mkdir(str(mem_graphs_path)) mem_rawdata_path = scenario_path.join('rawdata') if not os.path.exists(str(mem_rawdata_path)): os.mkdir(str(mem_rawdata_path)) graph_appliance_measurements(mem_graphs_path, ver, appliance_results, use_slab, provider_names) graph_individual_process_measurements(mem_graphs_path, process_results, provider_names) graph_same_miq_workers(mem_graphs_path, process_results, provider_names) graph_all_miq_workers(mem_graphs_path, process_results, provider_names) # Dump scenario Yaml: with open(str(scenario_path.join('scenario.yml')), 'w') as scenario_file: yaml.safe_dump(dict(scenario_data['scenario']), scenario_file, default_flow_style=False) generate_summary_csv(scenario_path.join('{}-summary.csv'.format(ver)), appliance_results, process_results, provider_names, ver) generate_raw_data_csv(mem_rawdata_path, appliance_results, process_results) generate_summary_html(scenario_path, ver, appliance_results, process_results, scenario_data, provider_names, grafana_urls) generate_workload_html(scenario_path, ver, scenario_data, provider_names, grafana_urls) logger.info('Finished Creating Report') def compile_per_process_results(procs_to_compile, process_results, ts_end): alive_pids = 0 recycled_pids = 0 total_running_rss = 0 total_running_pss = 0 total_running_uss = 0 total_running_vss = 0 total_running_swap = 0 for process in procs_to_compile: if process in process_results: for pid in process_results[process]: if ts_end in process_results[process][pid]: alive_pids += 1 total_running_rss += process_results[process][pid][ts_end]['rss'] total_running_pss += process_results[process][pid][ts_end]['pss'] total_running_uss += process_results[process][pid][ts_end]['uss'] total_running_vss += process_results[process][pid][ts_end]['vss'] total_running_swap += process_results[process][pid][ts_end]['swap'] else: recycled_pids += 1 return alive_pids, recycled_pids, total_running_rss, total_running_pss, total_running_uss, \ total_running_vss, total_running_swap def generate_raw_data_csv(directory, appliance_results, process_results): starttime = time.time() file_name = str(directory.join('appliance.csv')) with open(file_name, 'w') as csv_file: csv_file.write('TimeStamp,Total,Free,Used,Buffers,Cached,Slab,Swap_Total,Swap_Free\n') for ts in appliance_results: csv_file.write('{},{},{},{},{},{},{},{},{}\n'.format(ts, appliance_results[ts]['total'], appliance_results[ts]['free'], appliance_results[ts]['used'], appliance_results[ts]['buffers'], appliance_results[ts]['cached'], appliance_results[ts]['slab'], appliance_results[ts]['swap_total'], appliance_results[ts]['swap_free'])) for process_name in process_results: for process_pid in process_results[process_name]: file_name = str(directory.join('{}-{}.csv'.format(process_pid, process_name))) with open(file_name, 'w') as csv_file: csv_file.write('TimeStamp,RSS,PSS,USS,VSS,SWAP\n') for ts in process_results[process_name][process_pid]: csv_file.write('{},{},{},{},{},{}\n'.format(ts, process_results[process_name][process_pid][ts]['rss'], process_results[process_name][process_pid][ts]['pss'], process_results[process_name][process_pid][ts]['uss'], process_results[process_name][process_pid][ts]['vss'], process_results[process_name][process_pid][ts]['swap'])) timediff = time.time() - starttime logger.info('Generated Raw Data CSVs in: {}'.format(timediff)) def generate_summary_csv(file_name, appliance_results, process_results, provider_names, version_string): starttime = time.time() with open(str(file_name), 'w') as csv_file: csv_file.write('Version: {}, Provider(s): {}\n'.format(version_string, provider_names)) csv_file.write('Measurement,Start of test,End of test\n') start = list(appliance_results.keys())[0] end = list(appliance_results.keys())[-1] csv_file.write('Appliance Total Memory,{},{}\n'.format( round(appliance_results[start]['total'], 2), round(appliance_results[end]['total'], 2))) csv_file.write('Appliance Free Memory,{},{}\n'.format( round(appliance_results[start]['free'], 2), round(appliance_results[end]['free'], 2))) csv_file.write('Appliance Used Memory,{},{}\n'.format( round(appliance_results[start]['used'], 2), round(appliance_results[end]['used'], 2))) csv_file.write('Appliance Buffers,{},{}\n'.format( round(appliance_results[start]['buffers'], 2), round(appliance_results[end]['buffers'], 2))) csv_file.write('Appliance Cached,{},{}\n'.format( round(appliance_results[start]['cached'], 2), round(appliance_results[end]['cached'], 2))) csv_file.write('Appliance Slab,{},{}\n'.format( round(appliance_results[start]['slab'], 2), round(appliance_results[end]['slab'], 2))) csv_file.write('Appliance Total Swap,{},{}\n'.format( round(appliance_results[start]['swap_total'], 2), round(appliance_results[end]['swap_total'], 2))) csv_file.write('Appliance Free Swap,{},{}\n'.format( round(appliance_results[start]['swap_free'], 2), round(appliance_results[end]['swap_free'], 2))) summary_csv_measurement_dump(csv_file, process_results, 'rss') summary_csv_measurement_dump(csv_file, process_results, 'pss') summary_csv_measurement_dump(csv_file, process_results, 'uss') summary_csv_measurement_dump(csv_file, process_results, 'vss') summary_csv_measurement_dump(csv_file, process_results, 'swap') timediff = time.time() - starttime logger.info('Generated Summary CSV in: {}'.format(timediff)) def generate_summary_html(directory, version_string, appliance_results, process_results, scenario_data, provider_names, grafana_urls): starttime = time.time() file_name = str(directory.join('index.html')) with open(file_name, 'w') as html_file: html_file.write('<html>\n') html_file.write('<head><title>{} - {} Memory Usage Performance</title></head>'.format( version_string, provider_names)) html_file.write('<body>\n') html_file.write('<b>CFME {} {} Test Results</b><br>\n'.format(version_string, scenario_data['test_name'].title())) html_file.write('<b>Appliance Roles:</b> {}<br>\n'.format( scenario_data['appliance_roles'].replace(',', ', '))) html_file.write('<b>Provider(s):</b> {}<br>\n'.format(provider_names)) html_file.write('<b><a href=\'https://{}/\' target="_blank">{}</a></b>\n'.format( scenario_data['appliance_ip'], scenario_data['appliance_name'])) if grafana_urls: for g_name in sorted(grafana_urls.keys()): html_file.write( ' : <b><a href=\'{}\' target="_blank">{}</a></b>'.format(grafana_urls[g_name], g_name)) html_file.write('<br>\n') html_file.write('<b><a href=\'{}-summary.csv\'>Summary CSV</a></b>'.format(version_string)) html_file.write(' : <b><a href=\'workload.html\'>Workload Info</a></b>') html_file.write(' : <b><a href=\'graphs/\'>Graphs directory</a></b>\n') html_file.write(' : <b><a href=\'rawdata/\'>CSVs directory</a></b><br>\n') start = list(appliance_results.keys())[0] end = list(appliance_results.keys())[-1] timediff = end - start total_proc_count = 0 for proc_name in process_results: total_proc_count += len(list(process_results[proc_name].keys())) growth = appliance_results[end]['used'] - appliance_results[start]['used'] max_used_memory = 0 for ts in appliance_results: if appliance_results[ts]['used'] > max_used_memory: max_used_memory = appliance_results[ts]['used'] html_file.write('<table border="1">\n') html_file.write('<tr><td>\n') # Appliance Wide Results html_file.write('<table style="width:100%" border="1">\n') html_file.write('<tr>\n') html_file.write('<td><b>Version</b></td>\n') html_file.write('<td><b>Start Time</b></td>\n') html_file.write('<td><b>End Time</b></td>\n') html_file.write('<td><b>Total Test Time</b></td>\n') html_file.write('<td><b>Total Memory</b></td>\n') html_file.write('<td><b>Start Used Memory</b></td>\n') html_file.write('<td><b>End Used Memory</b></td>\n') html_file.write('<td><b>Used Memory Growth</b></td>\n') html_file.write('<td><b>Max Used Memory</b></td>\n') html_file.write('<td><b>Total Tracked Processes</b></td>\n') html_file.write('</tr>\n') html_file.write('<td><a href=\'rawdata/appliance.csv\'>{}</a></td>\n'.format( version_string)) html_file.write('<td>{}</td>\n'.format(start.replace(microsecond=0))) html_file.write('<td>{}</td>\n'.format(end.replace(microsecond=0))) html_file.write('<td>{}</td>\n'.format(str(timediff).partition('.')[0])) html_file.write('<td>{}</td>\n'.format(round(appliance_results[end]['total'], 2))) html_file.write('<td>{}</td>\n'.format(round(appliance_results[start]['used'], 2))) html_file.write('<td>{}</td>\n'.format(round(appliance_results[end]['used'], 2))) html_file.write('<td>{}</td>\n'.format(round(growth, 2))) html_file.write('<td>{}</td>\n'.format(round(max_used_memory, 2))) html_file.write('<td>{}</td>\n'.format(total_proc_count)) html_file.write('</table>\n') # CFME/Miq Worker Results html_file.write('<table style="width:100%" border="1">\n') html_file.write('<tr>\n') html_file.write('<td><b>Total CFME/Miq Workers</b></td>\n') html_file.write('<td><b>End Running Workers</b></td>\n') html_file.write('<td><b>Recycled Workers</b></td>\n') html_file.write('<td><b>End Total Worker RSS</b></td>\n') html_file.write('<td><b>End Total Worker PSS</b></td>\n') html_file.write('<td><b>End Total Worker USS</b></td>\n') html_file.write('<td><b>End Total Worker VSS</b></td>\n') html_file.write('<td><b>End Total Worker SWAP</b></td>\n') html_file.write('</tr>\n') a_pids, r_pids, t_rss, t_pss, t_uss, t_vss, t_swap = compile_per_process_results( miq_workers, process_results, end) html_file.write('<tr>\n') html_file.write('<td>{}</td>\n'.format(a_pids + r_pids)) html_file.write('<td>{}</td>\n'.format(a_pids)) html_file.write('<td>{}</td>\n'.format(r_pids)) html_file.write('<td>{}</td>\n'.format(round(t_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_swap, 2))) html_file.write('</tr>\n') html_file.write('</table>\n') # Per Process Summaries: html_file.write('<table style="width:100%" border="1">\n') html_file.write('<tr>\n') html_file.write('<td><b>Application/Process Group</b></td>\n') html_file.write('<td><b>Total Processes</b></td>\n') html_file.write('<td><b>End Running Processes</b></td>\n') html_file.write('<td><b>Recycled Processes</b></td>\n') html_file.write('<td><b>End Total Process RSS</b></td>\n') html_file.write('<td><b>End Total Process PSS</b></td>\n') html_file.write('<td><b>End Total Process USS</b></td>\n') html_file.write('<td><b>End Total Process VSS</b></td>\n') html_file.write('<td><b>End Total Process SWAP</b></td>\n') html_file.write('</tr>\n') a_pids, r_pids, t_rss, t_pss, t_uss, t_vss, t_swap = compile_per_process_results( ruby_processes, process_results, end) t_a_pids = a_pids t_r_pids = r_pids tt_rss = t_rss tt_pss = t_pss tt_uss = t_uss tt_vss = t_vss tt_swap = t_swap html_file.write('<tr>\n') html_file.write('<td>ruby</td>\n') html_file.write('<td>{}</td>\n'.format(a_pids + r_pids)) html_file.write('<td>{}</td>\n'.format(a_pids)) html_file.write('<td>{}</td>\n'.format(r_pids)) html_file.write('<td>{}</td>\n'.format(round(t_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_swap, 2))) html_file.write('</tr>\n') # memcached Summary a_pids, r_pids, t_rss, t_pss, t_uss, t_vss, t_swap = compile_per_process_results( ['memcached'], process_results, end) t_a_pids += a_pids t_r_pids += r_pids tt_rss += t_rss tt_pss += t_pss tt_uss += t_uss tt_vss += t_vss tt_swap += t_swap html_file.write('<tr>\n') html_file.write('<td>memcached</td>\n') html_file.write('<td>{}</td>\n'.format(a_pids + r_pids)) html_file.write('<td>{}</td>\n'.format(a_pids)) html_file.write('<td>{}</td>\n'.format(r_pids)) html_file.write('<td>{}</td>\n'.format(round(t_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_swap, 2))) html_file.write('</tr>\n') # Postgres Summary a_pids, r_pids, t_rss, t_pss, t_uss, t_vss, t_swap = compile_per_process_results( ['postgres'], process_results, end) t_a_pids += a_pids t_r_pids += r_pids tt_rss += t_rss tt_pss += t_pss tt_uss += t_uss tt_vss += t_vss tt_swap += t_swap html_file.write('<tr>\n') html_file.write('<td>postgres</td>\n') html_file.write('<td>{}</td>\n'.format(a_pids + r_pids)) html_file.write('<td>{}</td>\n'.format(a_pids)) html_file.write('<td>{}</td>\n'.format(r_pids)) html_file.write('<td>{}</td>\n'.format(round(t_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_swap, 2))) html_file.write('</tr>\n') # httpd Summary a_pids, r_pids, t_rss, t_pss, t_uss, t_vss, t_swap = compile_per_process_results(['httpd'], process_results, end) t_a_pids += a_pids t_r_pids += r_pids tt_rss += t_rss tt_pss += t_pss tt_uss += t_uss tt_vss += t_vss tt_swap += t_swap html_file.write('<tr>\n') html_file.write('<td>httpd</td>\n') html_file.write('<td>{}</td>\n'.format(a_pids + r_pids)) html_file.write('<td>{}</td>\n'.format(a_pids)) html_file.write('<td>{}</td>\n'.format(r_pids)) html_file.write('<td>{}</td>\n'.format(round(t_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_swap, 2))) html_file.write('</tr>\n') # collectd Summary a_pids, r_pids, t_rss, t_pss, t_uss, t_vss, t_swap = compile_per_process_results( ['collectd'], process_results, end) t_a_pids += a_pids t_r_pids += r_pids tt_rss += t_rss tt_pss += t_pss tt_uss += t_uss tt_vss += t_vss tt_swap += t_swap html_file.write('<tr>\n') html_file.write('<td>collectd</td>\n') html_file.write('<td>{}</td>\n'.format(a_pids + r_pids)) html_file.write('<td>{}</td>\n'.format(a_pids)) html_file.write('<td>{}</td>\n'.format(r_pids)) html_file.write('<td>{}</td>\n'.format(round(t_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_swap, 2))) html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>total</td>\n') html_file.write('<td>{}</td>\n'.format(t_a_pids + t_r_pids)) html_file.write('<td>{}</td>\n'.format(t_a_pids)) html_file.write('<td>{}</td>\n'.format(t_r_pids)) html_file.write('<td>{}</td>\n'.format(round(tt_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(tt_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(tt_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(tt_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(tt_swap, 2))) html_file.write('</tr>\n') html_file.write('</table>\n') # Appliance Graph html_file.write('</td></tr><tr><td>\n') file_name = '{}-appliance_memory.png'.format(version_string) html_file.write('<img src=\'graphs/{}\'>\n'.format(file_name)) file_name = '{}-appliance_swap.png'.format(version_string) # Check for swap usage through out time frame: max_swap_used = 0 for ts in appliance_results: swap_used = appliance_results[ts]['swap_total'] - appliance_results[ts]['swap_free'] if swap_used > max_swap_used: max_swap_used = swap_used if max_swap_used < 10: # Less than 10MiB Max, then hide graph html_file.write('<br><a href=\'graphs/{}\'>Swap Graph '.format(file_name)) html_file.write('(Hidden, max_swap_used < 10 MiB)</a>\n') else: html_file.write('<img src=\'graphs/{}\'>\n'.format(file_name)) html_file.write('</td></tr><tr><td>\n') # Per Process Results html_file.write('<table style="width:100%" border="1"><tr>\n') html_file.write('<td><b>Process Name</b></td>\n') html_file.write('<td><b>Process Pid</b></td>\n') html_file.write('<td><b>Start Time</b></td>\n') html_file.write('<td><b>End Time</b></td>\n') html_file.write('<td><b>Time Alive</b></td>\n') html_file.write('<td><b>RSS Mem Start</b></td>\n') html_file.write('<td><b>RSS Mem End</b></td>\n') html_file.write('<td><b>RSS Mem Change</b></td>\n') html_file.write('<td><b>PSS Mem Start</b></td>\n') html_file.write('<td><b>PSS Mem End</b></td>\n') html_file.write('<td><b>PSS Mem Change</b></td>\n') html_file.write('<td><b>CSV</b></td>\n') html_file.write('</tr>\n') # By Worker Type Memory Used for ordered_name in process_order: if ordered_name in process_results: for pid in process_results[ordered_name]: start = list(process_results[ordered_name][pid].keys())[0] end = list(process_results[ordered_name][pid].keys())[-1] timediff = end - start html_file.write('<tr>\n') if len(process_results[ordered_name]) > 1: html_file.write('<td><a href=\'#{}\'>{}</a></td>\n'.format(ordered_name, ordered_name)) html_file.write('<td><a href=\'graphs/{}-{}.png\'>{}</a></td>\n'.format( ordered_name, pid, pid)) else: html_file.write('<td>{}</td>\n'.format(ordered_name)) html_file.write('<td><a href=\'#{}-{}.png\'>{}</a></td>\n'.format( ordered_name, pid, pid)) html_file.write('<td>{}</td>\n'.format(start.replace(microsecond=0))) html_file.write('<td>{}</td>\n'.format(end.replace(microsecond=0))) html_file.write('<td>{}</td>\n'.format(str(timediff).partition('.')[0])) rss_change = process_results[ordered_name][pid][end]['rss'] - \ process_results[ordered_name][pid][start]['rss'] html_file.write('<td>{}</td>\n'.format( round(process_results[ordered_name][pid][start]['rss'], 2))) html_file.write('<td>{}</td>\n'.format( round(process_results[ordered_name][pid][end]['rss'], 2))) html_file.write('<td>{}</td>\n'.format(round(rss_change, 2))) pss_change = process_results[ordered_name][pid][end]['pss'] - \ process_results[ordered_name][pid][start]['pss'] html_file.write('<td>{}</td>\n'.format( round(process_results[ordered_name][pid][start]['pss'], 2))) html_file.write('<td>{}</td>\n'.format( round(process_results[ordered_name][pid][end]['pss'], 2))) html_file.write('<td>{}</td>\n'.format(round(pss_change, 2))) html_file.write('<td><a href=\'rawdata/{}-{}.csv\'>csv</a></td>\n'.format( pid, ordered_name)) html_file.write('</tr>\n') else: logger.debug('Process/Worker not part of test: {}'.format(ordered_name)) html_file.write('</table>\n') # Worker Graphs for ordered_name in process_order: if ordered_name in process_results: html_file.write('<tr><td>\n') html_file.write('<div id=\'{}\'>Process name: {}</div><br>\n'.format( ordered_name, ordered_name)) if len(process_results[ordered_name]) > 1: file_name = '{}-all.png'.format(ordered_name) html_file.write('<img id=\'{}\' src=\'graphs/{}\'><br>\n'.format(file_name, file_name)) else: for pid in sorted(process_results[ordered_name]): file_name = '{}-{}.png'.format(ordered_name, pid) html_file.write('<img id=\'{}\' src=\'graphs/{}\'><br>\n'.format( file_name, file_name)) html_file.write('</td></tr>\n') html_file.write('</table>\n') html_file.write('</body>\n') html_file.write('</html>\n') timediff = time.time() - starttime logger.info('Generated Summary html in: {}'.format(timediff)) def generate_workload_html(directory, ver, scenario_data, provider_names, grafana_urls): starttime = time.time() file_name = str(directory.join('workload.html')) with open(file_name, 'w') as html_file: html_file.write('<html>\n') html_file.write('<head><title>{} - {}</title></head>'.format( scenario_data['test_name'], provider_names)) html_file.write('<body>\n') html_file.write('<b>CFME {} {} Test Results</b><br>\n'.format(ver, scenario_data['test_name'].title())) html_file.write('<b>Appliance Roles:</b> {}<br>\n'.format( scenario_data['appliance_roles'].replace(',', ', '))) html_file.write('<b>Provider(s):</b> {}<br>\n'.format(provider_names)) html_file.write('<b><a href=\'https://{}/\' target="_blank">{}</a></b>\n'.format( scenario_data['appliance_ip'], scenario_data['appliance_name'])) if grafana_urls: for g_name in sorted(grafana_urls.keys()): html_file.write( ' : <b><a href=\'{}\' target="_blank">{}</a></b>'.format(grafana_urls[g_name], g_name)) html_file.write('<br>\n') html_file.write('<b><a href=\'{}-summary.csv\'>Summary CSV</a></b>'.format(ver)) html_file.write(' : <b><a href=\'index.html\'>Memory Info</a></b>') html_file.write(' : <b><a href=\'graphs/\'>Graphs directory</a></b>\n') html_file.write(' : <b><a href=\'rawdata/\'>CSVs directory</a></b><br>\n') html_file.write('<br><b>Scenario Data: </b><br>\n') yaml_html = get_scenario_html(scenario_data['scenario']) html_file.write(yaml_html + '\n') html_file.write('<br>\n<br>\n<br>\n<b>Quantifier Data: </b>\n<br>\n<br>\n<br>\n<br>\n') html_file.write('<table border="1">\n') html_file.write('<tr>\n') html_file.write('<td><b><font size="4"> System Information</font></b></td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>\n') system_path = ('../version_info/system.csv') html_file.write('<a href="{}" download="System_Versions-{}-{}"> System Versions</a>' .format(system_path, test_ts, scenario_data['scenario']['name'])) html_file.write('</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>&nbsp</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>&nbsp</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td><b><font size="4"> Process Information</font></b></td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>\n') process_path = ('../version_info/processes.csv') html_file.write('<a href="{}" download="Process_Versions-{}-{}"> Process Versions</a>' .format(process_path, test_ts, scenario_data['scenario']['name'])) html_file.write('</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>&nbsp</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>&nbsp</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td><b><font size="4"> Ruby Gem Information</font></b></td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>\n') gems_path = ('../version_info/gems.csv') html_file.write('<a href="{}" download="Gem_Versions-{}-{}"> Ruby Gem Versions</a>' .format(gems_path, test_ts, scenario_data['scenario']['name'])) html_file.write('</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>&nbsp</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>&nbsp</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td><b><font size="4"> RPM Information</font></b></td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>\n') rpms_path = ('../version_info/rpms.csv') html_file.write('<a href="{}" download="RPM_Versions-{}-{}"> RPM Versions</a>' .format(rpms_path, test_ts, scenario_data['scenario']['name'])) html_file.write('</td>\n') html_file.write('</tr>\n') html_file.write('</table>\n') html_file.write('</body>\n') html_file.write('</html>\n') timediff = time.time() - starttime logger.info('Generated Workload html in: {}'.format(timediff)) def add_workload_quantifiers(quantifiers, scenario_data): starttime = time.time() ver = current_version() workload_path = results_path.join('{}-{}-{}'.format(test_ts, scenario_data['test_dir'], ver)) directory = workload_path.join(scenario_data['scenario']['name']) file_name = str(directory.join('workload.html')) marker = '<b>Quantifier Data: </b>' yaml_dict = quantifiers yaml_string = str(json.dumps(yaml_dict, indent=4)) yaml_html = yaml_string.replace('\n', '<br>\n') with open(file_name, 'r+') as html_file: line = '' while marker not in line: line = html_file.readline() marker_pos = html_file.tell() remainder = html_file.read() html_file.seek(marker_pos) html_file.write('{} \n'.format(yaml_html)) html_file.write(remainder) timediff = time.time() - starttime logger.info('Added quantifiers in: {}'.format(timediff)) def get_scenario_html(scenario_data): scenario_dict = create_dict(scenario_data) scenario_yaml = yaml.safe_dump(scenario_dict) scenario_html = scenario_yaml.replace('\n', '<br>\n') scenario_html = scenario_html.replace(', ', '<br>\n &nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;') scenario_html = scenario_html.replace(' ', '&nbsp;') scenario_html = scenario_html.replace('[', '<br>\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;') scenario_html = scenario_html.replace(']', '\n') return scenario_html def create_dict(attr_dict): main_dict = dict(attr_dict) for key, value in main_dict.items(): if type(value) == AttrDict: main_dict[key] = create_dict(value) return main_dict def graph_appliance_measurements(graphs_path, ver, appliance_results, use_slab, provider_names): import matplotlib as mpl mpl.use('Agg') import matplotlib.dates as mdates import matplotlib.pyplot as plt from cycler import cycler starttime = time.time() dates = list(appliance_results.keys()) total_memory_list = list(appliance_results[ts]['total'] for ts in appliance_results.keys()) free_memory_list = list(appliance_results[ts]['free'] for ts in appliance_results.keys()) used_memory_list = list(appliance_results[ts]['used'] for ts in appliance_results.keys()) buffers_memory_list = list(appliance_results[ts]['buffers'] for ts in appliance_results.keys()) cache_memory_list = list(appliance_results[ts]['cached'] for ts in appliance_results.keys()) slab_memory_list = list(appliance_results[ts]['slab'] for ts in appliance_results.keys()) swap_total_list = list(appliance_results[ts]['swap_total'] for ts in appliance_results.keys()) swap_free_list = list(appliance_results[ts]['swap_free'] for ts in appliance_results.keys()) # Stack Plot Memory Usage file_name = graphs_path.join('{}-appliance_memory.png'.format(ver)) mpl.rcParams['axes.prop_cycle'] = cycler('color', ['firebrick', 'coral', 'steelblue', 'forestgreen']) fig, ax = plt.subplots() plt.title('Provider(s): {}\nAppliance Memory'.format(provider_names)) plt.xlabel('Date / Time') plt.ylabel('Memory (MiB)') if use_slab: y = [used_memory_list, slab_memory_list, cache_memory_list, free_memory_list] else: y = [used_memory_list, buffers_memory_list, cache_memory_list, free_memory_list] plt.stackplot(dates, *y, baseline='zero') ax.annotate(str(round(total_memory_list[0], 2)), xy=(dates[0], total_memory_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(total_memory_list[-1], 2)), xy=(dates[-1], total_memory_list[-1]), xytext=(4, -4), textcoords='offset points') if use_slab: ax.annotate(str(round(slab_memory_list[0], 2)), xy=(dates[0], used_memory_list[0] + slab_memory_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(slab_memory_list[-1], 2)), xy=(dates[-1], used_memory_list[-1] + slab_memory_list[-1]), xytext=(4, -4), textcoords='offset points') ax.annotate(str(round(cache_memory_list[0], 2)), xy=(dates[0], used_memory_list[0] + slab_memory_list[0] + cache_memory_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(cache_memory_list[-1], 2)), xy=( dates[-1], used_memory_list[-1] + slab_memory_list[-1] + cache_memory_list[-1]), xytext=(4, -4), textcoords='offset points') else: ax.annotate(str(round(buffers_memory_list[0], 2)), xy=( dates[0], used_memory_list[0] + buffers_memory_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(buffers_memory_list[-1], 2)), xy=(dates[-1], used_memory_list[-1] + buffers_memory_list[-1]), xytext=(4, -4), textcoords='offset points') ax.annotate(str(round(cache_memory_list[0], 2)), xy=(dates[0], used_memory_list[0] + buffers_memory_list[0] + cache_memory_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(cache_memory_list[-1], 2)), xy=( dates[-1], used_memory_list[-1] + buffers_memory_list[-1] + cache_memory_list[-1]), xytext=(4, -4), textcoords='offset points') ax.annotate(str(round(used_memory_list[0], 2)), xy=(dates[0], used_memory_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(used_memory_list[-1], 2)), xy=(dates[-1], used_memory_list[-1]), xytext=(4, -4), textcoords='offset points') datefmt = mdates.DateFormatter('%m-%d %H-%M') ax.xaxis.set_major_formatter(datefmt) ax.grid(True) p1 = plt.Rectangle((0, 0), 1, 1, fc='firebrick') p2 = plt.Rectangle((0, 0), 1, 1, fc='coral') p3 = plt.Rectangle((0, 0), 1, 1, fc='steelblue') p4 = plt.Rectangle((0, 0), 1, 1, fc='forestgreen') if use_slab: ax.legend([p1, p2, p3, p4], ['Used', 'Slab', 'Cached', 'Free'], bbox_to_anchor=(1.45, 0.22), fancybox=True) else: ax.legend([p1, p2, p3, p4], ['Used', 'Buffers', 'Cached', 'Free'], bbox_to_anchor=(1.45, 0.22), fancybox=True) fig.autofmt_xdate() plt.savefig(str(file_name), bbox_inches='tight') plt.close() # Stack Plot Swap usage mpl.rcParams['axes.prop_cycle'] = cycler('color', ['firebrick', 'forestgreen']) file_name = graphs_path.join('{}-appliance_swap.png'.format(ver)) fig, ax = plt.subplots() plt.title('Provider(s): {}\nAppliance Swap'.format(provider_names)) plt.xlabel('Date / Time') plt.ylabel('Swap (MiB)') swap_used_list = [t - f for f, t in zip(swap_free_list, swap_total_list)] y = [swap_used_list, swap_free_list] plt.stackplot(dates, *y, baseline='zero') ax.annotate(str(round(swap_total_list[0], 2)), xy=(dates[0], swap_total_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(swap_total_list[-1], 2)), xy=(dates[-1], swap_total_list[-1]), xytext=(4, -4), textcoords='offset points') ax.annotate(str(round(swap_used_list[0], 2)), xy=(dates[0], swap_used_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(swap_used_list[-1], 2)), xy=(dates[-1], swap_used_list[-1]), xytext=(4, -4), textcoords='offset points') datefmt = mdates.DateFormatter('%m-%d %H-%M') ax.xaxis.set_major_formatter(datefmt) ax.grid(True) p1 = plt.Rectangle((0, 0), 1, 1, fc='firebrick') p2 = plt.Rectangle((0, 0), 1, 1, fc='forestgreen') ax.legend([p1, p2], ['Used Swap', 'Free Swap'], bbox_to_anchor=(1.45, 0.22), fancybox=True) fig.autofmt_xdate() plt.savefig(str(file_name), bbox_inches='tight') plt.close() # Reset Colors mpl.rcdefaults() timediff = time.time() - starttime logger.info('Plotted Appliance Memory in: {}'.format(timediff)) def graph_all_miq_workers(graph_file_path, process_results, provider_names): import matplotlib as mpl mpl.use('Agg') import matplotlib.dates as mdates import matplotlib.pyplot as plt starttime = time.time() file_name = graph_file_path.join('all-processes.png') fig, ax = plt.subplots() plt.title('Provider(s): {}\nAll Workers/Monitored Processes'.format(provider_names)) plt.xlabel('Date / Time') plt.ylabel('Memory (MiB)') for process_name in process_results: if 'Worker' in process_name or 'Handler' in process_name or 'Catcher' in process_name: for process_pid in process_results[process_name]: dates = list(process_results[process_name][process_pid].keys()) rss_samples = list(process_results[process_name][process_pid][ts]['rss'] for ts in process_results[process_name][process_pid].keys()) vss_samples = list(process_results[process_name][process_pid][ts]['vss'] for ts in process_results[process_name][process_pid].keys()) plt.plot(dates, rss_samples, linewidth=1, label='{} {} RSS'.format(process_pid, process_name)) plt.plot(dates, vss_samples, linewidth=1, label='{} {} VSS'.format( process_pid, process_name)) datefmt = mdates.DateFormatter('%m-%d %H-%M') ax.xaxis.set_major_formatter(datefmt) ax.grid(True) plt.legend(loc='upper center', bbox_to_anchor=(1.2, 0.1), fancybox=True) fig.autofmt_xdate() plt.savefig(str(file_name), bbox_inches='tight') plt.close() timediff = time.time() - starttime logger.info('Plotted All Type/Process Memory in: {}'.format(timediff)) def graph_individual_process_measurements(graph_file_path, process_results, provider_names): import matplotlib as mpl mpl.use('Agg') import matplotlib.dates as mdates import matplotlib.pyplot as plt starttime = time.time() for process_name in process_results: for process_pid in process_results[process_name]: file_name = graph_file_path.join('{}-{}.png'.format(process_name, process_pid)) dates = list(process_results[process_name][process_pid].keys()) rss_samples = list(process_results[process_name][process_pid][ts]['rss'] for ts in process_results[process_name][process_pid].keys()) pss_samples = list(process_results[process_name][process_pid][ts]['pss'] for ts in process_results[process_name][process_pid].keys()) uss_samples = list(process_results[process_name][process_pid][ts]['uss'] for ts in process_results[process_name][process_pid].keys()) vss_samples = list(process_results[process_name][process_pid][ts]['vss'] for ts in process_results[process_name][process_pid].keys()) swap_samples = list(process_results[process_name][process_pid][ts]['swap'] for ts in process_results[process_name][process_pid].keys()) fig, ax = plt.subplots() plt.title('Provider(s)/Size: {}\nProcess/Worker: {}\nPID: {}'.format(provider_names, process_name, process_pid)) plt.xlabel('Date / Time') plt.ylabel('Memory (MiB)') plt.plot(dates, rss_samples, linewidth=1, label='RSS') plt.plot(dates, pss_samples, linewidth=1, label='PSS') plt.plot(dates, uss_samples, linewidth=1, label='USS') plt.plot(dates, vss_samples, linewidth=1, label='VSS') plt.plot(dates, swap_samples, linewidth=1, label='Swap') if rss_samples: ax.annotate(str(round(rss_samples[0], 2)), xy=(dates[0], rss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(rss_samples[-1], 2)), xy=(dates[-1], rss_samples[-1]), xytext=(4, -4), textcoords='offset points') if pss_samples: ax.annotate(str(round(pss_samples[0], 2)), xy=(dates[0], pss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(pss_samples[-1], 2)), xy=(dates[-1], pss_samples[-1]), xytext=(4, -4), textcoords='offset points') if uss_samples: ax.annotate(str(round(uss_samples[0], 2)), xy=(dates[0], uss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(uss_samples[-1], 2)), xy=(dates[-1], uss_samples[-1]), xytext=(4, -4), textcoords='offset points') if vss_samples: ax.annotate(str(round(vss_samples[0], 2)), xy=(dates[0], vss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(vss_samples[-1], 2)), xy=(dates[-1], vss_samples[-1]), xytext=(4, -4), textcoords='offset points') if swap_samples: ax.annotate(str(round(swap_samples[0], 2)), xy=(dates[0], swap_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(swap_samples[-1], 2)), xy=(dates[-1], swap_samples[-1]), xytext=(4, -4), textcoords='offset points') datefmt = mdates.DateFormatter('%m-%d %H-%M') ax.xaxis.set_major_formatter(datefmt) ax.grid(True) plt.legend(loc='upper center', bbox_to_anchor=(1.2, 0.1), fancybox=True) fig.autofmt_xdate() plt.savefig(str(file_name), bbox_inches='tight') plt.close() timediff = time.time() - starttime logger.info('Plotted Individual Process Memory in: {}'.format(timediff)) def graph_same_miq_workers(graph_file_path, process_results, provider_names): import matplotlib as mpl mpl.use('Agg') import matplotlib.dates as mdates import matplotlib.pyplot as plt starttime = time.time() for process_name in process_results: if len(process_results[process_name]) > 1: logger.debug('Plotting {} {} processes on single graph.'.format( len(process_results[process_name]), process_name)) file_name = graph_file_path.join('{}-all.png'.format(process_name)) fig, ax = plt.subplots() pids = 'PIDs: ' for i, pid in enumerate(process_results[process_name], 1): pids = '{}{}'.format(pids, '{},{}'.format(pid, [' ', '\n'][i % 6 == 0])) pids = pids[0:-2] plt.title('Provider: {}\nProcess/Worker: {}\n{}'.format(provider_names, process_name, pids)) plt.xlabel('Date / Time') plt.ylabel('Memory (MiB)') for process_pid in process_results[process_name]: dates = list(process_results[process_name][process_pid].keys()) rss_samples = list(process_results[process_name][process_pid][ts]['rss'] for ts in process_results[process_name][process_pid].keys()) pss_samples = list(process_results[process_name][process_pid][ts]['pss'] for ts in process_results[process_name][process_pid].keys()) uss_samples = list(process_results[process_name][process_pid][ts]['uss'] for ts in process_results[process_name][process_pid].keys()) vss_samples = list(process_results[process_name][process_pid][ts]['vss'] for ts in process_results[process_name][process_pid].keys()) swap_samples = list(process_results[process_name][process_pid][ts]['swap'] for ts in process_results[process_name][process_pid].keys()) plt.plot(dates, rss_samples, linewidth=1, label='{} RSS'.format(process_pid)) plt.plot(dates, pss_samples, linewidth=1, label='{} PSS'.format(process_pid)) plt.plot(dates, uss_samples, linewidth=1, label='{} USS'.format(process_pid)) plt.plot(dates, vss_samples, linewidth=1, label='{} VSS'.format(process_pid)) plt.plot(dates, swap_samples, linewidth=1, label='{} SWAP'.format(process_pid)) if rss_samples: ax.annotate(str(round(rss_samples[0], 2)), xy=(dates[0], rss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(rss_samples[-1], 2)), xy=(dates[-1], rss_samples[-1]), xytext=(4, -4), textcoords='offset points') if pss_samples: ax.annotate(str(round(pss_samples[0], 2)), xy=(dates[0], pss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(pss_samples[-1], 2)), xy=(dates[-1], pss_samples[-1]), xytext=(4, -4), textcoords='offset points') if uss_samples: ax.annotate(str(round(uss_samples[0], 2)), xy=(dates[0], uss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(uss_samples[-1], 2)), xy=(dates[-1], uss_samples[-1]), xytext=(4, -4), textcoords='offset points') if vss_samples: ax.annotate(str(round(vss_samples[0], 2)), xy=(dates[0], vss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(vss_samples[-1], 2)), xy=(dates[-1], vss_samples[-1]), xytext=(4, -4), textcoords='offset points') if swap_samples: ax.annotate(str(round(swap_samples[0], 2)), xy=(dates[0], swap_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(swap_samples[-1], 2)), xy=(dates[-1], swap_samples[-1]), xytext=(4, -4), textcoords='offset points') datefmt = mdates.DateFormatter('%m-%d %H-%M') ax.xaxis.set_major_formatter(datefmt) ax.grid(True) plt.legend(loc='upper center', bbox_to_anchor=(1.2, 0.1), fancybox=True) fig.autofmt_xdate() plt.savefig(str(file_name), bbox_inches='tight') plt.close() timediff = time.time() - starttime logger.info('Plotted Same Type/Process Memory in: {}'.format(timediff)) def summary_csv_measurement_dump(csv_file, process_results, measurement): csv_file.write('---------------------------------------------\n') csv_file.write('Per Process {} Memory Usage\n'.format(measurement.upper())) csv_file.write('---------------------------------------------\n') csv_file.write('Process/Worker Type,PID,Start of test,End of test\n') for ordered_name in process_order: if ordered_name in process_results: for process_pid in sorted(process_results[ordered_name]): start = list(process_results[ordered_name][process_pid].keys())[0] end = list(process_results[ordered_name][process_pid].keys())[-1] csv_file.write('{},{},{},{}\n'.format(ordered_name, process_pid, round(process_results[ordered_name][process_pid][start][measurement], 2), round(process_results[ordered_name][process_pid][end][measurement], 2)))
import pytest from fauxfactory import gen_numeric_string from widgetastic_patternfly import Button from cfme import test_requirements from cfme.services.catalogs.catalog_items import DetailsCatalogItemView from cfme.utils.appliance import ViaSSUI from cfme.utils.appliance import ViaUI from cfme.utils.appliance.implementations.ssui import navigate_to as ssui_nav from cfme.utils.appliance.implementations.ui import navigate_to as ui_nav pytestmark = [pytest.mark.tier(2), test_requirements.custom_button] def test_custom_group_on_catalog_item_crud(generic_catalog_item): """ Polarion: assignee: ndhandre initialEstimate: 1/8h caseimportance: medium caseposneg: positive testtype: functional startsin: 5.9 casecomponent: CustomButton tags: custom_button testSteps: 1. Add catalog_item 2. Goto catalog detail page and select `add group` from toolbar 3. Fill info and save button 4. Delete created button group Bugzilla: 1687289 """ btn_data = { "text": "button_{}".format(gen_numeric_string(3)), "hover": "hover_{}".format(gen_numeric_string(3)), "image": "fa-user", } btn_gp = generic_catalog_item.add_button_group(**btn_data) view = generic_catalog_item.create_view(DetailsCatalogItemView) view.flash.assert_message('Button Group "{}" was added'.format(btn_data["hover"])) assert generic_catalog_item.button_group_exists(btn_gp) generic_catalog_item.delete_button_group(btn_gp) # TODO(BZ-1687289): add deletion flash assertion as BZ fix. assert not generic_catalog_item.button_group_exists(btn_gp) def test_custom_button_on_catalog_item_crud(generic_catalog_item): """ Polarion: assignee: ndhandre initialEstimate: 1/8h caseimportance: medium caseposneg: positive testtype: functional startsin: 5.9 casecomponent: CustomButton tags: custom_button testSteps: 1. Add catalog_item 2. Goto catalog detail page and select `add group` from toolbar 3. Fill info and save button 4. Delete created button group Bugzilla: 1687289 """ btn_data = { "text": "button_{}".format(gen_numeric_string(3)), "hover": "hover_{}".format(gen_numeric_string(3)), "image": "fa-user", } btn = generic_catalog_item.add_button(**btn_data) view = generic_catalog_item.create_view(DetailsCatalogItemView) view.flash.assert_message('Custom Button "{}" was added'.format(btn_data["hover"])) assert generic_catalog_item.button_exists(btn) generic_catalog_item.delete_button(btn) # TODO(BZ-1687289): add deletion flash assertion as BZ fix. assert not generic_catalog_item.button_exists(btn) def test_custom_button_unassigned_behavior_catalog_level(appliance, generic_service): """ Test unassigned custom button behavior catalog level Note: At catalog level unassigned button (not part of any group) should displayed for both OPS UI and SSUI. Polarion: assignee: ndhandre initialEstimate: 1/6h caseimportance: medium caseposneg: positive testtype: functional startsin: 5.9 casecomponent: CustomButton testSteps: 1. Create custom button directly on catalog item. 2. Check service details page for both OPS UI and SSUI; button should display. Bugzilla: 1653195 """ service, catalog_item = generic_service btn_data = { "text": "button_{}".format(gen_numeric_string(3)), "hover": "hover_{}".format(gen_numeric_string(3)), "image": "fa-user", } btn = catalog_item.add_button(**btn_data) assert catalog_item.button_exists(btn) for context in [ViaUI, ViaSSUI]: navigate_to = ssui_nav if context is ViaSSUI else ui_nav with appliance.context.use(context): view = navigate_to(service, "Details") button = Button(view, btn) assert button.is_displayed
Yadnyawalkya/integration_tests
cfme/tests/automate/custom_button/test_catalog_custom_button.py
cfme/utils/smem_memory_monitor.py
""" Fixtures for Capacity and Utilization """ import fauxfactory import pytest from cfme.utils import conf from cfme.utils.ssh import SSHClient @pytest.fixture(scope="module") def enable_candu(appliance): candu = appliance.collections.candus server_settings = appliance.server.settings original_roles = server_settings.server_roles_db server_settings.enable_server_roles( 'ems_metrics_coordinator', 'ems_metrics_collector', 'ems_metrics_processor' ) server_settings.disable_server_roles( 'automate', 'smartstate' ) candu.enable_all() yield candu.disable_all() server_settings.update_server_roles_db(original_roles) @pytest.fixture(scope="module") def collect_data(appliance, provider, interval='hourly', back='7.days'): """Collect hourly back data for vsphere provider""" vm_name = provider.data['cap_and_util']['chargeback_vm'] # Capture real-time C&U data ret = appliance.ssh_client.run_rails_command( "\"vm = Vm.where(:ems_id => {}).where(:name => {})[0];\ vm.perf_capture({}, {}.ago.utc, Time.now.utc)\"" .format(provider.id, repr(vm_name), repr(interval), back)) return ret.success @pytest.fixture(scope="module") def enable_candu_category(appliance): """Enable capture C&U Data for tag category location by navigating to the Configuration -> Region page. Click 'Tags' tab , select required company category under 'My Company Categories' and enable 'Capture C & U Data' for the category. """ collection = appliance.collections.categories location_category = collection.instantiate(name="location", display_name="Location") if not location_category.capture_candu: location_category.update(updates={"capture_candu": True}) return location_category @pytest.fixture(scope="function") def candu_tag_vm(provider, enable_candu_category): """Add location tag to VM if not available""" collection = provider.appliance.provider_based_collection(provider) vm = collection.instantiate('cu-24x7', provider) tag = enable_candu_category.collections.tags.instantiate(name="london", display_name="London") vm.add_tag(tag, exists_check=True) return vm @pytest.fixture(scope="module") def temp_appliance_extended_db(temp_appliance_preconfig): app = temp_appliance_preconfig app.evmserverd.stop() app.db.extend_partition() app.evmserverd.start() return app @pytest.fixture(scope="module") def candu_db_restore(temp_appliance_extended_db): app = temp_appliance_extended_db # get DB backup file db_storage_hostname = conf.cfme_data.bottlenecks.hostname db_storage_ssh = SSHClient(hostname=db_storage_hostname, **conf.credentials.bottlenecks) rand_filename = "/tmp/db.backup_{}".format(fauxfactory.gen_alphanumeric()) db_storage_ssh.get_file("{}/candu.db.backup".format( conf.cfme_data.bottlenecks.backup_path), rand_filename) app.ssh_client.put_file(rand_filename, "/tmp/evm_db.backup") app.evmserverd.stop() app.db.drop() app.db.create() app.db.restore() # When you load a database from an older version of the application, you always need to # run migrations. # https://bugzilla.redhat.com/show_bug.cgi?id=1643250 app.db.migrate() app.db.fix_auth_key() app.db.fix_auth_dbyml() app.evmserverd.start() app.wait_for_web_ui()
import pytest from fauxfactory import gen_numeric_string from widgetastic_patternfly import Button from cfme import test_requirements from cfme.services.catalogs.catalog_items import DetailsCatalogItemView from cfme.utils.appliance import ViaSSUI from cfme.utils.appliance import ViaUI from cfme.utils.appliance.implementations.ssui import navigate_to as ssui_nav from cfme.utils.appliance.implementations.ui import navigate_to as ui_nav pytestmark = [pytest.mark.tier(2), test_requirements.custom_button] def test_custom_group_on_catalog_item_crud(generic_catalog_item): """ Polarion: assignee: ndhandre initialEstimate: 1/8h caseimportance: medium caseposneg: positive testtype: functional startsin: 5.9 casecomponent: CustomButton tags: custom_button testSteps: 1. Add catalog_item 2. Goto catalog detail page and select `add group` from toolbar 3. Fill info and save button 4. Delete created button group Bugzilla: 1687289 """ btn_data = { "text": "button_{}".format(gen_numeric_string(3)), "hover": "hover_{}".format(gen_numeric_string(3)), "image": "fa-user", } btn_gp = generic_catalog_item.add_button_group(**btn_data) view = generic_catalog_item.create_view(DetailsCatalogItemView) view.flash.assert_message('Button Group "{}" was added'.format(btn_data["hover"])) assert generic_catalog_item.button_group_exists(btn_gp) generic_catalog_item.delete_button_group(btn_gp) # TODO(BZ-1687289): add deletion flash assertion as BZ fix. assert not generic_catalog_item.button_group_exists(btn_gp) def test_custom_button_on_catalog_item_crud(generic_catalog_item): """ Polarion: assignee: ndhandre initialEstimate: 1/8h caseimportance: medium caseposneg: positive testtype: functional startsin: 5.9 casecomponent: CustomButton tags: custom_button testSteps: 1. Add catalog_item 2. Goto catalog detail page and select `add group` from toolbar 3. Fill info and save button 4. Delete created button group Bugzilla: 1687289 """ btn_data = { "text": "button_{}".format(gen_numeric_string(3)), "hover": "hover_{}".format(gen_numeric_string(3)), "image": "fa-user", } btn = generic_catalog_item.add_button(**btn_data) view = generic_catalog_item.create_view(DetailsCatalogItemView) view.flash.assert_message('Custom Button "{}" was added'.format(btn_data["hover"])) assert generic_catalog_item.button_exists(btn) generic_catalog_item.delete_button(btn) # TODO(BZ-1687289): add deletion flash assertion as BZ fix. assert not generic_catalog_item.button_exists(btn) def test_custom_button_unassigned_behavior_catalog_level(appliance, generic_service): """ Test unassigned custom button behavior catalog level Note: At catalog level unassigned button (not part of any group) should displayed for both OPS UI and SSUI. Polarion: assignee: ndhandre initialEstimate: 1/6h caseimportance: medium caseposneg: positive testtype: functional startsin: 5.9 casecomponent: CustomButton testSteps: 1. Create custom button directly on catalog item. 2. Check service details page for both OPS UI and SSUI; button should display. Bugzilla: 1653195 """ service, catalog_item = generic_service btn_data = { "text": "button_{}".format(gen_numeric_string(3)), "hover": "hover_{}".format(gen_numeric_string(3)), "image": "fa-user", } btn = catalog_item.add_button(**btn_data) assert catalog_item.button_exists(btn) for context in [ViaUI, ViaSSUI]: navigate_to = ssui_nav if context is ViaSSUI else ui_nav with appliance.context.use(context): view = navigate_to(service, "Details") button = Button(view, btn) assert button.is_displayed
Yadnyawalkya/integration_tests
cfme/tests/automate/custom_button/test_catalog_custom_button.py
cfme/fixtures/candu.py
"""Support for retrieving meteorological data from Dark Sky.""" from datetime import datetime, timedelta import logging from requests.exceptions import ( ConnectionError as ConnectError, HTTPError, Timeout) import voluptuous as vol from homeassistant.components.weather import ( ATTR_FORECAST_CONDITION, ATTR_FORECAST_PRECIPITATION, ATTR_FORECAST_TEMP, ATTR_FORECAST_TEMP_LOW, ATTR_FORECAST_TIME, ATTR_FORECAST_WIND_BEARING, ATTR_FORECAST_WIND_SPEED, PLATFORM_SCHEMA, WeatherEntity) from homeassistant.const import ( CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_MODE, CONF_NAME, PRESSURE_HPA, PRESSURE_INHG, TEMP_CELSIUS, TEMP_FAHRENHEIT) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle from homeassistant.util.pressure import convert as convert_pressure _LOGGER = logging.getLogger(__name__) ATTRIBUTION = "Powered by Dark Sky" FORECAST_MODE = ['hourly', 'daily'] MAP_CONDITION = { 'clear-day': 'sunny', 'clear-night': 'clear-night', 'rain': 'rainy', 'snow': 'snowy', 'sleet': 'snowy-rainy', 'wind': 'windy', 'fog': 'fog', 'cloudy': 'cloudy', 'partly-cloudy-day': 'partlycloudy', 'partly-cloudy-night': 'partlycloudy', 'hail': 'hail', 'thunderstorm': 'lightning', 'tornado': None, } CONF_UNITS = 'units' DEFAULT_NAME = 'Dark Sky' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_LATITUDE): cv.latitude, vol.Optional(CONF_LONGITUDE): cv.longitude, vol.Optional(CONF_MODE, default='hourly'): vol.In(FORECAST_MODE), vol.Optional(CONF_UNITS): vol.In(['auto', 'si', 'us', 'ca', 'uk', 'uk2']), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }) MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=3) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Dark Sky weather.""" latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) name = config.get(CONF_NAME) mode = config.get(CONF_MODE) units = config.get(CONF_UNITS) if not units: units = 'ca' if hass.config.units.is_metric else 'us' dark_sky = DarkSkyData( config.get(CONF_API_KEY), latitude, longitude, units) add_entities([DarkSkyWeather(name, dark_sky, mode)], True) class DarkSkyWeather(WeatherEntity): """Representation of a weather condition.""" def __init__(self, name, dark_sky, mode): """Initialize Dark Sky weather.""" self._name = name self._dark_sky = dark_sky self._mode = mode self._ds_data = None self._ds_currently = None self._ds_hourly = None self._ds_daily = None @property def attribution(self): """Return the attribution.""" return ATTRIBUTION @property def name(self): """Return the name of the sensor.""" return self._name @property def temperature(self): """Return the temperature.""" return self._ds_currently.get('temperature') @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_FAHRENHEIT if 'us' in self._dark_sky.units \ else TEMP_CELSIUS @property def humidity(self): """Return the humidity.""" return round(self._ds_currently.get('humidity') * 100.0, 2) @property def wind_speed(self): """Return the wind speed.""" return self._ds_currently.get('windSpeed') @property def wind_bearing(self): """Return the wind bearing.""" return self._ds_currently.get('windBearing') @property def ozone(self): """Return the ozone level.""" return self._ds_currently.get('ozone') @property def pressure(self): """Return the pressure.""" pressure = self._ds_currently.get('pressure') if 'us' in self._dark_sky.units: return round( convert_pressure(pressure, PRESSURE_HPA, PRESSURE_INHG), 2) return pressure @property def visibility(self): """Return the visibility.""" return self._ds_currently.get('visibility') @property def condition(self): """Return the weather condition.""" return MAP_CONDITION.get(self._ds_currently.get('icon')) @property def forecast(self): """Return the forecast array.""" # Per conversation with Joshua Reyes of Dark Sky, to get the total # forecasted precipitation, you have to multiple the intensity by # the hours for the forecast interval def calc_precipitation(intensity, hours): amount = None if intensity is not None: amount = round((intensity * hours), 1) return amount if amount > 0 else None data = None if self._mode == 'daily': data = [{ ATTR_FORECAST_TIME: datetime.fromtimestamp(entry.d.get('time')).isoformat(), ATTR_FORECAST_TEMP: entry.d.get('temperatureHigh'), ATTR_FORECAST_TEMP_LOW: entry.d.get('temperatureLow'), ATTR_FORECAST_PRECIPITATION: calc_precipitation(entry.d.get('precipIntensity'), 24), ATTR_FORECAST_WIND_SPEED: entry.d.get('windSpeed'), ATTR_FORECAST_WIND_BEARING: entry.d.get('windBearing'), ATTR_FORECAST_CONDITION: MAP_CONDITION.get(entry.d.get('icon')) } for entry in self._ds_daily.data] else: data = [{ ATTR_FORECAST_TIME: datetime.fromtimestamp(entry.d.get('time')).isoformat(), ATTR_FORECAST_TEMP: entry.d.get('temperature'), ATTR_FORECAST_PRECIPITATION: calc_precipitation(entry.d.get('precipIntensity'), 1), ATTR_FORECAST_CONDITION: MAP_CONDITION.get(entry.d.get('icon')) } for entry in self._ds_hourly.data] return data def update(self): """Get the latest data from Dark Sky.""" self._dark_sky.update() self._ds_data = self._dark_sky.data self._ds_currently = self._dark_sky.currently.d self._ds_hourly = self._dark_sky.hourly self._ds_daily = self._dark_sky.daily class DarkSkyData: """Get the latest data from Dark Sky.""" def __init__(self, api_key, latitude, longitude, units): """Initialize the data object.""" self._api_key = api_key self.latitude = latitude self.longitude = longitude self.requested_units = units self.data = None self.currently = None self.hourly = None self.daily = None @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data from Dark Sky.""" import forecastio try: self.data = forecastio.load_forecast( self._api_key, self.latitude, self.longitude, units=self.requested_units) self.currently = self.data.currently() self.hourly = self.data.hourly() self.daily = self.data.daily() except (ConnectError, HTTPError, Timeout, ValueError) as error: _LOGGER.error("Unable to connect to Dark Sky. %s", error) self.data = None @property def units(self): """Get the unit system of returned data.""" if self.data is None: return None return self.data.json.get('flags').get('units')
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/darksky/weather.py
"""Support for monitoring pyLoad.""" from datetime import timedelta import logging from aiohttp.hdrs import CONTENT_TYPE import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_SSL, CONF_HOST, CONF_NAME, CONF_PORT, CONF_PASSWORD, CONF_USERNAME, CONTENT_TYPE_JSON, CONF_MONITORED_VARIABLES) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) DEFAULT_HOST = 'localhost' DEFAULT_NAME = 'pyLoad' DEFAULT_PORT = 8000 MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=15) SENSOR_TYPES = { 'speed': ['speed', 'Speed', 'MB/s'], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string, vol.Optional(CONF_MONITORED_VARIABLES, default=['speed']): vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=False): cv.boolean, vol.Optional(CONF_USERNAME): cv.string, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the pyLoad sensors.""" host = config.get(CONF_HOST) port = config.get(CONF_PORT) ssl = 's' if config.get(CONF_SSL) else '' name = config.get(CONF_NAME) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) monitored_types = config.get(CONF_MONITORED_VARIABLES) url = "http{}://{}:{}/api/".format(ssl, host, port) try: pyloadapi = PyLoadAPI( api_url=url, username=username, password=password) pyloadapi.update() except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as conn_err: _LOGGER.error("Error setting up pyLoad API: %s", conn_err) return False devices = [] for ng_type in monitored_types: new_sensor = PyLoadSensor( api=pyloadapi, sensor_type=SENSOR_TYPES.get(ng_type), client_name=name) devices.append(new_sensor) add_entities(devices, True) class PyLoadSensor(Entity): """Representation of a pyLoad sensor.""" def __init__(self, api, sensor_type, client_name): """Initialize a new pyLoad sensor.""" self._name = '{} {}'.format(client_name, sensor_type[1]) self.type = sensor_type[0] self.api = api self._state = None self._unit_of_measurement = sensor_type[2] @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement def update(self): """Update state of sensor.""" try: self.api.update() except requests.exceptions.ConnectionError: # Error calling the API, already logged in api.update() return if self.api.status is None: _LOGGER.debug("Update of %s requested, but no status is available", self._name) return value = self.api.status.get(self.type) if value is None: _LOGGER.warning("Unable to locate value for %s", self.type) return if "speed" in self.type and value > 0: # Convert download rate from Bytes/s to MBytes/s self._state = round(value / 2**20, 2) else: self._state = value class PyLoadAPI: """Simple wrapper for pyLoad's API.""" def __init__(self, api_url, username=None, password=None): """Initialize pyLoad API and set headers needed later.""" self.api_url = api_url self.status = None self.headers = {CONTENT_TYPE: CONTENT_TYPE_JSON} if username is not None and password is not None: self.payload = {'username': username, 'password': password} self.login = requests.post( '{}{}'.format(api_url, 'login'), data=self.payload, timeout=5) self.update() def post(self, method, params=None): """Send a POST request and return the response as a dict.""" payload = {'method': method} if params: payload['params'] = params try: response = requests.post( '{}{}'.format(self.api_url, 'statusServer'), json=payload, cookies=self.login.cookies, headers=self.headers, timeout=5) response.raise_for_status() _LOGGER.debug("JSON Response: %s", response.json()) return response.json() except requests.exceptions.ConnectionError as conn_exc: _LOGGER.error("Failed to update pyLoad status. Error: %s", conn_exc) raise @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Update cached response.""" self.status = self.post('speed')
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/pyload/sensor.py
"""Connect to a MySensors gateway via pymysensors API.""" import logging import voluptuous as vol from homeassistant.components.mqtt import ( valid_publish_topic, valid_subscribe_topic) from homeassistant.const import CONF_OPTIMISTIC from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from .const import ( ATTR_DEVICES, CONF_BAUD_RATE, CONF_DEVICE, CONF_GATEWAYS, CONF_NODES, CONF_PERSISTENCE, CONF_PERSISTENCE_FILE, CONF_RETAIN, CONF_TCP_PORT, CONF_TOPIC_IN_PREFIX, CONF_TOPIC_OUT_PREFIX, CONF_VERSION, DOMAIN, MYSENSORS_GATEWAYS) from .device import get_mysensors_devices from .gateway import get_mysensors_gateway, setup_gateways, finish_setup _LOGGER = logging.getLogger(__name__) CONF_DEBUG = 'debug' CONF_NODE_NAME = 'name' DEFAULT_BAUD_RATE = 115200 DEFAULT_TCP_PORT = 5003 DEFAULT_VERSION = '1.4' def has_all_unique_files(value): """Validate that all persistence files are unique and set if any is set.""" persistence_files = [ gateway.get(CONF_PERSISTENCE_FILE) for gateway in value] if None in persistence_files and any( name is not None for name in persistence_files): raise vol.Invalid( 'persistence file name of all devices must be set if any is set') if not all(name is None for name in persistence_files): schema = vol.Schema(vol.Unique()) schema(persistence_files) return value def is_persistence_file(value): """Validate that persistence file path ends in either .pickle or .json.""" if value.endswith(('.json', '.pickle')): return value raise vol.Invalid( '{} does not end in either `.json` or `.pickle`'.format(value)) def deprecated(key): """Mark key as deprecated in configuration.""" def validator(config): """Check if key is in config, log warning and remove key.""" if key not in config: return config _LOGGER.warning( '%s option for %s is deprecated. Please remove %s from your ' 'configuration file', key, DOMAIN, key) config.pop(key) return config return validator NODE_SCHEMA = vol.Schema({ cv.positive_int: { vol.Required(CONF_NODE_NAME): cv.string } }) GATEWAY_SCHEMA = { vol.Required(CONF_DEVICE): cv.string, vol.Optional(CONF_PERSISTENCE_FILE): vol.All(cv.string, is_persistence_file), vol.Optional(CONF_BAUD_RATE, default=DEFAULT_BAUD_RATE): cv.positive_int, vol.Optional(CONF_TCP_PORT, default=DEFAULT_TCP_PORT): cv.port, vol.Optional(CONF_TOPIC_IN_PREFIX): valid_subscribe_topic, vol.Optional(CONF_TOPIC_OUT_PREFIX): valid_publish_topic, vol.Optional(CONF_NODES, default={}): NODE_SCHEMA, } CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema(vol.All(deprecated(CONF_DEBUG), { vol.Required(CONF_GATEWAYS): vol.All( cv.ensure_list, has_all_unique_files, [GATEWAY_SCHEMA]), vol.Optional(CONF_OPTIMISTIC, default=False): cv.boolean, vol.Optional(CONF_PERSISTENCE, default=True): cv.boolean, vol.Optional(CONF_RETAIN, default=True): cv.boolean, vol.Optional(CONF_VERSION, default=DEFAULT_VERSION): cv.string, })) }, extra=vol.ALLOW_EXTRA) async def async_setup(hass, config): """Set up the MySensors component.""" gateways = await setup_gateways(hass, config) if not gateways: _LOGGER.error( "No devices could be setup as gateways, check your configuration") return False hass.data[MYSENSORS_GATEWAYS] = gateways hass.async_create_task(finish_setup(hass, config, gateways)) return True def _get_mysensors_name(gateway, node_id, child_id): """Return a name for a node child.""" node_name = '{} {}'.format( gateway.sensors[node_id].sketch_name, node_id) node_name = next( (node[CONF_NODE_NAME] for conf_id, node in gateway.nodes_config.items() if node.get(CONF_NODE_NAME) is not None and conf_id == node_id), node_name) return '{} {}'.format(node_name, child_id) @callback def setup_mysensors_platform( hass, domain, discovery_info, device_class, device_args=None, async_add_entities=None): """Set up a MySensors platform.""" # Only act if called via MySensors by discovery event. # Otherwise gateway is not set up. if not discovery_info: return None if device_args is None: device_args = () new_devices = [] new_dev_ids = discovery_info[ATTR_DEVICES] for dev_id in new_dev_ids: devices = get_mysensors_devices(hass, domain) if dev_id in devices: continue gateway_id, node_id, child_id, value_type = dev_id gateway = get_mysensors_gateway(hass, gateway_id) if not gateway: continue device_class_copy = device_class if isinstance(device_class, dict): child = gateway.sensors[node_id].children[child_id] s_type = gateway.const.Presentation(child.type).name device_class_copy = device_class[s_type] name = _get_mysensors_name(gateway, node_id, child_id) args_copy = (*device_args, gateway, node_id, child_id, name, value_type) devices[dev_id] = device_class_copy(*args_copy) new_devices.append(devices[dev_id]) if new_devices: _LOGGER.info("Adding new devices: %s", new_devices) if async_add_entities is not None: async_add_entities(new_devices, True) return new_devices
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/mysensors/__init__.py
"""Config flow to configure the RainMachine component.""" from collections import OrderedDict import voluptuous as vol from homeassistant import config_entries from homeassistant.core import callback from homeassistant.const import ( CONF_IP_ADDRESS, CONF_PASSWORD, CONF_PORT, CONF_SCAN_INTERVAL, CONF_SSL) from homeassistant.helpers import aiohttp_client from .const import DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DEFAULT_SSL, DOMAIN @callback def configured_instances(hass): """Return a set of configured RainMachine instances.""" return set( entry.data[CONF_IP_ADDRESS] for entry in hass.config_entries.async_entries(DOMAIN)) @config_entries.HANDLERS.register(DOMAIN) class RainMachineFlowHandler(config_entries.ConfigFlow): """Handle a RainMachine config flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def __init__(self): """Initialize the config flow.""" self.data_schema = OrderedDict() self.data_schema[vol.Required(CONF_IP_ADDRESS)] = str self.data_schema[vol.Required(CONF_PASSWORD)] = str self.data_schema[vol.Optional(CONF_PORT, default=DEFAULT_PORT)] = int async def _show_form(self, errors=None): """Show the form to the user.""" return self.async_show_form( step_id='user', data_schema=vol.Schema(self.data_schema), errors=errors if errors else {}, ) async def async_step_import(self, import_config): """Import a config entry from configuration.yaml.""" return await self.async_step_user(import_config) async def async_step_user(self, user_input=None): """Handle the start of the config flow.""" from regenmaschine import login from regenmaschine.errors import RainMachineError if not user_input: return await self._show_form() if user_input[CONF_IP_ADDRESS] in configured_instances(self.hass): return await self._show_form({ CONF_IP_ADDRESS: 'identifier_exists' }) websession = aiohttp_client.async_get_clientsession(self.hass) try: await login( user_input[CONF_IP_ADDRESS], user_input[CONF_PASSWORD], websession, port=user_input.get(CONF_PORT, DEFAULT_PORT), ssl=True) except RainMachineError: return await self._show_form({ CONF_PASSWORD: 'invalid_credentials' }) # Since the config entry doesn't allow for configuration of SSL, make # sure it's set: if user_input.get(CONF_SSL) is None: user_input[CONF_SSL] = DEFAULT_SSL # Timedeltas are easily serializable, so store the seconds instead: scan_interval = user_input.get( CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) user_input[CONF_SCAN_INTERVAL] = scan_interval.seconds # Unfortunately, RainMachine doesn't provide a way to refresh the # access token without using the IP address and password, so we have to # store it: return self.async_create_entry( title=user_input[CONF_IP_ADDRESS], data=user_input)
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/rainmachine/config_flow.py
"""Support for Fibaro thermostats.""" import logging from homeassistant.components.climate.const import ( STATE_AUTO, STATE_COOL, STATE_DRY, STATE_ECO, STATE_FAN_ONLY, STATE_HEAT, STATE_MANUAL, SUPPORT_TARGET_TEMPERATURE, SUPPORT_OPERATION_MODE, SUPPORT_FAN_MODE) from homeassistant.components.climate import ( ClimateDevice) from homeassistant.const import ( ATTR_TEMPERATURE, STATE_OFF, TEMP_CELSIUS, TEMP_FAHRENHEIT) from . import ( FIBARO_DEVICES, FibaroDevice) SPEED_LOW = 'low' SPEED_MEDIUM = 'medium' SPEED_HIGH = 'high' # State definitions missing from HA, but defined by Z-Wave standard. # We map them to states known supported by HA here: STATE_AUXILIARY = STATE_HEAT STATE_RESUME = STATE_HEAT STATE_MOIST = STATE_DRY STATE_AUTO_CHANGEOVER = STATE_AUTO STATE_ENERGY_HEAT = STATE_ECO STATE_ENERGY_COOL = STATE_COOL STATE_FULL_POWER = STATE_AUTO STATE_FORCE_OPEN = STATE_MANUAL STATE_AWAY = STATE_AUTO STATE_FURNACE = STATE_HEAT FAN_AUTO_HIGH = 'auto_high' FAN_AUTO_MEDIUM = 'auto_medium' FAN_CIRCULATION = 'circulation' FAN_HUMIDITY_CIRCULATION = 'humidity_circulation' FAN_LEFT_RIGHT = 'left_right' FAN_UP_DOWN = 'up_down' FAN_QUIET = 'quiet' _LOGGER = logging.getLogger(__name__) # SDS13781-10 Z-Wave Application Command Class Specification 2019-01-04 # Table 128, Thermostat Fan Mode Set version 4::Fan Mode encoding FANMODES = { 0: STATE_OFF, 1: SPEED_LOW, 2: FAN_AUTO_HIGH, 3: SPEED_HIGH, 4: FAN_AUTO_MEDIUM, 5: SPEED_MEDIUM, 6: FAN_CIRCULATION, 7: FAN_HUMIDITY_CIRCULATION, 8: FAN_LEFT_RIGHT, 9: FAN_UP_DOWN, 10: FAN_QUIET, 128: STATE_AUTO } # SDS13781-10 Z-Wave Application Command Class Specification 2019-01-04 # Table 130, Thermostat Mode Set version 3::Mode encoding. OPMODES = { 0: STATE_OFF, 1: STATE_HEAT, 2: STATE_COOL, 3: STATE_AUTO, 4: STATE_AUXILIARY, 5: STATE_RESUME, 6: STATE_FAN_ONLY, 7: STATE_FURNACE, 8: STATE_DRY, 9: STATE_MOIST, 10: STATE_AUTO_CHANGEOVER, 11: STATE_ENERGY_HEAT, 12: STATE_ENERGY_COOL, 13: STATE_AWAY, 15: STATE_FULL_POWER, 31: STATE_FORCE_OPEN } SUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE) def setup_platform(hass, config, add_entities, discovery_info=None): """Perform the setup for Fibaro controller devices.""" if discovery_info is None: return add_entities( [FibaroThermostat(device) for device in hass.data[FIBARO_DEVICES]['climate']], True) class FibaroThermostat(FibaroDevice, ClimateDevice): """Representation of a Fibaro Thermostat.""" def __init__(self, fibaro_device): """Initialize the Fibaro device.""" super().__init__(fibaro_device) self._temp_sensor_device = None self._target_temp_device = None self._op_mode_device = None self._fan_mode_device = None self._support_flags = 0 self.entity_id = 'climate.{}'.format(self.ha_id) self._fan_mode_to_state = {} self._fan_state_to_mode = {} self._op_mode_to_state = {} self._op_state_to_mode = {} siblings = fibaro_device.fibaro_controller.get_siblings( fibaro_device.id) tempunit = 'C' for device in siblings: if device.type == 'com.fibaro.temperatureSensor': self._temp_sensor_device = FibaroDevice(device) tempunit = device.properties.unit if 'setTargetLevel' in device.actions or \ 'setThermostatSetpoint' in device.actions: self._target_temp_device = FibaroDevice(device) self._support_flags |= SUPPORT_TARGET_TEMPERATURE tempunit = device.properties.unit if 'setMode' in device.actions or \ 'setOperatingMode' in device.actions: self._op_mode_device = FibaroDevice(device) self._support_flags |= SUPPORT_OPERATION_MODE if 'setFanMode' in device.actions: self._fan_mode_device = FibaroDevice(device) self._support_flags |= SUPPORT_FAN_MODE if tempunit == 'F': self._unit_of_temp = TEMP_FAHRENHEIT else: self._unit_of_temp = TEMP_CELSIUS if self._fan_mode_device: fan_modes = self._fan_mode_device.fibaro_device.\ properties.supportedModes.split(",") for mode in fan_modes: try: self._fan_mode_to_state[int(mode)] = FANMODES[int(mode)] self._fan_state_to_mode[FANMODES[int(mode)]] = int(mode) except KeyError: self._fan_mode_to_state[int(mode)] = 'unknown' if self._op_mode_device: prop = self._op_mode_device.fibaro_device.properties if "supportedOperatingModes" in prop: op_modes = prop.supportedOperatingModes.split(",") elif "supportedModes" in prop: op_modes = prop.supportedModes.split(",") for mode in op_modes: try: self._op_mode_to_state[int(mode)] = OPMODES[int(mode)] self._op_state_to_mode[OPMODES[int(mode)]] = int(mode) except KeyError: self._op_mode_to_state[int(mode)] = 'unknown' async def async_added_to_hass(self): """Call when entity is added to hass.""" _LOGGER.debug("Climate %s\n" "- _temp_sensor_device %s\n" "- _target_temp_device %s\n" "- _op_mode_device %s\n" "- _fan_mode_device %s", self.ha_id, self._temp_sensor_device.ha_id if self._temp_sensor_device else "None", self._target_temp_device.ha_id if self._target_temp_device else "None", self._op_mode_device.ha_id if self._op_mode_device else "None", self._fan_mode_device.ha_id if self._fan_mode_device else "None") await super().async_added_to_hass() # Register update callback for child devices siblings = self.fibaro_device.fibaro_controller.get_siblings( self.fibaro_device.id) for device in siblings: if device != self.fibaro_device: self.controller.register(device.id, self._update_callback) @property def supported_features(self): """Return the list of supported features.""" return self._support_flags @property def fan_list(self): """Return the list of available fan modes.""" if self._fan_mode_device is None: return None return list(self._fan_state_to_mode) @property def current_fan_mode(self): """Return the fan setting.""" if self._fan_mode_device is None: return None mode = int(self._fan_mode_device.fibaro_device.properties.mode) return self._fan_mode_to_state[mode] def set_fan_mode(self, fan_mode): """Set new target fan mode.""" if self._fan_mode_device is None: return self._fan_mode_device.action( "setFanMode", self._fan_state_to_mode[fan_mode]) @property def current_operation(self): """Return current operation ie. heat, cool, idle.""" if self._op_mode_device is None: return None if "operatingMode" in self._op_mode_device.fibaro_device.properties: mode = int(self._op_mode_device.fibaro_device. properties.operatingMode) else: mode = int(self._op_mode_device.fibaro_device.properties.mode) return self._op_mode_to_state.get(mode) @property def operation_list(self): """Return the list of available operation modes.""" if self._op_mode_device is None: return None return list(self._op_state_to_mode) def set_operation_mode(self, operation_mode): """Set new target operation mode.""" if self._op_mode_device is None: return if "setOperatingMode" in self._op_mode_device.fibaro_device.actions: self._op_mode_device.action( "setOperatingMode", self._op_state_to_mode[operation_mode]) elif "setMode" in self._op_mode_device.fibaro_device.actions: self._op_mode_device.action( "setMode", self._op_state_to_mode[operation_mode]) @property def temperature_unit(self): """Return the unit of measurement.""" return self._unit_of_temp @property def current_temperature(self): """Return the current temperature.""" if self._temp_sensor_device: device = self._temp_sensor_device.fibaro_device return float(device.properties.value) return None @property def target_temperature(self): """Return the temperature we try to reach.""" if self._target_temp_device: device = self._target_temp_device.fibaro_device return float(device.properties.targetLevel) return None def set_temperature(self, **kwargs): """Set new target temperatures.""" temperature = kwargs.get(ATTR_TEMPERATURE) target = self._target_temp_device if temperature is not None: if "setThermostatSetpoint" in target.fibaro_device.actions: target.action("setThermostatSetpoint", self._op_state_to_mode[self.current_operation], temperature) else: target.action("setTargetLevel", temperature) @property def is_on(self): """Return true if on.""" if self.current_operation == STATE_OFF: return False return True
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/fibaro/climate.py
"""Clickatell platform for notify component.""" import logging import requests import voluptuous as vol from homeassistant.const import CONF_API_KEY, CONF_RECIPIENT import homeassistant.helpers.config_validation as cv from homeassistant.components.notify import (PLATFORM_SCHEMA, BaseNotificationService) _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'clickatell' BASE_API_URL = 'https://platform.clickatell.com/messages/http/send' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_RECIPIENT): cv.string, }) def get_service(hass, config, discovery_info=None): """Get the Clickatell notification service.""" return ClickatellNotificationService(config) class ClickatellNotificationService(BaseNotificationService): """Implementation of a notification service for the Clickatell service.""" def __init__(self, config): """Initialize the service.""" self.api_key = config.get(CONF_API_KEY) self.recipient = config.get(CONF_RECIPIENT) def send_message(self, message="", **kwargs): """Send a message to a user.""" data = { 'apiKey': self.api_key, 'to': self.recipient, 'content': message, } resp = requests.get(BASE_API_URL, params=data, timeout=5) if (resp.status_code != 200) or (resp.status_code != 201): _LOGGER.error("Error %s : %s", resp.status_code, resp.text)
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/clickatell/notify.py
"""Support for WeMo humidifier.""" import asyncio import logging from datetime import timedelta import requests import async_timeout import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.fan import ( DOMAIN, SUPPORT_SET_SPEED, FanEntity, SPEED_OFF, SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH) from homeassistant.exceptions import PlatformNotReady from homeassistant.const import ATTR_ENTITY_ID from . import SUBSCRIPTION_REGISTRY SCAN_INTERVAL = timedelta(seconds=10) DATA_KEY = 'fan.wemo' _LOGGER = logging.getLogger(__name__) ATTR_CURRENT_HUMIDITY = 'current_humidity' ATTR_TARGET_HUMIDITY = 'target_humidity' ATTR_FAN_MODE = 'fan_mode' ATTR_FILTER_LIFE = 'filter_life' ATTR_FILTER_EXPIRED = 'filter_expired' ATTR_WATER_LEVEL = 'water_level' # The WEMO_ constants below come from pywemo itself WEMO_ON = 1 WEMO_OFF = 0 WEMO_HUMIDITY_45 = 0 WEMO_HUMIDITY_50 = 1 WEMO_HUMIDITY_55 = 2 WEMO_HUMIDITY_60 = 3 WEMO_HUMIDITY_100 = 4 WEMO_FAN_OFF = 0 WEMO_FAN_MINIMUM = 1 WEMO_FAN_LOW = 2 # Not used due to limitations of the base fan implementation WEMO_FAN_MEDIUM = 3 WEMO_FAN_HIGH = 4 # Not used due to limitations of the base fan implementation WEMO_FAN_MAXIMUM = 5 WEMO_WATER_EMPTY = 0 WEMO_WATER_LOW = 1 WEMO_WATER_GOOD = 2 SUPPORTED_SPEEDS = [ SPEED_OFF, SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH] SUPPORTED_FEATURES = SUPPORT_SET_SPEED # Since the base fan object supports a set list of fan speeds, # we have to reuse some of them when mapping to the 5 WeMo speeds WEMO_FAN_SPEED_TO_HASS = { WEMO_FAN_OFF: SPEED_OFF, WEMO_FAN_MINIMUM: SPEED_LOW, WEMO_FAN_LOW: SPEED_LOW, # Reusing SPEED_LOW WEMO_FAN_MEDIUM: SPEED_MEDIUM, WEMO_FAN_HIGH: SPEED_HIGH, # Reusing SPEED_HIGH WEMO_FAN_MAXIMUM: SPEED_HIGH } # Because we reused mappings in the previous dict, we have to filter them # back out in this dict, or else we would have duplicate keys HASS_FAN_SPEED_TO_WEMO = {v: k for (k, v) in WEMO_FAN_SPEED_TO_HASS.items() if k not in [WEMO_FAN_LOW, WEMO_FAN_HIGH]} SERVICE_SET_HUMIDITY = 'wemo_set_humidity' SET_HUMIDITY_SCHEMA = vol.Schema({ vol.Required(ATTR_ENTITY_ID): cv.entity_ids, vol.Required(ATTR_TARGET_HUMIDITY): vol.All(vol.Coerce(float), vol.Range(min=0, max=100)) }) SERVICE_RESET_FILTER_LIFE = 'wemo_reset_filter_life' RESET_FILTER_LIFE_SCHEMA = vol.Schema({ vol.Required(ATTR_ENTITY_ID): cv.entity_ids }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up discovered WeMo humidifiers.""" from pywemo import discovery if DATA_KEY not in hass.data: hass.data[DATA_KEY] = {} if discovery_info is None: return location = discovery_info['ssdp_description'] mac = discovery_info['mac_address'] try: device = WemoHumidifier( discovery.device_from_description(location, mac)) except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as err: _LOGGER.error('Unable to access %s (%s)', location, err) raise PlatformNotReady hass.data[DATA_KEY][device.entity_id] = device add_entities([device]) def service_handle(service): """Handle the WeMo humidifier services.""" entity_ids = service.data.get(ATTR_ENTITY_ID) humidifiers = [device for device in hass.data[DATA_KEY].values() if device.entity_id in entity_ids] if service.service == SERVICE_SET_HUMIDITY: target_humidity = service.data.get(ATTR_TARGET_HUMIDITY) for humidifier in humidifiers: humidifier.set_humidity(target_humidity) elif service.service == SERVICE_RESET_FILTER_LIFE: for humidifier in humidifiers: humidifier.reset_filter_life() # Register service(s) hass.services.register( DOMAIN, SERVICE_SET_HUMIDITY, service_handle, schema=SET_HUMIDITY_SCHEMA) hass.services.register( DOMAIN, SERVICE_RESET_FILTER_LIFE, service_handle, schema=RESET_FILTER_LIFE_SCHEMA) class WemoHumidifier(FanEntity): """Representation of a WeMo humidifier.""" def __init__(self, device): """Initialize the WeMo switch.""" self.wemo = device self._state = None self._available = True self._update_lock = None self._fan_mode = None self._target_humidity = None self._current_humidity = None self._water_level = None self._filter_life = None self._filter_expired = None self._last_fan_on_mode = WEMO_FAN_MEDIUM self._model_name = self.wemo.model_name self._name = self.wemo.name self._serialnumber = self.wemo.serialnumber def _subscription_callback(self, _device, _type, _params): """Update the state by the Wemo device.""" _LOGGER.info("Subscription update for %s", self.name) updated = self.wemo.subscription_update(_type, _params) self.hass.add_job( self._async_locked_subscription_callback(not updated)) async def _async_locked_subscription_callback(self, force_update): """Handle an update from a subscription.""" # If an update is in progress, we don't do anything if self._update_lock.locked(): return await self._async_locked_update(force_update) self.async_schedule_update_ha_state() @property def unique_id(self): """Return the ID of this WeMo humidifier.""" return self._serialnumber @property def name(self): """Return the name of the humidifier if any.""" return self._name @property def is_on(self): """Return true if switch is on. Standby is on.""" return self._state @property def available(self): """Return true if switch is available.""" return self._available @property def icon(self): """Return the icon of device based on its type.""" return 'mdi:water-percent' @property def device_state_attributes(self): """Return device specific state attributes.""" return { ATTR_CURRENT_HUMIDITY: self._current_humidity, ATTR_TARGET_HUMIDITY: self._target_humidity, ATTR_FAN_MODE: self._fan_mode, ATTR_WATER_LEVEL: self._water_level, ATTR_FILTER_LIFE: self._filter_life, ATTR_FILTER_EXPIRED: self._filter_expired } @property def speed(self) -> str: """Return the current speed.""" return WEMO_FAN_SPEED_TO_HASS.get(self._fan_mode) @property def speed_list(self) -> list: """Get the list of available speeds.""" return SUPPORTED_SPEEDS @property def supported_features(self) -> int: """Flag supported features.""" return SUPPORTED_FEATURES async def async_added_to_hass(self): """Wemo humidifier added to HASS.""" # Define inside async context so we know our event loop self._update_lock = asyncio.Lock() registry = SUBSCRIPTION_REGISTRY await self.hass.async_add_executor_job(registry.register, self.wemo) registry.on(self.wemo, None, self._subscription_callback) async def async_update(self): """Update WeMo state. Wemo has an aggressive retry logic that sometimes can take over a minute to return. If we don't get a state after 5 seconds, assume the Wemo humidifier is unreachable. If update goes through, it will be made available again. """ # If an update is in progress, we don't do anything if self._update_lock.locked(): return try: with async_timeout.timeout(5): await asyncio.shield(self._async_locked_update(True)) except asyncio.TimeoutError: _LOGGER.warning('Lost connection to %s', self.name) self._available = False async def _async_locked_update(self, force_update): """Try updating within an async lock.""" async with self._update_lock: await self.hass.async_add_executor_job(self._update, force_update) def _update(self, force_update=True): """Update the device state.""" try: self._state = self.wemo.get_state(force_update) self._fan_mode = self.wemo.fan_mode_string self._target_humidity = self.wemo.desired_humidity_percent self._current_humidity = self.wemo.current_humidity_percent self._water_level = self.wemo.water_level_string self._filter_life = self.wemo.filter_life_percent self._filter_expired = self.wemo.filter_expired if self.wemo.fan_mode != WEMO_FAN_OFF: self._last_fan_on_mode = self.wemo.fan_mode if not self._available: _LOGGER.info('Reconnected to %s', self.name) self._available = True except AttributeError as err: _LOGGER.warning("Could not update status for %s (%s)", self.name, err) self._available = False def turn_on(self, speed: str = None, **kwargs) -> None: """Turn the switch on.""" if speed is None: self.wemo.set_state(self._last_fan_on_mode) else: self.set_speed(speed) def turn_off(self, **kwargs) -> None: """Turn the switch off.""" self.wemo.set_state(WEMO_FAN_OFF) def set_speed(self, speed: str) -> None: """Set the fan_mode of the Humidifier.""" self.wemo.set_state(HASS_FAN_SPEED_TO_WEMO.get(speed)) def set_humidity(self, humidity: float) -> None: """Set the target humidity level for the Humidifier.""" if humidity < 50: self.wemo.set_humidity(WEMO_HUMIDITY_45) elif 50 <= humidity < 55: self.wemo.set_humidity(WEMO_HUMIDITY_50) elif 55 <= humidity < 60: self.wemo.set_humidity(WEMO_HUMIDITY_55) elif 60 <= humidity < 100: self.wemo.set_humidity(WEMO_HUMIDITY_60) elif humidity >= 100: self.wemo.set_humidity(WEMO_HUMIDITY_100) def reset_filter_life(self) -> None: """Reset the filter life to 100%.""" self.wemo.reset_filter_life()
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/wemo/fan.py
"""Support for Google Home Bluetooth tacker.""" from datetime import timedelta import logging from homeassistant.components.device_tracker import DeviceScanner from homeassistant.helpers.event import async_track_time_interval from homeassistant.util import slugify from . import CLIENT, DOMAIN as GOOGLEHOME_DOMAIN, NAME _LOGGER = logging.getLogger(__name__) DEFAULT_SCAN_INTERVAL = timedelta(seconds=10) async def async_setup_scanner(hass, config, async_see, discovery_info=None): """Validate the configuration and return a Google Home scanner.""" if discovery_info is None: _LOGGER.warning( "To use this you need to configure the 'googlehome' component") return False scanner = GoogleHomeDeviceScanner(hass, hass.data[CLIENT], discovery_info, async_see) return await scanner.async_init() class GoogleHomeDeviceScanner(DeviceScanner): """This class queries a Google Home unit.""" def __init__(self, hass, client, config, async_see): """Initialize the scanner.""" self.async_see = async_see self.hass = hass self.rssi = config['rssi_threshold'] self.device_types = config['device_types'] self.host = config['host'] self.client = client async def async_init(self): """Further initialize connection to Google Home.""" await self.client.update_info(self.host) data = self.hass.data[GOOGLEHOME_DOMAIN][self.host] info = data.get('info', {}) connected = bool(info) if connected: await self.async_update() async_track_time_interval(self.hass, self.async_update, DEFAULT_SCAN_INTERVAL) return connected async def async_update(self, now=None): """Ensure the information from Google Home is up to date.""" _LOGGER.debug('Checking Devices on %s', self.host) await self.client.update_bluetooth(self.host) data = self.hass.data[GOOGLEHOME_DOMAIN][self.host] info = data.get('info') bluetooth = data.get('bluetooth') if info is None or bluetooth is None: return google_home_name = info.get('name', NAME) for device in bluetooth: if (device['device_type'] not in self.device_types or device['rssi'] < self.rssi): continue name = "{} {}".format(self.host, device['mac_address']) attributes = {} attributes['btle_mac_address'] = device['mac_address'] attributes['ghname'] = google_home_name attributes['rssi'] = device['rssi'] attributes['source_type'] = 'bluetooth' if device['name']: attributes['name'] = device['name'] await self.async_see(dev_id=slugify(name), attributes=attributes)
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/googlehome/device_tracker.py
"""Support for Tellstick lights using Tellstick Net.""" import logging from homeassistant.components import light, tellduslive from homeassistant.components.light import ( ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, Light) from homeassistant.helpers.dispatcher import async_dispatcher_connect from .entry import TelldusLiveEntity _LOGGER = logging.getLogger(__name__) async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Old way of setting up TelldusLive. Can only be called when a user accidentally mentions the platform in their config. But even in that case it would have been ignored. """ pass async def async_setup_entry(hass, config_entry, async_add_entities): """Set up tellduslive sensors dynamically.""" async def async_discover_light(device_id): """Discover and add a discovered sensor.""" client = hass.data[tellduslive.DOMAIN] async_add_entities([TelldusLiveLight(client, device_id)]) async_dispatcher_connect( hass, tellduslive.TELLDUS_DISCOVERY_NEW.format(light.DOMAIN, tellduslive.DOMAIN), async_discover_light, ) class TelldusLiveLight(TelldusLiveEntity, Light): """Representation of a Tellstick Net light.""" def __init__(self, client, device_id): """Initialize the Tellstick Net light.""" super().__init__(client, device_id) self._last_brightness = self.brightness def changed(self): """Define a property of the device that might have changed.""" self._last_brightness = self.brightness self._update_callback() @property def brightness(self): """Return the brightness of this light between 0..255.""" return self.device.dim_level @property def supported_features(self): """Flag supported features.""" return SUPPORT_BRIGHTNESS @property def is_on(self): """Return true if light is on.""" return self.device.is_on def turn_on(self, **kwargs): """Turn the light on.""" brightness = kwargs.get(ATTR_BRIGHTNESS, self._last_brightness) self.device.dim(level=brightness) self.changed() def turn_off(self, **kwargs): """Turn the light off.""" self.device.turn_off() self.changed()
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/tellduslive/light.py
"""HTTP views to interact with the device registry.""" import voluptuous as vol from homeassistant.components import websocket_api from homeassistant.components.websocket_api.decorators import ( async_response, require_admin) from homeassistant.core import callback from homeassistant.helpers.device_registry import async_get_registry WS_TYPE_LIST = 'config/device_registry/list' SCHEMA_WS_LIST = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({ vol.Required('type'): WS_TYPE_LIST, }) WS_TYPE_UPDATE = 'config/device_registry/update' SCHEMA_WS_UPDATE = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({ vol.Required('type'): WS_TYPE_UPDATE, vol.Required('device_id'): str, vol.Optional('area_id'): vol.Any(str, None), vol.Optional('name_by_user'): vol.Any(str, None), }) async def async_setup(hass): """Enable the Device Registry views.""" hass.components.websocket_api.async_register_command( WS_TYPE_LIST, websocket_list_devices, SCHEMA_WS_LIST ) hass.components.websocket_api.async_register_command( WS_TYPE_UPDATE, websocket_update_device, SCHEMA_WS_UPDATE ) return True @async_response async def websocket_list_devices(hass, connection, msg): """Handle list devices command.""" registry = await async_get_registry(hass) connection.send_message(websocket_api.result_message( msg['id'], [_entry_dict(entry) for entry in registry.devices.values()] )) @require_admin @async_response async def websocket_update_device(hass, connection, msg): """Handle update area websocket command.""" registry = await async_get_registry(hass) msg.pop('type') msg_id = msg.pop('id') entry = registry.async_update_device(**msg) connection.send_message(websocket_api.result_message( msg_id, _entry_dict(entry) )) @callback def _entry_dict(entry): """Convert entry to API format.""" return { 'config_entries': list(entry.config_entries), 'connections': list(entry.connections), 'manufacturer': entry.manufacturer, 'model': entry.model, 'name': entry.name, 'sw_version': entry.sw_version, 'id': entry.id, 'hub_device_id': entry.hub_device_id, 'area_id': entry.area_id, 'name_by_user': entry.name_by_user, }
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/config/device_registry.py
"""Support for Verisure cameras.""" import errno import logging import os from homeassistant.components.camera import Camera from homeassistant.const import EVENT_HOMEASSISTANT_STOP from . import CONF_SMARTCAM, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure Camera.""" if not int(hub.config.get(CONF_SMARTCAM, 1)): return False directory_path = hass.config.config_dir if not os.access(directory_path, os.R_OK): _LOGGER.error("file path %s is not readable", directory_path) return False hub.update_overview() smartcams = [] smartcams.extend([ VerisureSmartcam(hass, device_label, directory_path) for device_label in hub.get( "$.customerImageCameras[*].deviceLabel")]) add_entities(smartcams) class VerisureSmartcam(Camera): """Representation of a Verisure camera.""" def __init__(self, hass, device_label, directory_path): """Initialize Verisure File Camera component.""" super().__init__() self._device_label = device_label self._directory_path = directory_path self._image = None self._image_id = None hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, self.delete_image) def camera_image(self): """Return image response.""" self.check_imagelist() if not self._image: _LOGGER.debug("No image to display") return _LOGGER.debug("Trying to open %s", self._image) with open(self._image, 'rb') as file: return file.read() def check_imagelist(self): """Check the contents of the image list.""" hub.update_smartcam_imageseries() image_ids = hub.get_image_info( "$.imageSeries[?(@.deviceLabel=='%s')].image[0].imageId", self._device_label) if not image_ids: return new_image_id = image_ids[0] if new_image_id in ('-1', self._image_id): _LOGGER.debug("The image is the same, or loading image_id") return _LOGGER.debug("Download new image %s", new_image_id) new_image_path = os.path.join( self._directory_path, '{}{}'.format(new_image_id, '.jpg')) hub.session.download_image( self._device_label, new_image_id, new_image_path) _LOGGER.debug("Old image_id=%s", self._image_id) self.delete_image(self) self._image_id = new_image_id self._image = new_image_path def delete_image(self, event): """Delete an old image.""" remove_image = os.path.join( self._directory_path, '{}{}'.format(self._image_id, '.jpg')) try: os.remove(remove_image) _LOGGER.debug("Deleting old image %s", remove_image) except OSError as error: if error.errno != errno.ENOENT: raise @property def name(self): """Return the name of this camera.""" return hub.get_first( "$.customerImageCameras[?(@.deviceLabel=='%s')].area", self._device_label)
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/verisure/camera.py
"""Support for the Hive binary sensors.""" from homeassistant.components.binary_sensor import BinarySensorDevice from . import DATA_HIVE, DOMAIN DEVICETYPE_DEVICE_CLASS = { 'motionsensor': 'motion', 'contactsensor': 'opening', } def setup_platform(hass, config, add_entities, discovery_info=None): """Set up Hive sensor devices.""" if discovery_info is None: return session = hass.data.get(DATA_HIVE) add_entities([HiveBinarySensorEntity(session, discovery_info)]) class HiveBinarySensorEntity(BinarySensorDevice): """Representation of a Hive binary sensor.""" def __init__(self, hivesession, hivedevice): """Initialize the hive sensor.""" self.node_id = hivedevice["Hive_NodeID"] self.node_name = hivedevice["Hive_NodeName"] self.device_type = hivedevice["HA_DeviceType"] self.node_device_type = hivedevice["Hive_DeviceType"] self.session = hivesession self.attributes = {} self.data_updatesource = '{}.{}'.format(self.device_type, self.node_id) self._unique_id = '{}-{}'.format(self.node_id, self.device_type) self.session.entities.append(self) @property def unique_id(self): """Return unique ID of entity.""" return self._unique_id @property def device_info(self): """Return device information.""" return { 'identifiers': { (DOMAIN, self.unique_id) }, 'name': self.name } def handle_update(self, updatesource): """Handle the new update request.""" if '{}.{}'.format(self.device_type, self.node_id) not in updatesource: self.schedule_update_ha_state() @property def device_class(self): """Return the class of this sensor.""" return DEVICETYPE_DEVICE_CLASS.get(self.node_device_type) @property def name(self): """Return the name of the binary sensor.""" return self.node_name @property def device_state_attributes(self): """Show Device Attributes.""" return self.attributes @property def is_on(self): """Return true if the binary sensor is on.""" return self.session.sensor.get_state( self.node_id, self.node_device_type) def update(self): """Update all Node data from Hive.""" self.session.core.update_data(self.node_id) self.attributes = self.session.attributes.state_attributes( self.node_id)
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/hive/binary_sensor.py
"""Support for package tracking sensors from 17track.net.""" import logging from datetime import timedelta import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_LOCATION, CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME) from homeassistant.helpers import aiohttp_client, config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle, slugify _LOGGER = logging.getLogger(__name__) ATTR_DESTINATION_COUNTRY = 'destination_country' ATTR_FRIENDLY_NAME = 'friendly_name' ATTR_INFO_TEXT = 'info_text' ATTR_ORIGIN_COUNTRY = 'origin_country' ATTR_PACKAGES = 'packages' ATTR_PACKAGE_TYPE = 'package_type' ATTR_STATUS = 'status' ATTR_TRACKING_INFO_LANGUAGE = 'tracking_info_language' ATTR_TRACKING_NUMBER = 'tracking_number' CONF_SHOW_ARCHIVED = 'show_archived' CONF_SHOW_DELIVERED = 'show_delivered' DATA_PACKAGES = 'package_data' DATA_SUMMARY = 'summary_data' DEFAULT_ATTRIBUTION = 'Data provided by 17track.net' DEFAULT_SCAN_INTERVAL = timedelta(minutes=10) NOTIFICATION_DELIVERED_ID_SCAFFOLD = 'package_delivered_{0}' NOTIFICATION_DELIVERED_TITLE = 'Package Delivered' NOTIFICATION_DELIVERED_URL_SCAFFOLD = 'https://t.17track.net/track#nums={0}' VALUE_DELIVERED = 'Delivered' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_SHOW_ARCHIVED, default=False): cv.boolean, vol.Optional(CONF_SHOW_DELIVERED, default=False): cv.boolean, }) async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Configure the platform and add the sensors.""" from py17track import Client from py17track.errors import SeventeenTrackError websession = aiohttp_client.async_get_clientsession(hass) client = Client(websession) try: login_result = await client.profile.login( config[CONF_USERNAME], config[CONF_PASSWORD]) if not login_result: _LOGGER.error('Invalid username and password provided') return except SeventeenTrackError as err: _LOGGER.error('There was an error while logging in: %s', err) return scan_interval = config.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) data = SeventeenTrackData( client, async_add_entities, scan_interval, config[CONF_SHOW_ARCHIVED], config[CONF_SHOW_DELIVERED]) await data.async_update() sensors = [] for status, quantity in data.summary.items(): sensors.append(SeventeenTrackSummarySensor(data, status, quantity)) for package in data.packages: sensors.append(SeventeenTrackPackageSensor(data, package)) async_add_entities(sensors, True) class SeventeenTrackSummarySensor(Entity): """Define a summary sensor.""" def __init__(self, data, status, initial_state): """Initialize.""" self._attrs = {ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION} self._data = data self._state = initial_state self._status = status @property def available(self): """Return whether the entity is available.""" return self._state is not None @property def device_state_attributes(self): """Return the device state attributes.""" return self._attrs @property def icon(self): """Return the icon.""" return 'mdi:package' @property def name(self): """Return the name.""" return 'Seventeentrack Packages {0}'.format(self._status) @property def state(self): """Return the state.""" return self._state @property def unique_id(self): """Return a unique, HASS-friendly identifier for this entity.""" return 'summary_{0}_{1}'.format( self._data.account_id, slugify(self._status)) @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return 'packages' async def async_update(self): """Update the sensor.""" await self._data.async_update() package_data = [] for package in self._data.packages: if package.status != self._status: continue package_data.append({ ATTR_FRIENDLY_NAME: package.friendly_name, ATTR_INFO_TEXT: package.info_text, ATTR_STATUS: package.status, ATTR_TRACKING_NUMBER: package.tracking_number, }) if package_data: self._attrs[ATTR_PACKAGES] = package_data self._state = self._data.summary.get(self._status) class SeventeenTrackPackageSensor(Entity): """Define an individual package sensor.""" def __init__(self, data, package): """Initialize.""" self._attrs = { ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION, ATTR_DESTINATION_COUNTRY: package.destination_country, ATTR_INFO_TEXT: package.info_text, ATTR_LOCATION: package.location, ATTR_ORIGIN_COUNTRY: package.origin_country, ATTR_PACKAGE_TYPE: package.package_type, ATTR_TRACKING_INFO_LANGUAGE: package.tracking_info_language, ATTR_TRACKING_NUMBER: package.tracking_number, } self._data = data self._friendly_name = package.friendly_name self._state = package.status self._tracking_number = package.tracking_number @property def available(self): """Return whether the entity is available.""" return bool([ p for p in self._data.packages if p.tracking_number == self._tracking_number ]) @property def device_state_attributes(self): """Return the device state attributes.""" return self._attrs @property def icon(self): """Return the icon.""" return 'mdi:package' @property def name(self): """Return the name.""" name = self._friendly_name if not name: name = self._tracking_number return 'Seventeentrack Package: {0}'.format(name) @property def state(self): """Return the state.""" return self._state @property def unique_id(self): """Return a unique, HASS-friendly identifier for this entity.""" return 'package_{0}_{1}'.format( self._data.account_id, self._tracking_number) async def async_update(self): """Update the sensor.""" await self._data.async_update() if not self._data.packages: return try: package = next(( p for p in self._data.packages if p.tracking_number == self._tracking_number)) except StopIteration: # If the package no longer exists in the data, log a message and # delete this entity: _LOGGER.info( 'Deleting entity for stale package: %s', self._tracking_number) self.hass.async_create_task(self.async_remove()) return # If the user has elected to not see delivered packages and one gets # delivered, post a notification, remove the entity from the UI, and # delete it from the entity registry: if package.status == VALUE_DELIVERED and not self._data.show_delivered: _LOGGER.info('Package delivered: %s', self._tracking_number) self.hass.components.persistent_notification.create( 'Package Delivered: {0}<br />' 'Visit 17.track for more infomation: {1}' ''.format( self._tracking_number, NOTIFICATION_DELIVERED_URL_SCAFFOLD.format( self._tracking_number)), title=NOTIFICATION_DELIVERED_TITLE, notification_id=NOTIFICATION_DELIVERED_ID_SCAFFOLD.format( self._tracking_number)) reg = self.hass.helpers.entity_registry.async_get_registry() self.hass.async_create_task(reg.async_remove(self.entity_id)) self.hass.async_create_task(self.async_remove()) return self._attrs.update({ ATTR_INFO_TEXT: package.info_text, ATTR_LOCATION: package.location, }) self._state = package.status class SeventeenTrackData: """Define a data handler for 17track.net.""" def __init__( self, client, async_add_entities, scan_interval, show_archived, show_delivered): """Initialize.""" self._async_add_entities = async_add_entities self._client = client self._scan_interval = scan_interval self._show_archived = show_archived self.account_id = client.profile.account_id self.packages = [] self.show_delivered = show_delivered self.summary = {} self.async_update = Throttle(self._scan_interval)(self._async_update) async def _async_update(self): """Get updated data from 17track.net.""" from py17track.errors import SeventeenTrackError try: packages = await self._client.profile.packages( show_archived=self._show_archived) _LOGGER.debug('New package data received: %s', packages) if not self.show_delivered: packages = [p for p in packages if p.status != VALUE_DELIVERED] # Add new packages: to_add = set(packages) - set(self.packages) if self.packages and to_add: self._async_add_entities([ SeventeenTrackPackageSensor(self, package) for package in to_add ], True) self.packages = packages except SeventeenTrackError as err: _LOGGER.error('There was an error retrieving packages: %s', err) self.packages = [] try: self.summary = await self._client.profile.summary( show_archived=self._show_archived) _LOGGER.debug('New summary data received: %s', self.summary) except SeventeenTrackError as err: _LOGGER.error('There was an error retrieving the summary: %s', err) self.summary = {}
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/seventeentrack/sensor.py
"""MySensors constants.""" import homeassistant.helpers.config_validation as cv ATTR_DEVICES = 'devices' CONF_BAUD_RATE = 'baud_rate' CONF_DEVICE = 'device' CONF_GATEWAYS = 'gateways' CONF_NODES = 'nodes' CONF_PERSISTENCE = 'persistence' CONF_PERSISTENCE_FILE = 'persistence_file' CONF_RETAIN = 'retain' CONF_TCP_PORT = 'tcp_port' CONF_TOPIC_IN_PREFIX = 'topic_in_prefix' CONF_TOPIC_OUT_PREFIX = 'topic_out_prefix' CONF_VERSION = 'version' DOMAIN = 'mysensors' MYSENSORS_GATEWAY_READY = 'mysensors_gateway_ready_{}' MYSENSORS_GATEWAYS = 'mysensors_gateways' PLATFORM = 'platform' SCHEMA = 'schema' CHILD_CALLBACK = 'mysensors_child_callback_{}_{}_{}_{}' NODE_CALLBACK = 'mysensors_node_callback_{}_{}' TYPE = 'type' UPDATE_DELAY = 0.1 # MySensors const schemas BINARY_SENSOR_SCHEMA = {PLATFORM: 'binary_sensor', TYPE: 'V_TRIPPED'} CLIMATE_SCHEMA = {PLATFORM: 'climate', TYPE: 'V_HVAC_FLOW_STATE'} LIGHT_DIMMER_SCHEMA = { PLATFORM: 'light', TYPE: 'V_DIMMER', SCHEMA: {'V_DIMMER': cv.string, 'V_LIGHT': cv.string}} LIGHT_PERCENTAGE_SCHEMA = { PLATFORM: 'light', TYPE: 'V_PERCENTAGE', SCHEMA: {'V_PERCENTAGE': cv.string, 'V_STATUS': cv.string}} LIGHT_RGB_SCHEMA = { PLATFORM: 'light', TYPE: 'V_RGB', SCHEMA: { 'V_RGB': cv.string, 'V_STATUS': cv.string}} LIGHT_RGBW_SCHEMA = { PLATFORM: 'light', TYPE: 'V_RGBW', SCHEMA: { 'V_RGBW': cv.string, 'V_STATUS': cv.string}} NOTIFY_SCHEMA = {PLATFORM: 'notify', TYPE: 'V_TEXT'} DEVICE_TRACKER_SCHEMA = {PLATFORM: 'device_tracker', TYPE: 'V_POSITION'} DUST_SCHEMA = [ {PLATFORM: 'sensor', TYPE: 'V_DUST_LEVEL'}, {PLATFORM: 'sensor', TYPE: 'V_LEVEL'}] SWITCH_LIGHT_SCHEMA = {PLATFORM: 'switch', TYPE: 'V_LIGHT'} SWITCH_STATUS_SCHEMA = {PLATFORM: 'switch', TYPE: 'V_STATUS'} MYSENSORS_CONST_SCHEMA = { 'S_DOOR': [BINARY_SENSOR_SCHEMA, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_MOTION': [BINARY_SENSOR_SCHEMA, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_SMOKE': [BINARY_SENSOR_SCHEMA, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_SPRINKLER': [ BINARY_SENSOR_SCHEMA, {PLATFORM: 'switch', TYPE: 'V_STATUS'}], 'S_WATER_LEAK': [ BINARY_SENSOR_SCHEMA, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_SOUND': [ BINARY_SENSOR_SCHEMA, {PLATFORM: 'sensor', TYPE: 'V_LEVEL'}, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_VIBRATION': [ BINARY_SENSOR_SCHEMA, {PLATFORM: 'sensor', TYPE: 'V_LEVEL'}, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_MOISTURE': [ BINARY_SENSOR_SCHEMA, {PLATFORM: 'sensor', TYPE: 'V_LEVEL'}, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_HVAC': [CLIMATE_SCHEMA], 'S_COVER': [ {PLATFORM: 'cover', TYPE: 'V_DIMMER'}, {PLATFORM: 'cover', TYPE: 'V_PERCENTAGE'}, {PLATFORM: 'cover', TYPE: 'V_LIGHT'}, {PLATFORM: 'cover', TYPE: 'V_STATUS'}], 'S_DIMMER': [LIGHT_DIMMER_SCHEMA, LIGHT_PERCENTAGE_SCHEMA], 'S_RGB_LIGHT': [LIGHT_RGB_SCHEMA], 'S_RGBW_LIGHT': [LIGHT_RGBW_SCHEMA], 'S_INFO': [NOTIFY_SCHEMA, {PLATFORM: 'sensor', TYPE: 'V_TEXT'}], 'S_GPS': [ DEVICE_TRACKER_SCHEMA, {PLATFORM: 'sensor', TYPE: 'V_POSITION'}], 'S_TEMP': [{PLATFORM: 'sensor', TYPE: 'V_TEMP'}], 'S_HUM': [{PLATFORM: 'sensor', TYPE: 'V_HUM'}], 'S_BARO': [ {PLATFORM: 'sensor', TYPE: 'V_PRESSURE'}, {PLATFORM: 'sensor', TYPE: 'V_FORECAST'}], 'S_WIND': [ {PLATFORM: 'sensor', TYPE: 'V_WIND'}, {PLATFORM: 'sensor', TYPE: 'V_GUST'}, {PLATFORM: 'sensor', TYPE: 'V_DIRECTION'}], 'S_RAIN': [ {PLATFORM: 'sensor', TYPE: 'V_RAIN'}, {PLATFORM: 'sensor', TYPE: 'V_RAINRATE'}], 'S_UV': [{PLATFORM: 'sensor', TYPE: 'V_UV'}], 'S_WEIGHT': [ {PLATFORM: 'sensor', TYPE: 'V_WEIGHT'}, {PLATFORM: 'sensor', TYPE: 'V_IMPEDANCE'}], 'S_POWER': [ {PLATFORM: 'sensor', TYPE: 'V_WATT'}, {PLATFORM: 'sensor', TYPE: 'V_KWH'}, {PLATFORM: 'sensor', TYPE: 'V_VAR'}, {PLATFORM: 'sensor', TYPE: 'V_VA'}, {PLATFORM: 'sensor', TYPE: 'V_POWER_FACTOR'}], 'S_DISTANCE': [{PLATFORM: 'sensor', TYPE: 'V_DISTANCE'}], 'S_LIGHT_LEVEL': [ {PLATFORM: 'sensor', TYPE: 'V_LIGHT_LEVEL'}, {PLATFORM: 'sensor', TYPE: 'V_LEVEL'}], 'S_IR': [ {PLATFORM: 'sensor', TYPE: 'V_IR_RECEIVE'}, {PLATFORM: 'switch', TYPE: 'V_IR_SEND', SCHEMA: {'V_IR_SEND': cv.string, 'V_LIGHT': cv.string}}], 'S_WATER': [ {PLATFORM: 'sensor', TYPE: 'V_FLOW'}, {PLATFORM: 'sensor', TYPE: 'V_VOLUME'}], 'S_CUSTOM': [ {PLATFORM: 'sensor', TYPE: 'V_VAR1'}, {PLATFORM: 'sensor', TYPE: 'V_VAR2'}, {PLATFORM: 'sensor', TYPE: 'V_VAR3'}, {PLATFORM: 'sensor', TYPE: 'V_VAR4'}, {PLATFORM: 'sensor', TYPE: 'V_VAR5'}, {PLATFORM: 'sensor', TYPE: 'V_CUSTOM'}], 'S_SCENE_CONTROLLER': [ {PLATFORM: 'sensor', TYPE: 'V_SCENE_ON'}, {PLATFORM: 'sensor', TYPE: 'V_SCENE_OFF'}], 'S_COLOR_SENSOR': [{PLATFORM: 'sensor', TYPE: 'V_RGB'}], 'S_MULTIMETER': [ {PLATFORM: 'sensor', TYPE: 'V_VOLTAGE'}, {PLATFORM: 'sensor', TYPE: 'V_CURRENT'}, {PLATFORM: 'sensor', TYPE: 'V_IMPEDANCE'}], 'S_GAS': [ {PLATFORM: 'sensor', TYPE: 'V_FLOW'}, {PLATFORM: 'sensor', TYPE: 'V_VOLUME'}], 'S_WATER_QUALITY': [ {PLATFORM: 'sensor', TYPE: 'V_TEMP'}, {PLATFORM: 'sensor', TYPE: 'V_PH'}, {PLATFORM: 'sensor', TYPE: 'V_ORP'}, {PLATFORM: 'sensor', TYPE: 'V_EC'}, {PLATFORM: 'switch', TYPE: 'V_STATUS'}], 'S_AIR_QUALITY': DUST_SCHEMA, 'S_DUST': DUST_SCHEMA, 'S_LIGHT': [SWITCH_LIGHT_SCHEMA], 'S_BINARY': [SWITCH_STATUS_SCHEMA], 'S_LOCK': [{PLATFORM: 'switch', TYPE: 'V_LOCK_STATUS'}], }
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/mysensors/const.py
"""Cover Platform for the Somfy MyLink component.""" import logging from homeassistant.components.cover import ENTITY_ID_FORMAT, CoverDevice from homeassistant.util import slugify from . import CONF_DEFAULT_REVERSE, DATA_SOMFY_MYLINK _LOGGER = logging.getLogger(__name__) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Discover and configure Somfy covers.""" if discovery_info is None: return somfy_mylink = hass.data[DATA_SOMFY_MYLINK] cover_list = [] try: mylink_status = await somfy_mylink.status_info() except TimeoutError: _LOGGER.error("Unable to connect to the Somfy MyLink device, " "please check your settings") return for cover in mylink_status['result']: entity_id = ENTITY_ID_FORMAT.format(slugify(cover['name'])) entity_config = discovery_info.get(entity_id, {}) default_reverse = discovery_info[CONF_DEFAULT_REVERSE] cover_config = {} cover_config['target_id'] = cover['targetID'] cover_config['name'] = cover['name'] cover_config['reverse'] = entity_config.get('reverse', default_reverse) cover_list.append(SomfyShade(somfy_mylink, **cover_config)) _LOGGER.info('Adding Somfy Cover: %s with targetID %s', cover_config['name'], cover_config['target_id']) async_add_entities(cover_list) class SomfyShade(CoverDevice): """Object for controlling a Somfy cover.""" def __init__(self, somfy_mylink, target_id='AABBCC', name='SomfyShade', reverse=False, device_class='window'): """Initialize the cover.""" self.somfy_mylink = somfy_mylink self._target_id = target_id self._name = name self._reverse = reverse self._device_class = device_class @property def name(self): """Return the name of the cover.""" return self._name @property def is_closed(self): """Return if the cover is closed.""" return None @property def assumed_state(self): """Let HA know the integration is assumed state.""" return True @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return self._device_class async def async_open_cover(self, **kwargs): """Wrap Homeassistant calls to open the cover.""" if not self._reverse: await self.somfy_mylink.move_up(self._target_id) else: await self.somfy_mylink.move_down(self._target_id) async def async_close_cover(self, **kwargs): """Wrap Homeassistant calls to close the cover.""" if not self._reverse: await self.somfy_mylink.move_down(self._target_id) else: await self.somfy_mylink.move_up(self._target_id) async def async_stop_cover(self, **kwargs): """Stop the cover.""" await self.somfy_mylink.move_stop(self._target_id)
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/somfy_mylink/cover.py
"""Support for Qwikswitch devices.""" import logging import voluptuous as vol from homeassistant.components.binary_sensor import DEVICE_CLASSES_SCHEMA from homeassistant.components.light import ATTR_BRIGHTNESS from homeassistant.const import ( CONF_SENSORS, CONF_SWITCHES, CONF_URL, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP) from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.discovery import load_platform from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) DOMAIN = 'qwikswitch' CONF_DIMMER_ADJUST = 'dimmer_adjust' CONF_BUTTON_EVENTS = 'button_events' CV_DIM_VALUE = vol.All(vol.Coerce(float), vol.Range(min=1, max=3)) CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_URL, default='http://127.0.0.1:2020'): vol.Coerce(str), vol.Optional(CONF_DIMMER_ADJUST, default=1): CV_DIM_VALUE, vol.Optional(CONF_BUTTON_EVENTS, default=[]): cv.ensure_list_csv, vol.Optional(CONF_SENSORS, default=[]): vol.All( cv.ensure_list, [vol.Schema({ vol.Required('id'): str, vol.Optional('channel', default=1): int, vol.Required('name'): str, vol.Required('type'): str, vol.Optional('class'): DEVICE_CLASSES_SCHEMA, vol.Optional('invert'): bool })]), vol.Optional(CONF_SWITCHES, default=[]): vol.All( cv.ensure_list, [str]) })}, extra=vol.ALLOW_EXTRA) class QSEntity(Entity): """Qwikswitch Entity base.""" def __init__(self, qsid, name): """Initialize the QSEntity.""" self._name = name self.qsid = qsid @property def name(self): """Return the name of the sensor.""" return self._name @property def poll(self): """QS sensors gets packets in update_packet.""" return False @property def unique_id(self): """Return a unique identifier for this sensor.""" return "qs{}".format(self.qsid) @callback def update_packet(self, packet): """Receive update packet from QSUSB. Match dispather_send signature.""" self.async_schedule_update_ha_state() async def async_added_to_hass(self): """Listen for updates from QSUSb via dispatcher.""" self.hass.helpers.dispatcher.async_dispatcher_connect( self.qsid, self.update_packet) class QSToggleEntity(QSEntity): """Representation of a Qwikswitch Toggle Entity. Implemented: - QSLight extends QSToggleEntity and Light[2] (ToggleEntity[1]) - QSSwitch extends QSToggleEntity and SwitchDevice[3] (ToggleEntity[1]) [1] /helpers/entity.py [2] /components/light/__init__.py [3] /components/switch/__init__.py """ def __init__(self, qsid, qsusb): """Initialize the ToggleEntity.""" self.device = qsusb.devices[qsid] super().__init__(qsid, self.device.name) @property def is_on(self): """Check if device is on (non-zero).""" return self.device.value > 0 async def async_turn_on(self, **kwargs): """Turn the device on.""" new = kwargs.get(ATTR_BRIGHTNESS, 255) self.hass.data[DOMAIN].devices.set_value(self.qsid, new) async def async_turn_off(self, **_): """Turn the device off.""" self.hass.data[DOMAIN].devices.set_value(self.qsid, 0) async def async_setup(hass, config): """Qwiskswitch component setup.""" from pyqwikswitch.async_ import QSUsb from pyqwikswitch.qwikswitch import ( CMD_BUTTONS, QS_CMD, QS_ID, QSType, SENSORS) # Add cmd's to in /&listen packets will fire events # By default only buttons of type [TOGGLE,SCENE EXE,LEVEL] cmd_buttons = set(CMD_BUTTONS) for btn in config[DOMAIN][CONF_BUTTON_EVENTS]: cmd_buttons.add(btn) url = config[DOMAIN][CONF_URL] dimmer_adjust = config[DOMAIN][CONF_DIMMER_ADJUST] sensors = config[DOMAIN][CONF_SENSORS] switches = config[DOMAIN][CONF_SWITCHES] def callback_value_changed(_qsd, qsid, _val): """Update entity values based on device change.""" _LOGGER.debug("Dispatch %s (update from devices)", qsid) hass.helpers.dispatcher.async_dispatcher_send(qsid, None) session = async_get_clientsession(hass) qsusb = QSUsb(url=url, dim_adj=dimmer_adjust, session=session, callback_value_changed=callback_value_changed) # Discover all devices in QSUSB if not await qsusb.update_from_devices(): return False hass.data[DOMAIN] = qsusb comps = {'switch': [], 'light': [], 'sensor': [], 'binary_sensor': []} try: sensor_ids = [] for sens in sensors: _, _type = SENSORS[sens['type']] sensor_ids.append(sens['id']) if _type is bool: comps['binary_sensor'].append(sens) continue comps['sensor'].append(sens) for _key in ('invert', 'class'): if _key in sens: _LOGGER.warning( "%s should only be used for binary_sensors: %s", _key, sens) except KeyError: _LOGGER.warning("Sensor validation failed") for qsid, dev in qsusb.devices.items(): if qsid in switches: if dev.qstype != QSType.relay: _LOGGER.warning( "You specified a switch that is not a relay %s", qsid) continue comps['switch'].append(qsid) elif dev.qstype in (QSType.relay, QSType.dimmer): comps['light'].append(qsid) else: _LOGGER.warning("Ignored unknown QSUSB device: %s", dev) continue # Load platforms for comp_name, comp_conf in comps.items(): if comp_conf: load_platform(hass, comp_name, DOMAIN, {DOMAIN: comp_conf}, config) def callback_qs_listen(qspacket): """Typically a button press or update signal.""" # If button pressed, fire a hass event if QS_ID in qspacket: if qspacket.get(QS_CMD, '') in cmd_buttons: hass.bus.async_fire( 'qwikswitch.button.{}'.format(qspacket[QS_ID]), qspacket) return if qspacket[QS_ID] in sensor_ids: _LOGGER.debug("Dispatch %s ((%s))", qspacket[QS_ID], qspacket) hass.helpers.dispatcher.async_dispatcher_send( qspacket[QS_ID], qspacket) # Update all ha_objects hass.async_add_job(qsusb.update_from_devices) @callback def async_start(_): """Start listening.""" hass.async_add_job(qsusb.listen, callback_qs_listen) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, async_start) @callback def async_stop(_): """Stop the listener.""" hass.data[DOMAIN].stop() hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, async_stop) return True
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/qwikswitch/__init__.py
"""Support for the yandex speechkit tts service.""" import asyncio import logging import aiohttp import async_timeout import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider from homeassistant.const import CONF_API_KEY from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) YANDEX_API_URL = "https://tts.voicetech.yandex.net/generate?" SUPPORT_LANGUAGES = [ 'ru-RU', 'en-US', 'tr-TR', 'uk-UK' ] SUPPORT_CODECS = [ 'mp3', 'wav', 'opus', ] SUPPORT_VOICES = [ 'jane', 'oksana', 'alyss', 'omazh', 'zahar', 'ermil', 'levitan', 'ermilov', 'silaerkan', 'kolya', 'kostya', 'nastya', 'sasha', 'nick', 'erkanyavas', 'zhenya', 'tanya', 'anton_samokhvalov', 'tatyana_abramova', 'voicesearch', 'ermil_with_tuning', 'robot', 'dude', 'zombie', 'smoky' ] SUPPORTED_EMOTION = [ 'good', 'evil', 'neutral' ] MIN_SPEED = 0.1 MAX_SPEED = 3 CONF_CODEC = 'codec' CONF_VOICE = 'voice' CONF_EMOTION = 'emotion' CONF_SPEED = 'speed' DEFAULT_LANG = 'en-US' DEFAULT_CODEC = 'mp3' DEFAULT_VOICE = 'zahar' DEFAULT_EMOTION = 'neutral' DEFAULT_SPEED = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES), vol.Optional(CONF_CODEC, default=DEFAULT_CODEC): vol.In(SUPPORT_CODECS), vol.Optional(CONF_VOICE, default=DEFAULT_VOICE): vol.In(SUPPORT_VOICES), vol.Optional(CONF_EMOTION, default=DEFAULT_EMOTION): vol.In(SUPPORTED_EMOTION), vol.Optional(CONF_SPEED, default=DEFAULT_SPEED): vol.Range(min=MIN_SPEED, max=MAX_SPEED) }) SUPPORTED_OPTIONS = [ CONF_CODEC, CONF_VOICE, CONF_EMOTION, CONF_SPEED, ] async def async_get_engine(hass, config): """Set up VoiceRSS speech component.""" return YandexSpeechKitProvider(hass, config) class YandexSpeechKitProvider(Provider): """VoiceRSS speech api provider.""" def __init__(self, hass, conf): """Init VoiceRSS TTS service.""" self.hass = hass self._codec = conf.get(CONF_CODEC) self._key = conf.get(CONF_API_KEY) self._speaker = conf.get(CONF_VOICE) self._language = conf.get(CONF_LANG) self._emotion = conf.get(CONF_EMOTION) self._speed = str(conf.get(CONF_SPEED)) self.name = 'YandexTTS' @property def default_language(self): """Return the default language.""" return self._language @property def supported_languages(self): """Return list of supported languages.""" return SUPPORT_LANGUAGES @property def supported_options(self): """Return list of supported options.""" return SUPPORTED_OPTIONS async def async_get_tts_audio(self, message, language, options=None): """Load TTS from yandex.""" websession = async_get_clientsession(self.hass) actual_language = language options = options or {} try: with async_timeout.timeout(10, loop=self.hass.loop): url_param = { 'text': message, 'lang': actual_language, 'key': self._key, 'speaker': options.get(CONF_VOICE, self._speaker), 'format': options.get(CONF_CODEC, self._codec), 'emotion': options.get(CONF_EMOTION, self._emotion), 'speed': options.get(CONF_SPEED, self._speed) } request = await websession.get( YANDEX_API_URL, params=url_param) if request.status != 200: _LOGGER.error("Error %d on load URL %s", request.status, request.url) return (None, None) data = await request.read() except (asyncio.TimeoutError, aiohttp.ClientError): _LOGGER.error("Timeout for yandex speech kit API") return (None, None) return (self._codec, data)
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/yandextts/tts.py
"""Support for EDP re:dy.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.const import ( CONF_PASSWORD, CONF_USERNAME, EVENT_HOMEASSISTANT_START) from homeassistant.core import callback from homeassistant.helpers import aiohttp_client, discovery, dispatcher import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_point_in_time from homeassistant.util import dt as dt_util _LOGGER = logging.getLogger(__name__) DOMAIN = 'edp_redy' EDP_REDY = 'edp_redy' DATA_UPDATE_TOPIC = '{0}_data_update'.format(DOMAIN) UPDATE_INTERVAL = 60 CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string }) }, extra=vol.ALLOW_EXTRA) async def async_setup(hass, config): """Set up the EDP re:dy component.""" from edp_redy import EdpRedySession session = EdpRedySession(config[DOMAIN][CONF_USERNAME], config[DOMAIN][CONF_PASSWORD], aiohttp_client.async_get_clientsession(hass), hass.loop) hass.data[EDP_REDY] = session platform_loaded = False async def async_update_and_sched(time): update_success = await session.async_update() if update_success: nonlocal platform_loaded # pylint: disable=used-before-assignment if not platform_loaded: for component in ['sensor', 'switch']: await discovery.async_load_platform(hass, component, DOMAIN, {}, config) platform_loaded = True dispatcher.async_dispatcher_send(hass, DATA_UPDATE_TOPIC) # schedule next update async_track_point_in_time(hass, async_update_and_sched, time + timedelta(seconds=UPDATE_INTERVAL)) async def start_component(event): _LOGGER.debug("Starting updates") await async_update_and_sched(dt_util.utcnow()) # only start fetching data after HA boots to prevent delaying the boot # process hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_component) return True class EdpRedyDevice(Entity): """Representation a base re:dy device.""" def __init__(self, session, device_id, name): """Initialize the device.""" self._session = session self._state = None self._is_available = True self._device_state_attributes = {} self._id = device_id self._unique_id = device_id self._name = name if name else device_id async def async_added_to_hass(self): """Subscribe to the data updates topic.""" dispatcher.async_dispatcher_connect( self.hass, DATA_UPDATE_TOPIC, self._data_updated) @property def name(self): """Return the name of the device.""" return self._name @property def unique_id(self) -> str: """Return a unique ID.""" return self._unique_id @property def available(self): """Return True if entity is available.""" return self._is_available @property def should_poll(self): """Return the polling state. No polling needed.""" return False @property def device_state_attributes(self): """Return the state attributes.""" return self._device_state_attributes @callback def _data_updated(self): """Update state, trigger updates.""" self.async_schedule_update_ha_state(True) def _parse_data(self, data): """Parse data received from the server.""" if "OutOfOrder" in data: try: self._is_available = not data['OutOfOrder'] except ValueError: _LOGGER.error( "Could not parse OutOfOrder for %s", self._id) self._is_available = False
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/edp_redy/__init__.py
"""Support for the Microsoft Cognitive Services text-to-speech service.""" from http.client import HTTPException import logging import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider from homeassistant.const import CONF_API_KEY, CONF_TYPE import homeassistant.helpers.config_validation as cv CONF_GENDER = 'gender' CONF_OUTPUT = 'output' CONF_RATE = 'rate' CONF_VOLUME = 'volume' CONF_PITCH = 'pitch' CONF_CONTOUR = 'contour' _LOGGER = logging.getLogger(__name__) SUPPORTED_LANGUAGES = [ 'ar-eg', 'ar-sa', 'ca-es', 'cs-cz', 'da-dk', 'de-at', 'de-ch', 'de-de', 'el-gr', 'en-au', 'en-ca', 'en-gb', 'en-ie', 'en-in', 'en-us', 'es-es', 'es-mx', 'fi-fi', 'fr-ca', 'fr-ch', 'fr-fr', 'he-il', 'hi-in', 'hu-hu', 'id-id', 'it-it', 'ja-jp', 'ko-kr', 'nb-no', 'nl-nl', 'pl-pl', 'pt-br', 'pt-pt', 'ro-ro', 'ru-ru', 'sk-sk', 'sv-se', 'th-th', 'tr-tr', 'zh-cn', 'zh-hk', 'zh-tw', ] GENDERS = [ 'Female', 'Male', ] DEFAULT_LANG = 'en-us' DEFAULT_GENDER = 'Female' DEFAULT_TYPE = 'ZiraRUS' DEFAULT_OUTPUT = 'audio-16khz-128kbitrate-mono-mp3' DEFAULT_RATE = 0 DEFAULT_VOLUME = 0 DEFAULT_PITCH = "default" DEFAULT_CONTOUR = "" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORTED_LANGUAGES), vol.Optional(CONF_GENDER, default=DEFAULT_GENDER): vol.In(GENDERS), vol.Optional(CONF_TYPE, default=DEFAULT_TYPE): cv.string, vol.Optional(CONF_RATE, default=DEFAULT_RATE): vol.All(vol.Coerce(int), vol.Range(-100, 100)), vol.Optional(CONF_VOLUME, default=DEFAULT_VOLUME): vol.All(vol.Coerce(int), vol.Range(-100, 100)), vol.Optional(CONF_PITCH, default=DEFAULT_PITCH): cv.string, vol.Optional(CONF_CONTOUR, default=DEFAULT_CONTOUR): cv.string, }) def get_engine(hass, config): """Set up Microsoft speech component.""" return MicrosoftProvider(config[CONF_API_KEY], config[CONF_LANG], config[CONF_GENDER], config[CONF_TYPE], config[CONF_RATE], config[CONF_VOLUME], config[CONF_PITCH], config[CONF_CONTOUR]) class MicrosoftProvider(Provider): """The Microsoft speech API provider.""" def __init__(self, apikey, lang, gender, ttype, rate, volume, pitch, contour): """Init Microsoft TTS service.""" self._apikey = apikey self._lang = lang self._gender = gender self._type = ttype self._output = DEFAULT_OUTPUT self._rate = "{}%".format(rate) self._volume = "{}%".format(volume) self._pitch = pitch self._contour = contour self.name = 'Microsoft' @property def default_language(self): """Return the default language.""" return self._lang @property def supported_languages(self): """Return list of supported languages.""" return SUPPORTED_LANGUAGES def get_tts_audio(self, message, language, options=None): """Load TTS from Microsoft.""" if language is None: language = self._lang from pycsspeechtts import pycsspeechtts try: trans = pycsspeechtts.TTSTranslator(self._apikey) data = trans.speak(language=language, gender=self._gender, voiceType=self._type, output=self._output, rate=self._rate, volume=self._volume, pitch=self._pitch, contour=self._contour, text=message) except HTTPException as ex: _LOGGER.error("Error occurred for Microsoft TTS: %s", ex) return(None, None) return ("mp3", data)
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/microsoft/tts.py
"""Support for information about the German train system.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity import homeassistant.util.dt as dt_util _LOGGER = logging.getLogger(__name__) CONF_DESTINATION = 'to' CONF_START = 'from' CONF_ONLY_DIRECT = 'only_direct' DEFAULT_ONLY_DIRECT = False ICON = 'mdi:train' SCAN_INTERVAL = timedelta(minutes=2) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_DESTINATION): cv.string, vol.Required(CONF_START): cv.string, vol.Optional(CONF_ONLY_DIRECT, default=DEFAULT_ONLY_DIRECT): cv.boolean, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Deutsche Bahn Sensor.""" start = config.get(CONF_START) destination = config.get(CONF_DESTINATION) only_direct = config.get(CONF_ONLY_DIRECT) add_entities([DeutscheBahnSensor(start, destination, only_direct)], True) class DeutscheBahnSensor(Entity): """Implementation of a Deutsche Bahn sensor.""" def __init__(self, start, goal, only_direct): """Initialize the sensor.""" self._name = '{} to {}'.format(start, goal) self.data = SchieneData(start, goal, only_direct) self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Return the icon for the frontend.""" return ICON @property def state(self): """Return the departure time of the next train.""" return self._state @property def device_state_attributes(self): """Return the state attributes.""" connections = self.data.connections[0] if len(self.data.connections) > 1: connections['next'] = self.data.connections[1]['departure'] if len(self.data.connections) > 2: connections['next_on'] = self.data.connections[2]['departure'] return connections def update(self): """Get the latest delay from bahn.de and updates the state.""" self.data.update() self._state = self.data.connections[0].get('departure', 'Unknown') if self.data.connections[0].get('delay', 0) != 0: self._state += " + {}".format(self.data.connections[0]['delay']) class SchieneData: """Pull data from the bahn.de web page.""" def __init__(self, start, goal, only_direct): """Initialize the sensor.""" import schiene self.start = start self.goal = goal self.only_direct = only_direct self.schiene = schiene.Schiene() self.connections = [{}] def update(self): """Update the connection data.""" self.connections = self.schiene.connections( self.start, self.goal, dt_util.as_local(dt_util.utcnow()), self.only_direct) if not self.connections: self.connections = [{}] for con in self.connections: # Detail info is not useful. Having a more consistent interface # simplifies usage of template sensors. if 'details' in con: con.pop('details') delay = con.get('delay', {'delay_departure': 0, 'delay_arrival': 0}) con['delay'] = delay['delay_departure'] con['delay_arrival'] = delay['delay_arrival'] con['ontime'] = con.get('ontime', False)
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/deutsche_bahn/sensor.py
""" Support for getting the state of a Thermoworks Smoke Thermometer. Requires Smoke Gateway Wifi with an internet connection. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.thermoworks_smoke/ """ import logging from requests import RequestException import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import TEMP_FAHRENHEIT, CONF_EMAIL, CONF_PASSWORD,\ CONF_MONITORED_CONDITIONS, CONF_EXCLUDE, ATTR_BATTERY_LEVEL from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) PROBE_1 = 'probe1' PROBE_2 = 'probe2' PROBE_1_MIN = 'probe1_min' PROBE_1_MAX = 'probe1_max' PROBE_2_MIN = 'probe2_min' PROBE_2_MAX = 'probe2_max' BATTERY_LEVEL = 'battery' FIRMWARE = 'firmware' SERIAL_REGEX = '^(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$' # map types to labels SENSOR_TYPES = { PROBE_1: 'Probe 1', PROBE_2: 'Probe 2', PROBE_1_MIN: 'Probe 1 Min', PROBE_1_MAX: 'Probe 1 Max', PROBE_2_MIN: 'Probe 2 Min', PROBE_2_MAX: 'Probe 2 Max', } # exclude these keys from thermoworks data EXCLUDE_KEYS = [ FIRMWARE ] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_EMAIL): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_MONITORED_CONDITIONS, default=[PROBE_1, PROBE_2]): vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), vol.Optional(CONF_EXCLUDE, default=[]): vol.All(cv.ensure_list, [cv.matches_regex(SERIAL_REGEX)]), }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the thermoworks sensor.""" import thermoworks_smoke from requests.exceptions import HTTPError email = config[CONF_EMAIL] password = config[CONF_PASSWORD] monitored_variables = config[CONF_MONITORED_CONDITIONS] excluded = config[CONF_EXCLUDE] try: mgr = thermoworks_smoke.initialize_app(email, password, True, excluded) # list of sensor devices dev = [] # get list of registered devices for serial in mgr.serials(): for variable in monitored_variables: dev.append(ThermoworksSmokeSensor(variable, serial, mgr)) add_entities(dev, True) except HTTPError as error: msg = "{}".format(error.strerror) if 'EMAIL_NOT_FOUND' in msg or \ 'INVALID_PASSWORD' in msg: _LOGGER.error("Invalid email and password combination") else: _LOGGER.error(msg) class ThermoworksSmokeSensor(Entity): """Implementation of a thermoworks smoke sensor.""" def __init__(self, sensor_type, serial, mgr): """Initialize the sensor.""" self._name = "{name} {sensor}".format( name=mgr.name(serial), sensor=SENSOR_TYPES[sensor_type]) self.type = sensor_type self._state = None self._attributes = {} self._unit_of_measurement = TEMP_FAHRENHEIT self._unique_id = "{serial}-{type}".format( serial=serial, type=sensor_type) self.serial = serial self.mgr = mgr self.update_unit() @property def name(self): """Return the name of the sensor.""" return self._name @property def unique_id(self): """Return the unique id for the sensor.""" return self._unique_id @property def state(self): """Return the state of the sensor.""" return self._state @property def device_state_attributes(self): """Return the state attributes.""" return self._attributes @property def unit_of_measurement(self): """Return the unit of measurement of this sensor.""" return self._unit_of_measurement def update_unit(self): """Set the units from the data.""" if PROBE_2 in self.type: self._unit_of_measurement = self.mgr.units(self.serial, PROBE_2) else: self._unit_of_measurement = self.mgr.units(self.serial, PROBE_1) def update(self): """Get the monitored data from firebase.""" from stringcase import camelcase, snakecase try: values = self.mgr.data(self.serial) # set state from data based on type of sensor self._state = values.get(camelcase(self.type)) # set units self.update_unit() # set basic attributes for all sensors self._attributes = { 'time': values['time'], 'localtime': values['localtime'] } # set extended attributes for main probe sensors if self.type in [PROBE_1, PROBE_2]: for key, val in values.items(): # add all attributes that don't contain any probe name # or contain a matching probe name if ( (self.type == PROBE_1 and key.find(PROBE_2) == -1) or (self.type == PROBE_2 and key.find(PROBE_1) == -1) ): if key == BATTERY_LEVEL: key = ATTR_BATTERY_LEVEL else: # strip probe label and convert to snake_case key = snakecase(key.replace(self.type, '')) # add to attrs if key and key not in EXCLUDE_KEYS: self._attributes[key] = val # store actual unit because attributes are not converted self._attributes['unit_of_min_max'] = self._unit_of_measurement except (RequestException, ValueError, KeyError): _LOGGER.warning("Could not update status for %s", self.name)
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/thermoworks_smoke/sensor.py
"""Component for interacting with the Yale Smart Alarm System API.""" import logging import voluptuous as vol from homeassistant.components.alarm_control_panel import ( AlarmControlPanel, PLATFORM_SCHEMA) from homeassistant.const import ( CONF_PASSWORD, CONF_USERNAME, CONF_NAME, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED) import homeassistant.helpers.config_validation as cv CONF_AREA_ID = 'area_id' DEFAULT_NAME = 'Yale Smart Alarm' DEFAULT_AREA_ID = '1' _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_AREA_ID, default=DEFAULT_AREA_ID): cv.string, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the alarm platform.""" name = config[CONF_NAME] username = config[CONF_USERNAME] password = config[CONF_PASSWORD] area_id = config[CONF_AREA_ID] from yalesmartalarmclient.client import ( YaleSmartAlarmClient, AuthenticationError) try: client = YaleSmartAlarmClient(username, password, area_id) except AuthenticationError: _LOGGER.error("Authentication failed. Check credentials") return add_entities([YaleAlarmDevice(name, client)], True) class YaleAlarmDevice(AlarmControlPanel): """Represent a Yale Smart Alarm.""" def __init__(self, name, client): """Initialize the Yale Alarm Device.""" self._name = name self._client = client self._state = None from yalesmartalarmclient.client import (YALE_STATE_DISARM, YALE_STATE_ARM_PARTIAL, YALE_STATE_ARM_FULL) self._state_map = { YALE_STATE_DISARM: STATE_ALARM_DISARMED, YALE_STATE_ARM_PARTIAL: STATE_ALARM_ARMED_HOME, YALE_STATE_ARM_FULL: STATE_ALARM_ARMED_AWAY } @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the state of the device.""" return self._state def update(self): """Return the state of the device.""" armed_status = self._client.get_armed_status() self._state = self._state_map.get(armed_status) def alarm_disarm(self, code=None): """Send disarm command.""" self._client.disarm() def alarm_arm_home(self, code=None): """Send arm home command.""" self._client.arm_partial() def alarm_arm_away(self, code=None): """Send arm away command.""" self._client.arm_full()
"""The tests for the Updater component.""" import asyncio from datetime import timedelta from unittest.mock import patch, Mock import pytest from homeassistant.setup import async_setup_component from homeassistant.components import updater import homeassistant.util.dt as dt_util from tests.common import ( async_fire_time_changed, mock_coro, mock_component, MockDependency) NEW_VERSION = '10000.0' MOCK_VERSION = '10.0' MOCK_DEV_VERSION = '10.0.dev0' MOCK_HUUID = 'abcdefg' MOCK_RESPONSE = { 'version': '0.15', 'release-notes': 'https://home-assistant.io' } MOCK_CONFIG = {updater.DOMAIN: { 'reporting': True }} @pytest.fixture(autouse=True) def mock_distro(): """Mock distro dep.""" with MockDependency('distro'): yield @pytest.fixture def mock_get_newest_version(): """Fixture to mock get_newest_version.""" with patch('homeassistant.components.updater.get_newest_version') as mock: yield mock @pytest.fixture def mock_get_uuid(): """Fixture to mock get_uuid.""" with patch('homeassistant.components.updater._load_uuid') as mock: yield mock @asyncio.coroutine def test_new_version_shows_entity_after_hour( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, NEW_VERSION) @asyncio.coroutine def test_same_version_not_show_entity( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None @asyncio.coroutine def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, '')) res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: { 'reporting': False }}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.get(updater.ENTITY_ID) is None res = yield from updater.get_newest_version(hass, MOCK_HUUID, MOCK_CONFIG) call = mock_get_newest_version.mock_calls[0][1] assert call[0] is hass assert call[1] is None @asyncio.coroutine def test_get_newest_version_no_analytics_when_no_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', side_effect=Exception): res = yield from updater.get_newest_version(hass, None, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json=MOCK_RESPONSE) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE['version'], MOCK_RESPONSE['release-notes']) @asyncio.coroutine def test_error_fetching_new_version_timeout(hass): """Test we do not gather analytics when no huuid is passed in.""" with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))), \ patch('async_timeout.timeout', side_effect=asyncio.TimeoutError): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_bad_json(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, text='not json') with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_error_fetching_new_version_invalid_response(hass, aioclient_mock): """Test we do not gather analytics when no huuid is passed in.""" aioclient_mock.post(updater.UPDATER_URL, json={ 'version': '0.15' # 'release-notes' is missing }) with patch('homeassistant.helpers.system_info.async_get_system_info', Mock(return_value=mock_coro({'fake': 'bla'}))): res = yield from updater.get_newest_version(hass, MOCK_HUUID, False) assert res is None @asyncio.coroutine def test_new_version_shows_entity_after_hour_hassio( hass, mock_get_uuid, mock_get_newest_version): """Test if new entity is created if new version is available / hass.io.""" mock_get_uuid.return_value = MOCK_HUUID mock_get_newest_version.return_value = mock_coro((NEW_VERSION, '')) mock_component(hass, 'hassio') hass.data['hassio_hass_version'] = "999.0" res = yield from async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {}}) assert res, 'Updater failed to set up' with patch('homeassistant.components.updater.current_version', MOCK_VERSION): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) yield from hass.async_block_till_done() assert hass.states.is_state(updater.ENTITY_ID, "999.0")
auduny/home-assistant
tests/components/updater/test_init.py
homeassistant/components/yale_smart_alarm/alarm_control_panel.py
from abc import abstractmethod, ABCMeta from collections import Sequence, Hashable from numbers import Integral import operator import six from pyrsistent._transformations import transform def _bitcount(val): return bin(val).count("1") BRANCH_FACTOR = 32 BIT_MASK = BRANCH_FACTOR - 1 SHIFT = _bitcount(BIT_MASK) def compare_pvector(v, other, operator): return operator(v.tolist(), other.tolist() if isinstance(other, PVector) else other) def _index_or_slice(index, stop): if stop is None: return index return slice(index, stop) class PythonPVector(object): """ Support structure for PVector that implements structural sharing for vectors using a trie. """ __slots__ = ('_count', '_shift', '_root', '_tail', '_tail_offset', '__weakref__') def __new__(cls, count, shift, root, tail): self = super(PythonPVector, cls).__new__(cls) self._count = count self._shift = shift self._root = root self._tail = tail # Derived attribute stored for performance self._tail_offset = self._count - len(self._tail) return self def __len__(self): return self._count def __getitem__(self, index): if isinstance(index, slice): # There are more conditions than the below where it would be OK to # return ourselves, implement those... if index.start is None and index.stop is None and index.step is None: return self # This is a bit nasty realizing the whole structure as a list before # slicing it but it is the fastest way I've found to date, and it's easy :-) return _EMPTY_PVECTOR.extend(self.tolist()[index]) if index < 0: index += self._count return PythonPVector._node_for(self, index)[index & BIT_MASK] def __add__(self, other): return self.extend(other) def __repr__(self): return 'pvector({0})'.format(str(self.tolist())) def __str__(self): return self.__repr__() def __iter__(self): # This is kind of lazy and will produce some memory overhead but it is the fasted method # by far of those tried since it uses the speed of the built in python list directly. return iter(self.tolist()) def __ne__(self, other): return compare_pvector(self, other, operator.ne) def __eq__(self, other): return self is other or compare_pvector(self, other, operator.eq) def __gt__(self, other): return compare_pvector(self, other, operator.gt) def __lt__(self, other): return compare_pvector(self, other, operator.lt) def __ge__(self, other): return compare_pvector(self, other, operator.ge) def __le__(self, other): return compare_pvector(self, other, operator.le) def __mul__(self, times): if times <= 0 or self is _EMPTY_PVECTOR: return _EMPTY_PVECTOR if times == 1: return self return _EMPTY_PVECTOR.extend(times * self.tolist()) __rmul__ = __mul__ def _fill_list(self, node, shift, the_list): if shift: shift -= SHIFT for n in node: self._fill_list(n, shift, the_list) else: the_list.extend(node) def tolist(self): """ The fastest way to convert the vector into a python list. """ the_list = [] self._fill_list(self._root, self._shift, the_list) the_list.extend(self._tail) return the_list def _totuple(self): """ Returns the content as a python tuple. """ return tuple(self.tolist()) def __hash__(self): # Taking the easy way out again... return hash(self._totuple()) def transform(self, *transformations): return transform(self, transformations) def __reduce__(self): # Pickling support return pvector, (self.tolist(),) def mset(self, *args): if len(args) % 2: raise TypeError("mset expected an even number of arguments") evolver = self.evolver() for i in range(0, len(args), 2): evolver[args[i]] = args[i+1] return evolver.persistent() class Evolver(object): __slots__ = ('_count', '_shift', '_root', '_tail', '_tail_offset', '_dirty_nodes', '_extra_tail', '_cached_leafs', '_orig_pvector') def __init__(self, v): self._reset(v) def __getitem__(self, index): if not isinstance(index, Integral): raise TypeError("'%s' object cannot be interpreted as an index" % type(index).__name__) if index < 0: index += self._count + len(self._extra_tail) if self._count <= index < self._count + len(self._extra_tail): return self._extra_tail[index - self._count] return PythonPVector._node_for(self, index)[index & BIT_MASK] def _reset(self, v): self._count = v._count self._shift = v._shift self._root = v._root self._tail = v._tail self._tail_offset = v._tail_offset self._dirty_nodes = {} self._cached_leafs = {} self._extra_tail = [] self._orig_pvector = v def append(self, element): self._extra_tail.append(element) return self def extend(self, iterable): self._extra_tail.extend(iterable) return self def set(self, index, val): self[index] = val return self def __setitem__(self, index, val): if not isinstance(index, Integral): raise TypeError("'%s' object cannot be interpreted as an index" % type(index).__name__) if index < 0: index += self._count + len(self._extra_tail) if 0 <= index < self._count: node = self._cached_leafs.get(index >> SHIFT) if node: node[index & BIT_MASK] = val elif index >= self._tail_offset: if id(self._tail) not in self._dirty_nodes: self._tail = list(self._tail) self._dirty_nodes[id(self._tail)] = True self._cached_leafs[index >> SHIFT] = self._tail self._tail[index & BIT_MASK] = val else: self._root = self._do_set(self._shift, self._root, index, val) elif self._count <= index < self._count + len(self._extra_tail): self._extra_tail[index - self._count] = val elif index == self._count + len(self._extra_tail): self._extra_tail.append(val) else: raise IndexError("Index out of range: %s" % (index,)) def _do_set(self, level, node, i, val): if id(node) in self._dirty_nodes: ret = node else: ret = list(node) self._dirty_nodes[id(ret)] = True if level == 0: ret[i & BIT_MASK] = val self._cached_leafs[i >> SHIFT] = ret else: sub_index = (i >> level) & BIT_MASK # >>> ret[sub_index] = self._do_set(level - SHIFT, node[sub_index], i, val) return ret def delete(self, index, stop=None): del self[_index_or_slice(index, stop)] return self def __delitem__(self, key): if self._orig_pvector: # All structural sharing bets are off, base evolver on _extra_tail only l = self._orig_pvector.tolist() l.extend(self._extra_tail) self._reset(_EMPTY_PVECTOR) self._extra_tail = l del self._extra_tail[key] def persistent(self): result = self._orig_pvector if self.is_dirty(): result = PythonPVector(self._count, self._shift, self._root, self._tail).extend(self._extra_tail) self._reset(result) return result def __len__(self): return self._count + len(self._extra_tail) def is_dirty(self): return bool(self._dirty_nodes or self._extra_tail) def evolver(self): return PythonPVector.Evolver(self) def set(self, i, val): # This method could be implemented by a call to mset() but doing so would cause # a ~5 X performance penalty on PyPy (considered the primary platform for this implementation # of PVector) so we're keeping this implementation for now. if not isinstance(i, Integral): raise TypeError("'%s' object cannot be interpreted as an index" % type(i).__name__) if i < 0: i += self._count if 0 <= i < self._count: if i >= self._tail_offset: new_tail = list(self._tail) new_tail[i & BIT_MASK] = val return PythonPVector(self._count, self._shift, self._root, new_tail) return PythonPVector(self._count, self._shift, self._do_set(self._shift, self._root, i, val), self._tail) if i == self._count: return self.append(val) raise IndexError("Index out of range: %s" % (i,)) def _do_set(self, level, node, i, val): ret = list(node) if level == 0: ret[i & BIT_MASK] = val else: sub_index = (i >> level) & BIT_MASK # >>> ret[sub_index] = self._do_set(level - SHIFT, node[sub_index], i, val) return ret @staticmethod def _node_for(pvector_like, i): if 0 <= i < pvector_like._count: if i >= pvector_like._tail_offset: return pvector_like._tail node = pvector_like._root for level in range(pvector_like._shift, 0, -SHIFT): node = node[(i >> level) & BIT_MASK] # >>> return node raise IndexError("Index out of range: %s" % (i,)) def _create_new_root(self): new_shift = self._shift # Overflow root? if (self._count >> SHIFT) > (1 << self._shift): # >>> new_root = [self._root, self._new_path(self._shift, self._tail)] new_shift += SHIFT else: new_root = self._push_tail(self._shift, self._root, self._tail) return new_root, new_shift def append(self, val): if len(self._tail) < BRANCH_FACTOR: new_tail = list(self._tail) new_tail.append(val) return PythonPVector(self._count + 1, self._shift, self._root, new_tail) # Full tail, push into tree new_root, new_shift = self._create_new_root() return PythonPVector(self._count + 1, new_shift, new_root, [val]) def _new_path(self, level, node): if level == 0: return node return [self._new_path(level - SHIFT, node)] def _mutating_insert_tail(self): self._root, self._shift = self._create_new_root() self._tail = [] def _mutating_fill_tail(self, offset, sequence): max_delta_len = BRANCH_FACTOR - len(self._tail) delta = sequence[offset:offset + max_delta_len] self._tail.extend(delta) delta_len = len(delta) self._count += delta_len return offset + delta_len def _mutating_extend(self, sequence): offset = 0 sequence_len = len(sequence) while offset < sequence_len: offset = self._mutating_fill_tail(offset, sequence) if len(self._tail) == BRANCH_FACTOR: self._mutating_insert_tail() self._tail_offset = self._count - len(self._tail) def extend(self, obj): # Mutates the new vector directly for efficiency but that's only an # implementation detail, once it is returned it should be considered immutable l = obj.tolist() if isinstance(obj, PythonPVector) else list(obj) if l: new_vector = self.append(l[0]) new_vector._mutating_extend(l[1:]) return new_vector return self def _push_tail(self, level, parent, tail_node): """ if parent is leaf, insert node, else does it map to an existing child? -> node_to_insert = push node one more level else alloc new path return node_to_insert placed in copy of parent """ ret = list(parent) if level == SHIFT: ret.append(tail_node) return ret sub_index = ((self._count - 1) >> level) & BIT_MASK # >>> if len(parent) > sub_index: ret[sub_index] = self._push_tail(level - SHIFT, parent[sub_index], tail_node) return ret ret.append(self._new_path(level - SHIFT, tail_node)) return ret def index(self, value, *args, **kwargs): return self.tolist().index(value, *args, **kwargs) def count(self, value): return self.tolist().count(value) def delete(self, index, stop=None): l = self.tolist() del l[_index_or_slice(index, stop)] return _EMPTY_PVECTOR.extend(l) @six.add_metaclass(ABCMeta) class PVector(object): """ Persistent vector implementation. Meant as a replacement for the cases where you would normally use a Python list. Do not instantiate directly, instead use the factory functions :py:func:`v` and :py:func:`pvector` to create an instance. Heavily influenced by the persistent vector available in Clojure. Initially this was more or less just a port of the Java code for the Clojure vector. It has since been modified and to some extent optimized for usage in Python. The vector is organized as a trie, any mutating method will return a new vector that contains the changes. No updates are done to the original vector. Structural sharing between vectors are applied where possible to save space and to avoid making complete copies. This structure corresponds most closely to the built in list type and is intended as a replacement. Where the semantics are the same (more or less) the same function names have been used but for some cases it is not possible, for example assignments. The PVector implements the Sequence protocol and is Hashable. Inserts are amortized O(1). Random access is log32(n) where n is the size of the vector. The following are examples of some common operations on persistent vectors: >>> p = v(1, 2, 3) >>> p2 = p.append(4) >>> p3 = p2.extend([5, 6, 7]) >>> p pvector([1, 2, 3]) >>> p2 pvector([1, 2, 3, 4]) >>> p3 pvector([1, 2, 3, 4, 5, 6, 7]) >>> p3[5] 6 >>> p.set(1, 99) pvector([1, 99, 3]) >>> """ @abstractmethod def __len__(self): """ >>> len(v(1, 2, 3)) 3 """ @abstractmethod def __getitem__(self, index): """ Get value at index. Full slicing support. >>> v1 = v(5, 6, 7, 8) >>> v1[2] 7 >>> v1[1:3] pvector([6, 7]) """ @abstractmethod def __add__(self, other): """ >>> v1 = v(1, 2) >>> v2 = v(3, 4) >>> v1 + v2 pvector([1, 2, 3, 4]) """ @abstractmethod def __mul__(self, times): """ >>> v1 = v(1, 2) >>> 3 * v1 pvector([1, 2, 1, 2, 1, 2]) """ @abstractmethod def __hash__(self): """ >>> v1 = v(1, 2, 3) >>> v2 = v(1, 2, 3) >>> hash(v1) == hash(v2) True """ @abstractmethod def evolver(self): """ Create a new evolver for this pvector. The evolver acts as a mutable view of the vector with "transaction like" semantics. No part of the underlying vector i updated, it is still fully immutable. Furthermore multiple evolvers created from the same pvector do not interfere with each other. You may want to use an evolver instead of working directly with the pvector in the following cases: * Multiple updates are done to the same vector and the intermediate results are of no interest. In this case using an evolver may be a more efficient and easier to work with. * You need to pass a vector into a legacy function or a function that you have no control over which performs in place mutations of lists. In this case pass an evolver instance instead and then create a new pvector from the evolver once the function returns. The following example illustrates a typical workflow when working with evolvers. It also displays most of the API (which i kept small by design, you should not be tempted to use evolvers in excess ;-)). Create the evolver and perform various mutating updates to it: >>> v1 = v(1, 2, 3, 4, 5) >>> e = v1.evolver() >>> e[1] = 22 >>> _ = e.append(6) >>> _ = e.extend([7, 8, 9]) >>> e[8] += 1 >>> len(e) 9 The underlying pvector remains the same: >>> v1 pvector([1, 2, 3, 4, 5]) The changes are kept in the evolver. An updated pvector can be created using the persistent() function on the evolver. >>> v2 = e.persistent() >>> v2 pvector([1, 22, 3, 4, 5, 6, 7, 8, 10]) The new pvector will share data with the original pvector in the same way that would have been done if only using operations on the pvector. """ @abstractmethod def mset(self, *args): """ Return a new vector with elements in specified positions replaced by values (multi set). Elements on even positions in the argument list are interpreted as indexes while elements on odd positions are considered values. >>> v1 = v(1, 2, 3) >>> v1.mset(0, 11, 2, 33) pvector([11, 2, 33]) """ @abstractmethod def set(self, i, val): """ Return a new vector with element at position i replaced with val. The original vector remains unchanged. Setting a value one step beyond the end of the vector is equal to appending. Setting beyond that will result in an IndexError. >>> v1 = v(1, 2, 3) >>> v1.set(1, 4) pvector([1, 4, 3]) >>> v1.set(3, 4) pvector([1, 2, 3, 4]) >>> v1.set(-1, 4) pvector([1, 2, 4]) """ @abstractmethod def append(self, val): """ Return a new vector with val appended. >>> v1 = v(1, 2) >>> v1.append(3) pvector([1, 2, 3]) """ @abstractmethod def extend(self, obj): """ Return a new vector with all values in obj appended to it. Obj may be another PVector or any other Iterable. >>> v1 = v(1, 2, 3) >>> v1.extend([4, 5]) pvector([1, 2, 3, 4, 5]) """ @abstractmethod def index(self, value, *args, **kwargs): """ Return first index of value. Additional indexes may be supplied to limit the search to a sub range of the vector. >>> v1 = v(1, 2, 3, 4, 3) >>> v1.index(3) 2 >>> v1.index(3, 3, 5) 4 """ @abstractmethod def count(self, value): """ Return the number of times that value appears in the vector. >>> v1 = v(1, 4, 3, 4) >>> v1.count(4) 2 """ @abstractmethod def transform(self, *transformations): """ Transform arbitrarily complex combinations of PVectors and PMaps. A transformation consists of two parts. One match expression that specifies which elements to transform and one transformation function that performs the actual transformation. >>> from pyrsistent import freeze, ny >>> news_paper = freeze({'articles': [{'author': 'Sara', 'content': 'A short article'}, ... {'author': 'Steve', 'content': 'A slightly longer article'}], ... 'weather': {'temperature': '11C', 'wind': '5m/s'}}) >>> short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:25] + '...' if len(c) > 25 else c) >>> very_short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:15] + '...' if len(c) > 15 else c) >>> very_short_news.articles[0].content 'A short article' >>> very_short_news.articles[1].content 'A slightly long...' When nothing has been transformed the original data structure is kept >>> short_news is news_paper True >>> very_short_news is news_paper False >>> very_short_news.articles[0] is news_paper.articles[0] True """ @abstractmethod def delete(self, index, stop=None): """ Delete a portion of the vector by index or range. >>> v1 = v(1, 2, 3, 4, 5) >>> v1.delete(1) pvector([1, 3, 4, 5]) >>> v1.delete(1, 3) pvector([1, 4, 5]) """ _EMPTY_PVECTOR = PythonPVector(0, SHIFT, [], []) PVector.register(PythonPVector) Sequence.register(PVector) Hashable.register(PVector) def python_pvector(iterable=()): """ Create a new persistent vector containing the elements in iterable. >>> v1 = pvector([1, 2, 3]) >>> v1 pvector([1, 2, 3]) """ return _EMPTY_PVECTOR.extend(iterable) try: # Use the C extension as underlying trie implementation if it is available import os if os.environ.get('PYRSISTENT_NO_C_EXTENSION'): pvector = python_pvector else: from pvectorc import pvector PVector.register(type(pvector())) except ImportError: pvector = python_pvector def v(*elements): """ Create a new persistent vector containing all parameters to this function. >>> v1 = v(1, 2, 3) >>> v1 pvector([1, 2, 3]) """ return pvector(elements)
import pickle import pytest from pyrsistent import plist, l def test_literalish_works(): assert l(1, 2, 3) == plist([1, 2, 3]) def test_first_and_rest(): pl = plist([1, 2]) assert pl.first == 1 assert pl.rest.first == 2 assert pl.rest.rest is plist() def test_instantiate_large_list(): assert plist(range(1000)).first == 0 def test_iteration(): assert list(plist()) == [] assert list(plist([1, 2, 3])) == [1, 2, 3] def test_cons(): assert plist([1, 2, 3]).cons(0) == plist([0, 1, 2, 3]) def test_cons_empty_list(): assert plist().cons(0) == plist([0]) def test_truthiness(): assert plist([1]) assert not plist() def test_len(): assert len(plist([1, 2, 3])) == 3 assert len(plist()) == 0 def test_first_illegal_on_empty_list(): with pytest.raises(AttributeError): plist().first def test_rest_return_self_on_empty_list(): assert plist().rest is plist() def test_reverse(): assert plist([1, 2, 3]).reverse() == plist([3, 2, 1]) assert reversed(plist([1, 2, 3])) == plist([3, 2, 1]) assert plist().reverse() == plist() assert reversed(plist()) == plist() def test_inequality(): assert plist([1, 2]) != plist([1, 3]) assert plist([1, 2]) != plist([1, 2, 3]) assert plist() != plist([1, 2, 3]) def test_repr(): assert str(plist()) == "plist([])" assert str(plist([1, 2, 3])) == "plist([1, 2, 3])" def test_indexing(): assert plist([1, 2, 3])[2] == 3 assert plist([1, 2, 3])[-1] == 3 def test_indexing_on_empty_list(): with pytest.raises(IndexError): plist()[0] def test_index_out_of_range(): with pytest.raises(IndexError): plist([1, 2])[2] with pytest.raises(IndexError): plist([1, 2])[-3] def test_index_invalid_type(): with pytest.raises(TypeError) as e: plist([1, 2, 3])['foo'] assert 'cannot be interpreted' in str(e) def test_slicing_take(): assert plist([1, 2, 3])[:2] == plist([1, 2]) def test_slicing_take_out_of_range(): assert plist([1, 2, 3])[:20] == plist([1, 2, 3]) def test_slicing_drop(): li = plist([1, 2, 3]) assert li[1:] is li.rest def test_slicing_drop_out_of_range(): assert plist([1, 2, 3])[3:] is plist() def test_contains(): assert 2 in plist([1, 2, 3]) assert 4 not in plist([1, 2, 3]) assert 1 not in plist() def test_count(): assert plist([1, 2, 1]).count(1) == 2 assert plist().count(1) == 0 def test_index(): assert plist([1, 2, 3]).index(3) == 2 def test_index_item_not_found(): with pytest.raises(ValueError): plist().index(3) with pytest.raises(ValueError): plist([1, 2]).index(3) def test_pickling_empty_list(): assert pickle.loads(pickle.dumps(plist(), -1)) == plist() def test_pickling_non_empty_list(): assert pickle.loads(pickle.dumps(plist([1, 2, 3]), -1)) == plist([1, 2, 3]) def test_comparison(): assert plist([1, 2]) < plist([1, 2, 3]) assert plist([2, 1]) > plist([1, 2, 3]) assert plist() < plist([1]) assert plist([1]) > plist() def test_comparison_with_other_type(): assert plist() != [] def test_hashing(): assert hash(plist([1, 2])) == hash(plist([1, 2])) assert hash(plist([1, 2])) != hash(plist([2, 1])) def test_split(): left_list, right_list = plist([1, 2, 3, 4, 5]).split(3) assert left_list == plist([1, 2, 3]) assert right_list == plist([4, 5]) def test_split_no_split_occurred(): x = plist([1, 2]) left_list, right_list = x.split(2) assert left_list is x assert right_list is plist() def test_split_empty_list(): left_list, right_list = plist().split(2) assert left_list == plist() assert right_list == plist() def test_remove(): assert plist([1, 2, 3, 2]).remove(2) == plist([1, 3, 2]) assert plist([1, 2, 3]).remove(1) == plist([2, 3]) assert plist([1, 2, 3]).remove(3) == plist([1, 2]) def test_remove_missing_element(): with pytest.raises(ValueError): plist([1, 2]).remove(3) with pytest.raises(ValueError): plist().remove(2) def test_mcons(): assert plist([1, 2]).mcons([3, 4]) == plist([4, 3, 1, 2]) def test_supports_weakref(): import weakref weakref.ref(plist()) weakref.ref(plist([1, 2]))
Futrell/pyrsistent
tests/list_test.py
pyrsistent/_pvector.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # Rob Crittenden <rcritten@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ RPC client and shared RPC client/server functionality. This module adds some additional functionality on top of the ``xmlrpc.client`` module in the Python standard library (``xmlrpclib`` in Python 2). For documentation on the ``xmlrpclib`` module, see: http://docs.python.org/2/library/xmlrpclib.html Also see the `ipaserver.rpcserver` module. """ from __future__ import absolute_import from decimal import Decimal import datetime import os import locale import base64 import json import re import socket import gzip import gssapi from dns import resolver, rdatatype from dns.exception import DNSException from ssl import SSLError import six from six.moves import urllib from ipalib.backend import Connectible from ipalib.constants import LDAP_GENERALIZED_TIME_FORMAT from ipalib.errors import (public_errors, UnknownError, NetworkError, KerberosError, XMLRPCMarshallError, JSONError) from ipalib import errors, capabilities from ipalib.request import context, Connection from ipapython.ipa_log_manager import root_logger from ipapython import ipautil from ipapython import session_storage from ipapython.cookie import Cookie from ipapython.dnsutil import DNSName from ipalib.text import _ from ipalib.util import create_https_connection from ipalib.krb_utils import KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN, KRB5KRB_AP_ERR_TKT_EXPIRED, \ KRB5_FCC_PERM, KRB5_FCC_NOFILE, KRB5_CC_FORMAT, \ KRB5_REALM_CANT_RESOLVE, KRB5_CC_NOTFOUND, get_principal from ipapython.dn import DN from ipapython.kerberos import Principal from ipalib.capabilities import VERSION_WITHOUT_CAPABILITIES from ipalib import api # The XMLRPC client is in "six.moves.xmlrpc_client", but pylint # cannot handle that try: from xmlrpclib import (Binary, Fault, DateTime, dumps, loads, ServerProxy, Transport, ProtocolError, MININT, MAXINT) except ImportError: # pylint: disable=import-error from xmlrpc.client import (Binary, Fault, DateTime, dumps, loads, ServerProxy, Transport, ProtocolError, MININT, MAXINT) # pylint: disable=import-error if six.PY3: from http.client import RemoteDisconnected else: from httplib import BadStatusLine as RemoteDisconnected # pylint: enable=import-error if six.PY3: unicode = str COOKIE_NAME = 'ipa_session' CCACHE_COOKIE_KEY = 'X-IPA-Session-Cookie' errors_by_code = dict((e.errno, e) for e in public_errors) def update_persistent_client_session_data(principal, data): ''' Given a principal create or update the session data for that principal in the persistent secure storage. Raises ValueError if unable to perform the action for any reason. ''' try: session_storage.store_data(principal, CCACHE_COOKIE_KEY, data) except Exception as e: raise ValueError(str(e)) def read_persistent_client_session_data(principal): ''' Given a principal return the stored session data for that principal from the persistent secure storage. Raises ValueError if unable to perform the action for any reason. ''' try: return session_storage.get_data(principal, CCACHE_COOKIE_KEY) except Exception as e: raise ValueError(str(e)) def delete_persistent_client_session_data(principal): ''' Given a principal remove the session data for that principal from the persistent secure storage. Raises ValueError if unable to perform the action for any reason. ''' try: session_storage.remove_data(principal, CCACHE_COOKIE_KEY) except Exception as e: raise ValueError(str(e)) def xml_wrap(value, version): """ Wrap all ``str`` in ``xmlrpc.client.Binary``. Because ``xmlrpc.client.dumps()`` will itself convert all ``unicode`` instances into UTF-8 encoded ``str`` instances, we don't do it here. So in total, when encoding data for an XML-RPC packet, the following transformations occur: * All ``str`` instances are treated as binary data and are wrapped in an ``xmlrpc.client.Binary()`` instance. * Only ``unicode`` instances are treated as character data. They get converted to UTF-8 encoded ``str`` instances (although as mentioned, not by this function). Also see `xml_unwrap()`. :param value: The simple scalar or simple compound value to wrap. """ if type(value) in (list, tuple): return tuple(xml_wrap(v, version) for v in value) if isinstance(value, dict): return dict( (k, xml_wrap(v, version)) for (k, v) in value.items() ) if type(value) is bytes: return Binary(value) if type(value) is Decimal: # transfer Decimal as a string return unicode(value) if isinstance(value, six.integer_types) and (value < MININT or value > MAXINT): return unicode(value) if isinstance(value, DN): return str(value) # Encode datetime.datetime objects as xmlrpc.client.DateTime objects if isinstance(value, datetime.datetime): if capabilities.client_has_capability(version, 'datetime_values'): return DateTime(value) else: return value.strftime(LDAP_GENERALIZED_TIME_FORMAT) if isinstance(value, DNSName): if capabilities.client_has_capability(version, 'dns_name_values'): return {'__dns_name__': unicode(value)} else: return unicode(value) if isinstance(value, Principal): return unicode(value) assert type(value) in (unicode, float, bool, type(None)) + six.integer_types return value def xml_unwrap(value, encoding='UTF-8'): """ Unwrap all ``xmlrpc.Binary``, decode all ``str`` into ``unicode``. When decoding data from an XML-RPC packet, the following transformations occur: * The binary payloads of all ``xmlrpc.client.Binary`` instances are returned as ``str`` instances. * All ``str`` instances are treated as UTF-8 encoded Unicode strings. They are decoded and the resulting ``unicode`` instance is returned. Also see `xml_wrap()`. :param value: The value to unwrap. :param encoding: The Unicode encoding to use (defaults to ``'UTF-8'``). """ if type(value) in (list, tuple): return tuple(xml_unwrap(v, encoding) for v in value) if type(value) is dict: if '__dns_name__' in value: return DNSName(value['__dns_name__']) else: return dict( (k, xml_unwrap(v, encoding)) for (k, v) in value.items() ) if isinstance(value, bytes): return value.decode(encoding) if isinstance(value, Binary): assert type(value.data) is bytes return value.data if isinstance(value, DateTime): # xmlprc DateTime is converted to string of %Y%m%dT%H:%M:%S format return datetime.datetime.strptime(str(value), "%Y%m%dT%H:%M:%S") assert type(value) in (unicode, int, float, bool, type(None)) return value def xml_dumps(params, version, methodname=None, methodresponse=False, encoding='UTF-8'): """ Encode an XML-RPC data packet, transparently wraping ``params``. This function will wrap ``params`` using `xml_wrap()` and will then encode the XML-RPC data packet using ``xmlrpc.client.dumps()`` (from the Python standard library). For documentation on the ``xmlrpc.client.dumps()`` function, see: http://docs.python.org/library/xmlrpc.client.html#convenience-functions Also see `xml_loads()`. :param params: A ``tuple`` or an ``xmlrpc.client.Fault`` instance. :param methodname: The name of the method to call if this is a request. :param methodresponse: Set this to ``True`` if this is a response. :param encoding: The Unicode encoding to use (defaults to ``'UTF-8'``). """ if type(params) is tuple: params = xml_wrap(params, version) else: assert isinstance(params, Fault) return dumps(params, methodname=methodname, methodresponse=methodresponse, encoding=encoding, allow_none=True, ) class _JSONPrimer(dict): """Fast JSON primer and pre-converter Prepare a data structure for JSON serialization. In an ideal world, priming could be handled by the default hook of json.dumps(). Unfortunately the hook treats Python 2 str as text while FreeIPA considers str as bytes. The primer uses a couple of tricks to archive maximum performance: * O(1) type look instead of O(n) chain of costly isinstance() calls * __missing__ and __mro__ with caching to handle subclasses * inline code with minor code duplication (func lookup in enc_list/dict) * avoid surplus function calls (e.g. func is _identity, obj.__class__ instead if type(obj)) * function default arguments to turn global into local lookups * avoid re-creation of bound method objects (e.g. result.append) * on-demand lookup of client capabilities with cached values Depending on the client version number, the primer converts: * bytes -> {'__base64__': b64encode} * datetime -> {'__datetime__': LDAP_GENERALIZED_TIME} * DNSName -> {'__dns_name__': unicode} The _ipa_obj_hook() functions unserializes the marked JSON objects to bytes, datetime and DNSName. :see: _ipa_obj_hook """ __slots__ = ('version', '_cap_datetime', '_cap_dnsname') _identity = object() def __init__(self, version, _identity=_identity): super(_JSONPrimer, self).__init__() self.version = version self._cap_datetime = None self._cap_dnsname = None self.update({ unicode: _identity, bool: _identity, type(None): _identity, float: _identity, Decimal: unicode, DN: str, Principal: unicode, DNSName: self._enc_dnsname, datetime.datetime: self._enc_datetime, bytes: self._enc_bytes, list: self._enc_list, tuple: self._enc_list, dict: self._enc_dict, }) # int, long for t in six.integer_types: self[t] = _identity def __missing__(self, typ): # walk MRO to find best match for c in typ.__mro__: if c in self: self[typ] = self[c] return self[c] # use issubclass to check for registered ABCs for c in self: if issubclass(typ, c): self[typ] = self[c] return self[c] raise TypeError(typ) def convert(self, obj, _identity=_identity): # obj.__class__ is twice as fast as type(obj) func = self[obj.__class__] return obj if func is _identity else func(obj) def _enc_datetime(self, val): cap = self._cap_datetime if cap is None: cap = capabilities.client_has_capability(self.version, 'datetime_values') self._cap_datetime = cap if cap: return {'__datetime__': val.strftime(LDAP_GENERALIZED_TIME_FORMAT)} else: return val.strftime(LDAP_GENERALIZED_TIME_FORMAT) def _enc_dnsname(self, val): cap = self._cap_dnsname if cap is None: cap = capabilities.client_has_capability(self.version, 'dns_name_values') self._cap_dnsname = cap if cap: return {'__dns_name__': unicode(val)} else: return unicode(val) def _enc_bytes(self, val): encoded = base64.b64encode(val) if not six.PY2: encoded = encoded.decode('ascii') return {'__base64__': encoded} def _enc_list(self, val, _identity=_identity): result = [] append = result.append for v in val: func = self[v.__class__] append(v if func is _identity else func(v)) return result def _enc_dict(self, val, _identity=_identity, _iteritems=six.iteritems): result = {} for k, v in _iteritems(val): func = self[v.__class__] result[k] = v if func is _identity else func(v) return result def json_encode_binary(val, version, pretty_print=False): """Serialize a Python object structure to JSON :param object val: Python object structure :param str version: client version :param bool pretty_print: indent and sort JSON (warning: slow!) :return: text :note: pretty printing triggers a slow path in Python's JSON module. Only use pretty_print in debug mode. """ result = _JSONPrimer(version).convert(val) if pretty_print: return json.dumps(result, indent=4, sort_keys=True) else: return json.dumps(result) def _ipa_obj_hook(dct, _iteritems=six.iteritems, _list=list): """JSON object hook :see: _JSONPrimer """ if '__base64__' in dct: return base64.b64decode(dct['__base64__']) elif '__datetime__' in dct: return datetime.datetime.strptime(dct['__datetime__'], LDAP_GENERALIZED_TIME_FORMAT) elif '__dns_name__' in dct: return DNSName(dct['__dns_name__']) else: # XXX tests assume tuples. Is this really necessary? for k, v in _iteritems(dct): if v.__class__ is _list: dct[k] = tuple(v) return dct def json_decode_binary(val): """Convert serialized JSON string back to Python data structure :param val: JSON string :type val: str, bytes :return: Python data structure :see: _ipa_obj_hook, _JSONPrimer """ if isinstance(val, bytes): val = val.decode('utf-8') return json.loads(val, object_hook=_ipa_obj_hook) def decode_fault(e, encoding='UTF-8'): assert isinstance(e, Fault) if isinstance(e.faultString, bytes): return Fault(e.faultCode, e.faultString.decode(encoding)) return e def xml_loads(data, encoding='UTF-8'): """ Decode the XML-RPC packet in ``data``, transparently unwrapping its params. This function will decode the XML-RPC packet in ``data`` using ``xmlrpc.client.loads()`` (from the Python standard library). If ``data`` contains a fault, ``xmlrpc.client.loads()`` will itself raise an ``xmlrpc.client.Fault`` exception. Assuming an exception is not raised, this function will then unwrap the params in ``data`` using `xml_unwrap()`. Finally, a ``(params, methodname)`` tuple is returned containing the unwrapped params and the name of the method being called. If the packet contains no method name, ``methodname`` will be ``None``. For documentation on the ``xmlrpc.client.loads()`` function, see: http://docs.python.org/2/library/xmlrpclib.html#convenience-functions Also see `xml_dumps()`. :param data: The XML-RPC packet to decode. """ try: (params, method) = loads(data) return (xml_unwrap(params), method) except Fault as e: raise decode_fault(e) class DummyParser(object): def __init__(self): self.data = [] def feed(self, data): self.data.append(data) def close(self): return b''.join(self.data) class MultiProtocolTransport(Transport): """Transport that handles both XML-RPC and JSON""" def __init__(self, *args, **kwargs): Transport.__init__(self) self.protocol = kwargs.get('protocol', None) def getparser(self): if self.protocol == 'json': parser = DummyParser() return parser, parser else: return Transport.getparser(self) def send_content(self, connection, request_body): if self.protocol == 'json': connection.putheader("Content-Type", "application/json") else: connection.putheader("Content-Type", "text/xml") # gzip compression would be set up here, but we have it turned off # (encode_threshold is None) connection.putheader("Content-Length", str(len(request_body))) connection.endheaders(request_body) class LanguageAwareTransport(MultiProtocolTransport): """Transport sending Accept-Language header""" def get_host_info(self, host): host, extra_headers, x509 = MultiProtocolTransport.get_host_info( self, host) try: lang = locale.setlocale(locale.LC_ALL, '').split('.')[0].lower() except locale.Error: # fallback to default locale lang = 'en_us' if not isinstance(extra_headers, list): extra_headers = [] extra_headers.append( ('Accept-Language', lang.replace('_', '-')) ) extra_headers.append( ('Referer', 'https://%s/ipa/xml' % str(host)) ) return (host, extra_headers, x509) class SSLTransport(LanguageAwareTransport): """Handles an HTTPS transaction to an XML-RPC server.""" def make_connection(self, host): host, self._extra_headers, _x509 = self.get_host_info(host) if self._connection and host == self._connection[0]: root_logger.debug("HTTP connection keep-alive (%s)", host) return self._connection[1] conn = create_https_connection( host, 443, api.env.tls_ca_cert, tls_version_min=api.env.tls_version_min, tls_version_max=api.env.tls_version_max) conn.connect() root_logger.debug("New HTTP connection (%s)", host) self._connection = host, conn return self._connection[1] class KerbTransport(SSLTransport): """ Handles Kerberos Negotiation authentication to an XML-RPC server. """ flags = [gssapi.RequirementFlag.mutual_authentication, gssapi.RequirementFlag.out_of_sequence_detection] def __init__(self, *args, **kwargs): SSLTransport.__init__(self, *args, **kwargs) self._sec_context = None self.service = kwargs.pop("service", "HTTP") self.ccache = kwargs.pop("ccache", None) def _handle_exception(self, e, service=None): minor = e.min_code if minor == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN: raise errors.ServiceError(service=service) elif minor == KRB5_FCC_NOFILE: raise errors.NoCCacheError() elif minor == KRB5KRB_AP_ERR_TKT_EXPIRED: raise errors.TicketExpired() elif minor == KRB5_FCC_PERM: raise errors.BadCCachePerms() elif minor == KRB5_CC_FORMAT: raise errors.BadCCacheFormat() elif minor == KRB5_REALM_CANT_RESOLVE: raise errors.CannotResolveKDC() elif minor == KRB5_CC_NOTFOUND: raise errors.CCacheError() else: raise errors.KerberosError(message=unicode(e)) def _get_host(self): return self._connection[0] def _remove_extra_header(self, name): for (h, v) in self._extra_headers: if h == name: self._extra_headers.remove((h, v)) break def get_auth_info(self, use_cookie=True): """ Two things can happen here. If we have a session we will add a cookie for that. If not we will set an Authorization header. """ if not isinstance(self._extra_headers, list): self._extra_headers = [] # Remove any existing Cookie first self._remove_extra_header('Cookie') if use_cookie: session_cookie = getattr(context, 'session_cookie', None) if session_cookie: self._extra_headers.append(('Cookie', session_cookie)) return # Set the remote host principal host = self._get_host() service = self.service + "@" + host.split(':')[0] try: creds = None if self.ccache: creds = gssapi.Credentials(usage='initiate', store={'ccache': self.ccache}) name = gssapi.Name(service, gssapi.NameType.hostbased_service) self._sec_context = gssapi.SecurityContext(creds=creds, name=name, flags=self.flags) response = self._sec_context.step() except gssapi.exceptions.GSSError as e: self._handle_exception(e, service=service) self._set_auth_header(response) def _set_auth_header(self, token): # Remove any existing authorization header first self._remove_extra_header('Authorization') if token: self._extra_headers.append( ('Authorization', 'negotiate %s' % base64.b64encode(token).decode('ascii')) ) def _auth_complete(self, response): if self._sec_context: header = response.getheader('www-authenticate', '') token = None for field in header.split(','): k, _dummy, v = field.strip().partition(' ') if k.lower() == 'negotiate': try: token = base64.b64decode(v.encode('ascii')) break # b64decode raises TypeError on invalid input except (TypeError, UnicodeError): pass if not token: raise KerberosError( message=u"No valid Negotiate header in server response") token = self._sec_context.step(token=token) if self._sec_context.complete: self._sec_context = None return True self._set_auth_header(token) return False elif response.status == 401: self.get_auth_info(use_cookie=False) return False return True def single_request(self, host, handler, request_body, verbose=0): # Based on Python 2.7's xmllib.Transport.single_request try: h = self.make_connection(host) if verbose: h.set_debuglevel(1) self.get_auth_info() while True: if six.PY2: # pylint: disable=no-value-for-parameter self.send_request(h, handler, request_body) # pylint: enable=no-value-for-parameter self.send_host(h, host) self.send_user_agent(h) self.send_content(h, request_body) response = h.getresponse(buffering=True) else: self.__send_request(h, host, handler, request_body, verbose) response = h.getresponse() if response.status != 200: if (response.getheader("content-length", 0)): response.read() if response.status == 401: if not self._auth_complete(response): continue raise ProtocolError( host + handler, response.status, response.reason, response.msg) self.verbose = verbose if not self._auth_complete(response): continue return self.parse_response(response) except gssapi.exceptions.GSSError as e: self._handle_exception(e) except RemoteDisconnected: # keep-alive connection was terminated by remote peer, close # connection and let transport handle reconnect for us. self.close() root_logger.debug("HTTP server has closed connection (%s)", host) raise except BaseException as e: # Unexpected exception may leave connections in a bad state. self.close() root_logger.debug("HTTP connection destroyed (%s)", host, exc_info=True) raise if six.PY3: def __send_request(self, connection, host, handler, request_body, debug): # Based on xmlrpc.client.Transport.send_request headers = self._extra_headers[:] if debug: connection.set_debuglevel(1) if self.accept_gzip_encoding and gzip: connection.putrequest("POST", handler, skip_accept_encoding=True) connection.putheader("Accept-Encoding", "gzip") headers.append(("Accept-Encoding", "gzip")) else: connection.putrequest("POST", handler) headers.append(("User-Agent", self.user_agent)) self.send_headers(connection, headers) # pylint: disable=E1101 self.send_content(connection, request_body) return connection # Find all occurrences of the expiry component expiry_re = re.compile(r'.*?(&expiry=\d+).*?') def _slice_session_cookie(self, session_cookie): # Keep only the cookie value and strip away all other info. # This is to reduce the churn on FILE ccaches which grow every time we # set new data. The expiration time for the cookie is set in the # encrypted data anyway and will be enforced by the server http_cookie = session_cookie.http_cookie() # We also remove the "expiry" part from the data which is not required for exp in self.expiry_re.findall(http_cookie): http_cookie = http_cookie.replace(exp, '') return http_cookie def store_session_cookie(self, cookie_header): ''' Given the contents of a Set-Cookie header scan the header and extract each cookie contained within until the session cookie is located. Examine the session cookie if the domain and path are specified, if not update the cookie with those values from the request URL. Then write the session cookie into the key store for the principal. If the cookie header is None or the session cookie is not present in the header no action is taken. Context Dependencies: The per thread context is expected to contain: principal The current pricipal the HTTP request was issued for. request_url The URL of the HTTP request. ''' if cookie_header is None: return principal = getattr(context, 'principal', None) request_url = getattr(context, 'request_url', None) root_logger.debug("received Set-Cookie (%s)'%s'", type(cookie_header), cookie_header) if not isinstance(cookie_header, list): cookie_header = [cookie_header] # Search for the session cookie session_cookie = None try: for cookie in cookie_header: session_cookie = ( Cookie.get_named_cookie_from_string( cookie, COOKIE_NAME, request_url, timestamp=datetime.datetime.utcnow()) ) if session_cookie is not None: break except Exception as e: root_logger.error("unable to parse cookie header '%s': %s", cookie_header, e) return if session_cookie is None: return cookie_string = self._slice_session_cookie(session_cookie) root_logger.debug("storing cookie '%s' for principal %s", cookie_string, principal) try: update_persistent_client_session_data(principal, cookie_string) except Exception as e: # Not fatal, we just can't use the session cookie we were sent. pass def parse_response(self, response): if six.PY2: header = response.msg.getheaders('Set-Cookie') else: header = response.msg.get_all('Set-Cookie') self.store_session_cookie(header) return SSLTransport.parse_response(self, response) class DelegatedKerbTransport(KerbTransport): """ Handles Kerberos Negotiation authentication and TGT delegation to an XML-RPC server. """ flags = [gssapi.RequirementFlag.delegate_to_peer, gssapi.RequirementFlag.mutual_authentication, gssapi.RequirementFlag.out_of_sequence_detection] class RPCClient(Connectible): """ Forwarding backend plugin for XML-RPC client. Also see the `ipaserver.rpcserver.xmlserver` plugin. """ # Values to set on subclasses: session_path = None server_proxy_class = ServerProxy protocol = None env_rpc_uri_key = None def get_url_list(self, rpc_uri): """ Create a list of urls consisting of the available IPA servers. """ # the configured URL defines what we use for the discovered servers (_scheme, _netloc, path, _params, _query, _fragment ) = urllib.parse.urlparse(rpc_uri) servers = [] name = '_ldap._tcp.%s.' % self.env.domain try: answers = resolver.query(name, rdatatype.SRV) except DNSException: answers = [] for answer in answers: server = str(answer.target).rstrip(".") servers.append('https://%s%s' % (ipautil.format_netloc(server), path)) servers = list(set(servers)) # the list/set conversion won't preserve order so stick in the # local config file version here. cfg_server = rpc_uri if cfg_server in servers: # make sure the configured master server is there just once and # it is the first one servers.remove(cfg_server) servers.insert(0, cfg_server) else: servers.insert(0, cfg_server) return servers def get_session_cookie_from_persistent_storage(self, principal): ''' Retrieves the session cookie for the given principal from the persistent secure storage. Returns None if not found or unable to retrieve the session cookie for any reason, otherwise returns a Cookie object containing the session cookie. ''' # Get the session data, it should contain a cookie string # (possibly with more than one cookie). try: cookie_string = read_persistent_client_session_data(principal) except Exception: return None # Search for the session cookie within the cookie string try: session_cookie = Cookie.get_named_cookie_from_string( cookie_string, COOKIE_NAME, timestamp=datetime.datetime.utcnow()) except Exception as e: self.log.debug( 'Error retrieving cookie from the persistent storage: {err}' .format(err=e)) return None return session_cookie def apply_session_cookie(self, url): ''' Attempt to load a session cookie for the current principal from the persistent secure storage. If the cookie is successfully loaded adjust the input url's to point to the session path and insert the session cookie into the per thread context for later insertion into the HTTP request. If the cookie is not successfully loaded then the original url is returned and the per thread context is not modified. Context Dependencies: The per thread context is expected to contain: principal The current pricipal the HTTP request was issued for. The per thread context will be updated with: session_cookie A cookie string to be inserted into the Cookie header of the HTPP request. ''' original_url = url principal = getattr(context, 'principal', None) session_cookie = self.get_session_cookie_from_persistent_storage(principal) if session_cookie is None: self.log.debug("failed to find session_cookie in persistent storage for principal '%s'", principal) return original_url else: self.debug("found session_cookie in persistent storage for principal '%s', cookie: '%s'", principal, session_cookie) # Decide if we should send the cookie to the server try: session_cookie.http_return_ok(original_url) except Cookie.Expired as e: self.debug("deleting session data for principal '%s': %s", principal, e) try: delete_persistent_client_session_data(principal) except Exception as e: pass return original_url except Cookie.URLMismatch as e: self.debug("not sending session cookie, URL mismatch: %s", e) return original_url except Exception as e: self.error("not sending session cookie, unknown error: %s", e) return original_url # O.K. session_cookie is valid to be returned, stash it away where it will will # get included in a HTTP Cookie headed sent to the server. self.log.debug("setting session_cookie into context '%s'", session_cookie.http_cookie()) setattr(context, 'session_cookie', session_cookie.http_cookie()) # Form the session URL by substituting the session path into the original URL scheme, netloc, path, params, query, fragment = urllib.parse.urlparse(original_url) path = self.session_path # urlencode *can* take one argument # pylint: disable=too-many-function-args session_url = urllib.parse.urlunparse((scheme, netloc, path, params, query, fragment)) return session_url def create_connection(self, ccache=None, verbose=None, fallback=None, delegate=None, ca_certfile=None): if verbose is None: verbose = self.api.env.verbose if fallback is None: fallback = self.api.env.fallback if delegate is None: delegate = self.api.env.delegate if ca_certfile is None: ca_certfile = self.api.env.tls_ca_cert try: rpc_uri = self.env[self.env_rpc_uri_key] principal = get_principal(ccache_name=ccache) stored_principal = getattr(context, 'principal', None) if principal != stored_principal: try: delattr(context, 'session_cookie') except AttributeError: pass setattr(context, 'principal', principal) # We have a session cookie, try using the session URI to see if it # is still valid if not delegate: rpc_uri = self.apply_session_cookie(rpc_uri) except (errors.CCacheError, ValueError): # No session key, do full Kerberos auth pass context.ca_certfile = ca_certfile urls = self.get_url_list(rpc_uri) serverproxy = None for url in urls: kw = dict(allow_none=True, encoding='UTF-8') kw['verbose'] = verbose if url.startswith('https://'): if delegate: transport_class = DelegatedKerbTransport else: transport_class = KerbTransport else: transport_class = LanguageAwareTransport kw['transport'] = transport_class(protocol=self.protocol, service='HTTP', ccache=ccache) self.log.info('trying %s' % url) setattr(context, 'request_url', url) serverproxy = self.server_proxy_class(url, **kw) if len(urls) == 1: # if we have only 1 server and then let the # main requester handle any errors. This also means it # must handle a 401 but we save a ping. return serverproxy try: command = getattr(serverproxy, 'ping') try: command([], {}) except Fault as e: e = decode_fault(e) if e.faultCode in errors_by_code: error = errors_by_code[e.faultCode] raise error(message=e.faultString) else: raise UnknownError( code=e.faultCode, error=e.faultString, server=url, ) # We don't care about the response, just that we got one break except KerberosError as krberr: # kerberos error on one server is likely on all raise errors.KerberosError(message=unicode(krberr)) except ProtocolError as e: if hasattr(context, 'session_cookie') and e.errcode == 401: # Unauthorized. Remove the session and try again. delattr(context, 'session_cookie') try: delete_persistent_client_session_data(principal) except Exception as e: # This shouldn't happen if we have a session but it isn't fatal. pass return self.create_connection(ccache, verbose, fallback, delegate) if not fallback: raise serverproxy = None except Exception as e: if not fallback: raise else: self.log.info('Connection to %s failed with %s', url, e) serverproxy = None if serverproxy is None: raise NetworkError(uri=_('any of the configured servers'), error=', '.join(urls)) return serverproxy def destroy_connection(self): conn = getattr(context, self.id, None) if conn is not None: conn = conn.conn._ServerProxy__transport conn.close() def _call_command(self, command, params): """Call the command with given params""" # For XML, this method will wrap/unwrap binary values # For JSON we do that in the proxy return command(*params) def forward(self, name, *args, **kw): """ Forward call to command named ``name`` over XML-RPC. This method will encode and forward an XML-RPC request, and will then decode and return the corresponding XML-RPC response. :param command: The name of the command being forwarded. :param args: Positional arguments to pass to remote command. :param kw: Keyword arguments to pass to remote command. """ server = getattr(context, 'request_url', None) self.log.info("Forwarding '%s' to %s server '%s'", name, self.protocol, server) command = getattr(self.conn, name) params = [args, kw] try: return self._call_command(command, params) except Fault as e: e = decode_fault(e) self.debug('Caught fault %d from server %s: %s', e.faultCode, server, e.faultString) if e.faultCode in errors_by_code: error = errors_by_code[e.faultCode] raise error(message=e.faultString) raise UnknownError( code=e.faultCode, error=e.faultString, server=server, ) except SSLError as e: raise NetworkError(uri=server, error=str(e)) except ProtocolError as e: # By catching a 401 here we can detect the case where we have # a single IPA server and the session is invalid. Otherwise # we always have to do a ping(). session_cookie = getattr(context, 'session_cookie', None) if session_cookie and e.errcode == 401: # Unauthorized. Remove the session and try again. delattr(context, 'session_cookie') try: principal = getattr(context, 'principal', None) delete_persistent_client_session_data(principal) except Exception as e: # This shouldn't happen if we have a session but it isn't fatal. pass # Create a new serverproxy with the non-session URI serverproxy = self.create_connection(os.environ.get('KRB5CCNAME'), self.env.verbose, self.env.fallback, self.env.delegate) setattr(context, self.id, Connection(serverproxy, self.disconnect)) return self.forward(name, *args, **kw) raise NetworkError(uri=server, error=e.errmsg) except socket.error as e: raise NetworkError(uri=server, error=str(e)) except (OverflowError, TypeError) as e: raise XMLRPCMarshallError(error=str(e)) class xmlclient(RPCClient): session_path = '/ipa/session/xml' server_proxy_class = ServerProxy protocol = 'xml' env_rpc_uri_key = 'xmlrpc_uri' def _call_command(self, command, params): version = params[1].get('version', VERSION_WITHOUT_CAPABILITIES) params = xml_wrap(params, version) result = command(*params) return xml_unwrap(result) class JSONServerProxy(object): def __init__(self, uri, transport, encoding, verbose, allow_none): split_uri = urllib.parse.urlsplit(uri) if split_uri.scheme not in ("http", "https"): raise IOError("unsupported XML-RPC protocol") self.__host = split_uri.netloc self.__handler = split_uri.path self.__transport = transport assert encoding == 'UTF-8' assert allow_none self.__verbose = verbose # FIXME: Some of our code requires ServerProxy internals. # But, xmlrpc.client.ServerProxy's _ServerProxy__transport can be accessed # by calling serverproxy('transport') self._ServerProxy__transport = transport def __request(self, name, args): print_json = self.__verbose >= 2 payload = {'method': unicode(name), 'params': args, 'id': 0} version = args[1].get('version', VERSION_WITHOUT_CAPABILITIES) payload = json_encode_binary( payload, version, pretty_print=print_json) if print_json: root_logger.info( 'Request: %s', payload ) response = self.__transport.request( self.__host, self.__handler, payload.encode('utf-8'), verbose=self.__verbose >= 3, ) if print_json: root_logger.info( 'Response: %s', json.dumps(json.loads(response), sort_keys=True, indent=4) ) try: response = json_decode_binary(response) except ValueError as e: raise JSONError(error=str(e)) error = response.get('error') if error: try: error_class = errors_by_code[error['code']] except KeyError: raise UnknownError( code=error.get('code'), error=error.get('message'), server=self.__host, ) else: kw = error.get('data', {}) kw['message'] = error['message'] raise error_class(**kw) return response['result'] def __getattr__(self, name): def _call(*args): return self.__request(name, args) return _call class jsonclient(RPCClient): session_path = '/ipa/session/json' server_proxy_class = JSONServerProxy protocol = 'json' env_rpc_uri_key = 'jsonrpc_uri'
# Authors: # Pavel Zuna <pzuna@redhat.com> # # Copyright (C) 2009 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipaserver/plugins/hbacrule.py` module. """ from nose.tools import raises, assert_raises # pylint: disable=E0611 from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, assert_attr_equal from ipalib import api from ipalib import errors import pytest @pytest.mark.tier1 class test_hbac(XMLRPC_test): """ Test the `hbacrule` plugin. """ rule_name = u'testing_rule1234' rule_renamed = u'mega_testing_rule' rule_type = u'allow' rule_type_fail = u'value not allowed' rule_service = u'ssh' rule_time = u'absolute 20081010000000 ~ 20081015120000' rule_time2 = u'absolute 20081010000000 ~ 20081016120000' # wrong time, has 30th day in February in first date rule_time_fail = u'absolute 20080230000000 ~ 20081015120000' rule_desc = u'description' rule_desc_mod = u'description modified' test_user = u'hbacrule_test_user' test_group = u'hbacrule_test_group' test_host = u'hbacrule.testnetgroup' test_hostgroup = u'hbacrule_test_hostgroup' test_service = u'sshd' test_host_external = u'notfound.example.com' test_invalid_sourcehost = u'inv+alid#srchost.nonexist.com' def test_0_hbacrule_add(self): """ Test adding a new HBAC rule using `xmlrpc.hbacrule_add`. """ ret = self.failsafe_add(api.Object.hbacrule, self.rule_name, accessruletype=self.rule_type, description=self.rule_desc, ) entry = ret['result'] assert_attr_equal(entry, 'cn', self.rule_name) assert_attr_equal(entry, 'accessruletype', self.rule_type) assert_attr_equal(entry, 'ipaenabledflag', 'TRUE') assert_attr_equal(entry, 'description', self.rule_desc) @raises(errors.DuplicateEntry) def test_1_hbacrule_add(self): """ Test adding an existing HBAC rule using `xmlrpc.hbacrule_add'. """ api.Command['hbacrule_add']( self.rule_name, accessruletype=self.rule_type ) def test_2_hbacrule_show(self): """ Test displaying a HBAC rule using `xmlrpc.hbacrule_show`. """ entry = api.Command['hbacrule_show'](self.rule_name)['result'] assert_attr_equal(entry, 'cn', self.rule_name) assert_attr_equal(entry, 'ipaenabledflag', 'TRUE') assert_attr_equal(entry, 'description', self.rule_desc) def test_3_hbacrule_mod(self): """ Test modifying a HBAC rule using `xmlrpc.hbacrule_mod`. """ ret = api.Command['hbacrule_mod']( self.rule_name, description=self.rule_desc_mod ) entry = ret['result'] assert_attr_equal(entry, 'description', self.rule_desc_mod) # def test_4_hbacrule_add_accesstime(self): # """ # Test adding access time to HBAC rule using `xmlrpc.hbacrule_add_accesstime`. # """ # return # ret = api.Command['hbacrule_add_accesstime']( # self.rule_name, accesstime=self.rule_time2 # ) # entry = ret['result'] # assert_attr_equal(entry, 'accesstime', self.rule_time); # assert_attr_equal(entry, 'accesstime', self.rule_time2); # def test_5_hbacrule_add_accesstime(self): # """ # Test adding invalid access time to HBAC rule using `xmlrpc.hbacrule_add_accesstime`. # """ # try: # api.Command['hbacrule_add_accesstime']( # self.rule_name, accesstime=self.rule_time_fail # ) # except errors.ValidationError: # pass # else: # assert False def test_6_hbacrule_find(self): """ Test searching for HBAC rules using `xmlrpc.hbacrule_find`. """ ret = api.Command['hbacrule_find']( cn=self.rule_name, accessruletype=self.rule_type, description=self.rule_desc_mod ) assert ret['truncated'] is False entries = ret['result'] assert_attr_equal(entries[0], 'cn', self.rule_name) assert_attr_equal(entries[0], 'accessruletype', self.rule_type) assert_attr_equal(entries[0], 'description', self.rule_desc_mod) def test_7_hbacrule_init_testing_data(self): """ Initialize data for more HBAC plugin testing. """ self.failsafe_add(api.Object.user, self.test_user, givenname=u'first', sn=u'last' ) self.failsafe_add(api.Object.group, self.test_group, description=u'description' ) self.failsafe_add(api.Object.host, self.test_host, force=True ) self.failsafe_add(api.Object.hostgroup, self.test_hostgroup, description=u'description' ) self.failsafe_add(api.Object.hbacsvc, self.test_service, description=u'desc', ) def test_8_hbacrule_add_user(self): """ Test adding user and group to HBAC rule using `xmlrpc.hbacrule_add_user`. """ ret = api.Command['hbacrule_add_user']( self.rule_name, user=self.test_user, group=self.test_group ) assert ret['completed'] == 2 failed = ret['failed'] assert 'memberuser' in failed assert 'user' in failed['memberuser'] assert not failed['memberuser']['user'] assert 'group' in failed['memberuser'] assert not failed['memberuser']['group'] entry = ret['result'] assert_attr_equal(entry, 'memberuser_user', self.test_user) assert_attr_equal(entry, 'memberuser_group', self.test_group) def test_9_a_show_user(self): """ Test showing a user to verify HBAC rule membership `xmlrpc.user_show`. """ ret = api.Command['user_show'](self.test_user, all=True) entry = ret['result'] assert_attr_equal(entry, 'memberof_hbacrule', self.rule_name) def test_9_b_show_group(self): """ Test showing a group to verify HBAC rule membership `xmlrpc.group_show`. """ ret = api.Command['group_show'](self.test_group, all=True) entry = ret['result'] assert_attr_equal(entry, 'memberof_hbacrule', self.rule_name) def test_9_hbacrule_remove_user(self): """ Test removing user and group from HBAC rule using `xmlrpc.hbacrule_remove_user'. """ ret = api.Command['hbacrule_remove_user']( self.rule_name, user=self.test_user, group=self.test_group ) assert ret['completed'] == 2 failed = ret['failed'] assert 'memberuser' in failed assert 'user' in failed['memberuser'] assert not failed['memberuser']['user'] assert 'group' in failed['memberuser'] assert not failed['memberuser']['group'] entry = ret['result'] assert 'memberuser_user' not in entry assert 'memberuser_group' not in entry def test_a_hbacrule_add_host(self): """ Test adding host and hostgroup to HBAC rule using `xmlrpc.hbacrule_add_host`. """ ret = api.Command['hbacrule_add_host']( self.rule_name, host=self.test_host, hostgroup=self.test_hostgroup ) assert ret['completed'] == 2 failed = ret['failed'] assert 'memberhost' in failed assert 'host' in failed['memberhost'] assert not failed['memberhost']['host'] assert 'hostgroup' in failed['memberhost'] assert not failed['memberhost']['hostgroup'] entry = ret['result'] assert_attr_equal(entry, 'memberhost_host', self.test_host) assert_attr_equal(entry, 'memberhost_hostgroup', self.test_hostgroup) def test_a_hbacrule_show_host(self): """ Test showing host to verify HBAC rule membership `xmlrpc.host_show`. """ ret = api.Command['host_show'](self.test_host, all=True) entry = ret['result'] assert_attr_equal(entry, 'memberof_hbacrule', self.rule_name) def test_a_hbacrule_show_hostgroup(self): """ Test showing hostgroup to verify HBAC rule membership `xmlrpc.hostgroup_show`. """ ret = api.Command['hostgroup_show'](self.test_hostgroup, all=True) entry = ret['result'] assert_attr_equal(entry, 'memberof_hbacrule', self.rule_name) def test_b_hbacrule_remove_host(self): """ Test removing host and hostgroup from HBAC rule using `xmlrpc.hbacrule_remove_host`. """ ret = api.Command['hbacrule_remove_host']( self.rule_name, host=self.test_host, hostgroup=self.test_hostgroup ) assert ret['completed'] == 2 failed = ret['failed'] assert 'memberhost' in failed assert 'host' in failed['memberhost'] assert not failed['memberhost']['host'] assert 'hostgroup' in failed['memberhost'] assert not failed['memberhost']['hostgroup'] entry = ret['result'] assert 'memberhost_host' not in entry assert 'memberhost_hostgroup' not in entry @raises(errors.DeprecationError) def test_a_hbacrule_add_sourcehost_deprecated(self): """ Test deprecated command hbacrule_add_sourcehost. """ api.Command['hbacrule_add_sourcehost']( self.rule_name, host=self.test_host, hostgroup=self.test_hostgroup ) def test_a_hbacrule_add_service(self): """ Test adding service to HBAC rule using `xmlrpc.hbacrule_add_service`. """ ret = api.Command['hbacrule_add_service']( self.rule_name, hbacsvc=self.test_service ) assert ret['completed'] == 1 failed = ret['failed'] assert 'memberservice' in failed assert 'hbacsvc' in failed['memberservice'] assert not failed['memberservice']['hbacsvc'] entry = ret['result'] assert_attr_equal(entry, 'memberservice_hbacsvc', self.test_service) def test_a_hbacrule_remove_service(self): """ Test removing service to HBAC rule using `xmlrpc.hbacrule_remove_service`. """ ret = api.Command['hbacrule_remove_service']( self.rule_name, hbacsvc=self.test_service ) assert ret['completed'] == 1 failed = ret['failed'] assert 'memberservice' in failed assert 'hbacsvc' in failed['memberservice'] assert not failed['memberservice']['hbacsvc'] entry = ret['result'] assert 'memberservice service' not in entry @raises(errors.DeprecationError) def test_b_hbacrule_remove_sourcehost_deprecated(self): """ Test deprecated command hbacrule_remove_sourcehost. """ api.Command['hbacrule_remove_sourcehost']( self.rule_name, host=self.test_host, hostgroup=self.test_hostgroup ) @raises(errors.ValidationError) def test_c_hbacrule_mod_invalid_external_setattr(self): """ Test adding the same external host using `xmlrpc.hbacrule_add_host`. """ api.Command['hbacrule_mod']( self.rule_name, setattr=self.test_invalid_sourcehost ) def test_d_hbacrule_disable(self): """ Test disabling HBAC rule using `xmlrpc.hbacrule_disable`. """ assert api.Command['hbacrule_disable'](self.rule_name)['result'] is True entry = api.Command['hbacrule_show'](self.rule_name)['result'] # FIXME: Should this be 'disabled' or 'FALSE'? assert_attr_equal(entry, 'ipaenabledflag', 'FALSE') def test_e_hbacrule_enabled(self): """ Test enabling HBAC rule using `xmlrpc.hbacrule_enable`. """ assert api.Command['hbacrule_enable'](self.rule_name)['result'] is True # check it's really enabled entry = api.Command['hbacrule_show'](self.rule_name)['result'] # FIXME: Should this be 'enabled' or 'TRUE'? assert_attr_equal(entry, 'ipaenabledflag', 'TRUE') def test_ea_hbacrule_disable_setattr(self): """ Test disabling HBAC rule using setattr """ command_result = api.Command['hbacrule_mod']( self.rule_name, setattr=u'ipaenabledflag=false') assert command_result['result']['ipaenabledflag'] == (u'FALSE',) entry = api.Command['hbacrule_show'](self.rule_name)['result'] assert_attr_equal(entry, 'ipaenabledflag', 'FALSE') def test_eb_hbacrule_enable_setattr(self): """ Test enabling HBAC rule using setattr """ command_result = api.Command['hbacrule_mod']( self.rule_name, setattr=u'ipaenabledflag=1') assert command_result['result']['ipaenabledflag'] == (u'TRUE',) # check it's really enabled entry = api.Command['hbacrule_show'](self.rule_name)['result'] assert_attr_equal(entry, 'ipaenabledflag', 'TRUE') @raises(errors.MutuallyExclusiveError) def test_f_hbacrule_exclusiveuser(self): """ Test adding a user to an HBAC rule when usercat='all' """ api.Command['hbacrule_mod'](self.rule_name, usercategory=u'all') try: api.Command['hbacrule_add_user'](self.rule_name, user=u'admin') finally: api.Command['hbacrule_mod'](self.rule_name, usercategory=u'') @raises(errors.MutuallyExclusiveError) def test_g_hbacrule_exclusiveuser(self): """ Test setting usercat='all' in an HBAC rule when there are users """ api.Command['hbacrule_add_user'](self.rule_name, user=u'admin') try: api.Command['hbacrule_mod'](self.rule_name, usercategory=u'all') finally: api.Command['hbacrule_remove_user'](self.rule_name, user=u'admin') @raises(errors.MutuallyExclusiveError) def test_h_hbacrule_exclusivehost(self): """ Test adding a host to an HBAC rule when hostcat='all' """ api.Command['hbacrule_mod'](self.rule_name, hostcategory=u'all') try: api.Command['hbacrule_add_host'](self.rule_name, host=self.test_host) finally: api.Command['hbacrule_mod'](self.rule_name, hostcategory=u'') @raises(errors.MutuallyExclusiveError) def test_i_hbacrule_exclusivehost(self): """ Test setting hostcat='all' in an HBAC rule when there are hosts """ api.Command['hbacrule_add_host'](self.rule_name, host=self.test_host) try: api.Command['hbacrule_mod'](self.rule_name, hostcategory=u'all') finally: api.Command['hbacrule_remove_host'](self.rule_name, host=self.test_host) @raises(errors.MutuallyExclusiveError) def test_j_hbacrule_exclusiveservice(self): """ Test adding a service to an HBAC rule when servicecat='all' """ api.Command['hbacrule_mod'](self.rule_name, servicecategory=u'all') try: api.Command['hbacrule_add_service'](self.rule_name, hbacsvc=self.test_service) finally: api.Command['hbacrule_mod'](self.rule_name, servicecategory=u'') @raises(errors.MutuallyExclusiveError) def test_k_hbacrule_exclusiveservice(self): """ Test setting servicecat='all' in an HBAC rule when there are services """ api.Command['hbacrule_add_service'](self.rule_name, hbacsvc=self.test_service) try: api.Command['hbacrule_mod'](self.rule_name, servicecategory=u'all') finally: api.Command['hbacrule_remove_service'](self.rule_name, hbacsvc=self.test_service) @raises(errors.ValidationError) def test_l_hbacrule_add(self): """ Test adding a new HBAC rule with a deny type. """ api.Command['hbacrule_add']( u'denyrule', accessruletype=u'deny', description=self.rule_desc, ) @raises(errors.ValidationError) def test_m_hbacrule_add(self): """ Test changing an HBAC rule to the deny type """ api.Command['hbacrule_mod']( self.rule_name, accessruletype=u'deny', ) def test_n_hbacrule_links(self): """ Test adding various links to HBAC rule """ api.Command['hbacrule_add_service']( self.rule_name, hbacsvc=self.test_service ) entry = api.Command['hbacrule_show'](self.rule_name)['result'] assert_attr_equal(entry, 'cn', self.rule_name) assert_attr_equal(entry, 'memberservice_hbacsvc', self.test_service) def test_o_hbacrule_rename(self): """ Test renaming an HBAC rule, rename it back afterwards """ api.Command['hbacrule_mod']( self.rule_name, rename=self.rule_renamed ) entry = api.Command['hbacrule_show'](self.rule_renamed)['result'] assert_attr_equal(entry, 'cn', self.rule_renamed) # clean up by renaming the rule back api.Command['hbacrule_mod']( self.rule_renamed, rename=self.rule_name ) def test_y_hbacrule_zap_testing_data(self): """ Clear data for HBAC plugin testing. """ api.Command['hbacrule_remove_host'](self.rule_name, host=self.test_host) api.Command['hbacrule_remove_host'](self.rule_name, hostgroup=self.test_hostgroup) api.Command['user_del'](self.test_user) api.Command['group_del'](self.test_group) api.Command['host_del'](self.test_host) api.Command['hostgroup_del'](self.test_hostgroup) api.Command['hbacsvc_del'](self.test_service) def test_k_2_sudorule_referential_integrity(self): """ Test that links in HBAC rule were removed by referential integrity plugin """ entry = api.Command['hbacrule_show'](self.rule_name)['result'] assert_attr_equal(entry, 'cn', self.rule_name) assert 'sourcehost_host' not in entry assert 'sourcehost_hostgroup' not in entry assert 'memberservice_hbacsvc' not in entry def test_z_hbacrule_del(self): """ Test deleting a HBAC rule using `xmlrpc.hbacrule_del`. """ api.Command['hbacrule_del'](self.rule_name) # verify that it's gone with assert_raises(errors.NotFound): api.Command['hbacrule_show'](self.rule_name) @raises(errors.ValidationError) def test_zz_hbacrule_add_with_deprecated_option(self): """ Test using a deprecated command option 'sourcehostcategory' with 'hbacrule_add'. """ api.Command['hbacrule_add']( self.rule_name, sourcehostcategory=u'all' )
redhatrises/freeipa
ipatests/test_xmlrpc/test_hbac_plugin.py
ipalib/rpc.py
import abc import logging from django.db import models from django.utils import timezone from osf.exceptions import ValidationValueError, ValidationTypeError from osf.utils.datetime_aware_jsonfield import DateTimeAwareJSONField from osf.utils.fields import NonNaiveDateTimeField from osf.utils import akismet from website import settings logger = logging.getLogger(__name__) def _get_client(): return akismet.AkismetClient( apikey=settings.AKISMET_APIKEY, website=settings.DOMAIN, verify=True ) def _validate_reports(value, *args, **kwargs): from osf.models import OSFUser for key, val in value.items(): if not OSFUser.load(key): raise ValidationValueError('Keys must be user IDs') if not isinstance(val, dict): raise ValidationTypeError('Values must be dictionaries') if ('category' not in val or 'text' not in val or 'date' not in val or 'retracted' not in val): raise ValidationValueError( ('Values must include `date`, `category`, ', '`text`, `retracted` keys') ) class SpamStatus(object): UNKNOWN = None FLAGGED = 1 SPAM = 2 HAM = 4 class SpamMixin(models.Model): """Mixin to add to objects that can be marked as spam. """ class Meta: abstract = True # # Node fields that trigger an update to search on save # SPAM_UPDATE_FIELDS = { # 'spam_status', # } spam_status = models.IntegerField(default=SpamStatus.UNKNOWN, null=True, blank=True, db_index=True) spam_pro_tip = models.CharField(default=None, null=True, blank=True, max_length=200) # Data representing the original spam indication # - author: author name # - author_email: email of the author # - content: data flagged # - headers: request headers # - Remote-Addr: ip address from request # - User-Agent: user agent from request # - Referer: referrer header from request (typo +1, rtd) spam_data = DateTimeAwareJSONField(default=dict, blank=True) date_last_reported = NonNaiveDateTimeField(default=None, null=True, blank=True, db_index=True) # Reports is a dict of reports keyed on reporting user # Each report is a dictionary including: # - date: date reported # - retracted: if a report has been retracted # - category: What type of spam does the reporter believe this is # - text: Comment on the comment reports = DateTimeAwareJSONField( default=dict, blank=True, validators=[_validate_reports] ) def flag_spam(self): # If ham and unedited then tell user that they should read it again if self.spam_status == SpamStatus.UNKNOWN: self.spam_status = SpamStatus.FLAGGED def remove_flag(self, save=False): if self.spam_status != SpamStatus.FLAGGED: return for report in self.reports.values(): if not report.get('retracted', True): return self.spam_status = SpamStatus.UNKNOWN if save: self.save() @property def is_spam(self): return self.spam_status == SpamStatus.SPAM @property def is_spammy(self): return self.spam_status in [SpamStatus.FLAGGED, SpamStatus.SPAM] def report_abuse(self, user, save=False, **kwargs): """Report object is spam or other abuse of OSF :param user: User submitting report :param save: Save changes :param kwargs: Should include category and message :raises ValueError: if user is reporting self """ if user == self.user: raise ValueError('User cannot report self.') self.flag_spam() date = timezone.now() report = {'date': date, 'retracted': False} report.update(kwargs) if 'text' not in report: report['text'] = None self.reports[user._id] = report self.date_last_reported = report['date'] if save: self.save() def retract_report(self, user, save=False): """Retract last report by user Only marks the last report as retracted because there could be history in how the object is edited that requires a user to flag or retract even if object is marked as HAM. :param user: User retracting :param save: Save changes """ if user._id in self.reports: if not self.reports[user._id]['retracted']: self.reports[user._id]['retracted'] = True self.remove_flag() else: raise ValueError('User has not reported this content') if save: self.save() def confirm_ham(self, save=False): # not all mixins will implement check spam pre-req, only submit ham when it was incorrectly flagged if ( settings.SPAM_CHECK_ENABLED and self.spam_data and self.spam_status in [SpamStatus.FLAGGED, SpamStatus.SPAM] ): client = _get_client() client.submit_ham( user_ip=self.spam_data['headers']['Remote-Addr'], user_agent=self.spam_data['headers'].get('User-Agent'), referrer=self.spam_data['headers'].get('Referer'), comment_content=self.spam_data['content'], comment_author=self.spam_data['author'], comment_author_email=self.spam_data['author_email'], ) logger.info('confirm_ham update sent') self.spam_status = SpamStatus.HAM if save: self.save() def confirm_spam(self, save=False): # not all mixins will implement check spam pre-req, only submit spam when it was incorrectly flagged if ( settings.SPAM_CHECK_ENABLED and self.spam_data and self.spam_status in [SpamStatus.UNKNOWN, SpamStatus.HAM] ): client = _get_client() client.submit_spam( user_ip=self.spam_data['headers']['Remote-Addr'], user_agent=self.spam_data['headers'].get('User-Agent'), referrer=self.spam_data['headers'].get('Referer'), comment_content=self.spam_data['content'], comment_author=self.spam_data['author'], comment_author_email=self.spam_data['author_email'], ) logger.info('confirm_spam update sent') self.spam_status = SpamStatus.SPAM if save: self.save() @abc.abstractmethod def check_spam(self, user, saved_fields, request_headers, save=False): """Must return is_spam""" pass def do_check_spam(self, author, author_email, content, request_headers, update=True): if self.spam_status == SpamStatus.HAM: return False if self.is_spammy: return True client = _get_client() remote_addr = request_headers['Remote-Addr'] user_agent = request_headers.get('User-Agent') referer = request_headers.get('Referer') try: is_spam, pro_tip = client.check_comment( user_ip=remote_addr, user_agent=user_agent, referrer=referer, comment_content=content, comment_author=author, comment_author_email=author_email ) except akismet.AkismetClientError: logger.exception('Error performing SPAM check') return False if update: self.spam_pro_tip = pro_tip self.spam_data['headers'] = { 'Remote-Addr': remote_addr, 'User-Agent': user_agent, 'Referer': referer, } self.spam_data['content'] = content self.spam_data['author'] = author self.spam_data['author_email'] = author_email if is_spam: self.flag_spam() return is_spam
"""Tests for osf.utils.manager.IncludeQueryset""" import pytest from framework.auth import Auth from osf.models import Node from osf_tests.factories import ProjectFactory, NodeFactory, UserFactory pytestmark = pytest.mark.django_db @pytest.fixture() def create_n_nodes(): def _create_n_nodes(n, roots=True): return [ ProjectFactory() if roots else NodeFactory() for _ in range(n) ] return _create_n_nodes class TestIncludeQuerySet: @pytest.mark.django_assert_num_queries def test_include_guids(self, create_n_nodes, django_assert_num_queries): create_n_nodes(3) # Confirm guids included automagically with django_assert_num_queries(1): for node in Node.objects.all(): assert node._id is not None with django_assert_num_queries(1): for node in Node.objects.include('guids').all(): assert node._id is not None @pytest.mark.django_assert_num_queries def test_include_guids_filter(self, create_n_nodes, django_assert_num_queries): nodes = create_n_nodes(3) nids = [e.id for e in nodes[:-1]] with django_assert_num_queries(1): for node in Node.objects.include('guids').filter(id__in=nids): assert node._id is not None @pytest.mark.django_assert_num_queries def test_include_root_guids(self, create_n_nodes, django_assert_num_queries): nodes = create_n_nodes(3, roots=False) queryset = Node.objects.filter(id__in=[e.id for e in nodes]).include('root__guids') with django_assert_num_queries(1): for node in queryset: assert node.root._id is not None @pytest.mark.django_assert_num_queries def test_include_contributor_user_guids(self, create_n_nodes, django_assert_num_queries): nodes = create_n_nodes(3) for node in nodes: for _ in range(3): contrib = UserFactory() node.add_contributor(contrib, auth=Auth(node.creator), save=True) nodes = Node.objects.include('contributor__user__guids').all() for node in nodes: with django_assert_num_queries(0): for contributor in node.contributor_set.all(): assert contributor.user._id is not None
mattclark/osf.io
osf_tests/test_include_queryset.py
osf/models/spam.py
from warnings import catch_warnings import numpy as np from pandas.core.dtypes import generic as gt import pandas as pd import pandas._testing as tm class TestABCClasses: tuples = [[1, 2, 2], ["red", "blue", "red"]] multi_index = pd.MultiIndex.from_arrays(tuples, names=("number", "color")) datetime_index = pd.to_datetime(["2000/1/1", "2010/1/1"]) timedelta_index = pd.to_timedelta(np.arange(5), unit="s") period_index = pd.period_range("2000/1/1", "2010/1/1/", freq="M") categorical = pd.Categorical([1, 2, 3], categories=[2, 3, 1]) categorical_df = pd.DataFrame({"values": [1, 2, 3]}, index=categorical) df = pd.DataFrame({"names": ["a", "b", "c"]}, index=multi_index) sparse_array = pd.arrays.SparseArray(np.random.randn(10)) datetime_array = pd.core.arrays.DatetimeArray(datetime_index) timedelta_array = pd.core.arrays.TimedeltaArray(timedelta_index) def test_abc_types(self): assert isinstance(pd.Index(["a", "b", "c"]), gt.ABCIndex) assert isinstance(pd.Int64Index([1, 2, 3]), gt.ABCInt64Index) assert isinstance(pd.UInt64Index([1, 2, 3]), gt.ABCUInt64Index) assert isinstance(pd.Float64Index([1, 2, 3]), gt.ABCFloat64Index) assert isinstance(self.multi_index, gt.ABCMultiIndex) assert isinstance(self.datetime_index, gt.ABCDatetimeIndex) assert isinstance(self.timedelta_index, gt.ABCTimedeltaIndex) assert isinstance(self.period_index, gt.ABCPeriodIndex) assert isinstance(self.categorical_df.index, gt.ABCCategoricalIndex) assert isinstance(pd.Index(["a", "b", "c"]), gt.ABCIndexClass) assert isinstance(pd.Int64Index([1, 2, 3]), gt.ABCIndexClass) assert isinstance(pd.Series([1, 2, 3]), gt.ABCSeries) assert isinstance(self.df, gt.ABCDataFrame) assert isinstance(self.sparse_array, gt.ABCExtensionArray) assert isinstance(self.categorical, gt.ABCCategorical) assert isinstance(self.datetime_array, gt.ABCDatetimeArray) assert not isinstance(self.datetime_index, gt.ABCDatetimeArray) assert isinstance(self.timedelta_array, gt.ABCTimedeltaArray) assert not isinstance(self.timedelta_index, gt.ABCTimedeltaArray) def test_setattr_warnings(): # GH7175 - GOTCHA: You can't use dot notation to add a column... d = { "one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]), "two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]), } df = pd.DataFrame(d) with catch_warnings(record=True) as w: # successfully add new column # this should not raise a warning df["three"] = df.two + 1 assert len(w) == 0 assert df.three.sum() > df.two.sum() with catch_warnings(record=True) as w: # successfully modify column in place # this should not raise a warning df.one += 1 assert len(w) == 0 assert df.one.iloc[0] == 2 with catch_warnings(record=True) as w: # successfully add an attribute to a series # this should not raise a warning df.two.not_an_index = [1, 2] assert len(w) == 0 with tm.assert_produces_warning(UserWarning): # warn when setting column to nonexistent name df.four = df.two + 2 assert df.four.sum() > df.two.sum()
""" Tests the 'read_fwf' function in parsers.py. This test suite is independent of the others because the engine is set to 'python-fwf' internally. """ from datetime import datetime from io import BytesIO, StringIO import numpy as np import pytest import pandas as pd from pandas import DataFrame, DatetimeIndex import pandas._testing as tm from pandas.io.parsers import EmptyDataError, read_csv, read_fwf def test_basic(): data = """\ A B C D 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ result = read_fwf(StringIO(data)) expected = DataFrame( [ [201158, 360.242940, 149.910199, 11950.7], [201159, 444.953632, 166.985655, 11788.4], [201160, 364.136849, 183.628767, 11806.2], [201161, 413.836124, 184.375703, 11916.8], [201162, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D"], ) tm.assert_frame_equal(result, expected) def test_colspecs(): data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] result = read_fwf(StringIO(data), colspecs=colspecs) expected = DataFrame( [ [2011, 58, 360.242940, 149.910199, 11950.7], [2011, 59, 444.953632, 166.985655, 11788.4], [2011, 60, 364.136849, 183.628767, 11806.2], [2011, 61, 413.836124, 184.375703, 11916.8], [2011, 62, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D", "E"], ) tm.assert_frame_equal(result, expected) def test_widths(): data = """\ A B C D E 2011 58 360.242940 149.910199 11950.7 2011 59 444.953632 166.985655 11788.4 2011 60 364.136849 183.628767 11806.2 2011 61 413.836124 184.375703 11916.8 2011 62 502.953953 173.237159 12468.3 """ result = read_fwf(StringIO(data), widths=[5, 5, 13, 13, 7]) expected = DataFrame( [ [2011, 58, 360.242940, 149.910199, 11950.7], [2011, 59, 444.953632, 166.985655, 11788.4], [2011, 60, 364.136849, 183.628767, 11806.2], [2011, 61, 413.836124, 184.375703, 11916.8], [2011, 62, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D", "E"], ) tm.assert_frame_equal(result, expected) def test_non_space_filler(): # From Thomas Kluyver: # # Apparently, some non-space filler characters can be seen, this is # supported by specifying the 'delimiter' character: # # http://publib.boulder.ibm.com/infocenter/dmndhelp/v6r1mx/index.jsp?topic=/com.ibm.wbit.612.help.config.doc/topics/rfixwidth.html data = """\ A~~~~B~~~~C~~~~~~~~~~~~D~~~~~~~~~~~~E 201158~~~~360.242940~~~149.910199~~~11950.7 201159~~~~444.953632~~~166.985655~~~11788.4 201160~~~~364.136849~~~183.628767~~~11806.2 201161~~~~413.836124~~~184.375703~~~11916.8 201162~~~~502.953953~~~173.237159~~~12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] result = read_fwf(StringIO(data), colspecs=colspecs, delimiter="~") expected = DataFrame( [ [2011, 58, 360.242940, 149.910199, 11950.7], [2011, 59, 444.953632, 166.985655, 11788.4], [2011, 60, 364.136849, 183.628767, 11806.2], [2011, 61, 413.836124, 184.375703, 11916.8], [2011, 62, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D", "E"], ) tm.assert_frame_equal(result, expected) def test_over_specified(): data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] with pytest.raises(ValueError, match="must specify only one of"): read_fwf(StringIO(data), colspecs=colspecs, widths=[6, 10, 10, 7]) def test_under_specified(): data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ with pytest.raises(ValueError, match="Must specify either"): read_fwf(StringIO(data), colspecs=None, widths=None) def test_read_csv_compat(): csv_data = """\ A,B,C,D,E 2011,58,360.242940,149.910199,11950.7 2011,59,444.953632,166.985655,11788.4 2011,60,364.136849,183.628767,11806.2 2011,61,413.836124,184.375703,11916.8 2011,62,502.953953,173.237159,12468.3 """ expected = read_csv(StringIO(csv_data), engine="python") fwf_data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] result = read_fwf(StringIO(fwf_data), colspecs=colspecs) tm.assert_frame_equal(result, expected) def test_bytes_io_input(): result = read_fwf( BytesIO("שלום\nשלום".encode("utf8")), widths=[2, 2], encoding="utf8" ) expected = DataFrame([["של", "ום"]], columns=["של", "ום"]) tm.assert_frame_equal(result, expected) def test_fwf_colspecs_is_list_or_tuple(): data = """index,A,B,C,D foo,2,3,4,5 bar,7,8,9,10 baz,12,13,14,15 qux,12,13,14,15 foo2,12,13,14,15 bar2,12,13,14,15 """ msg = "column specifications must be a list or tuple.+" with pytest.raises(TypeError, match=msg): read_fwf(StringIO(data), colspecs={"a": 1}, delimiter=",") def test_fwf_colspecs_is_list_or_tuple_of_two_element_tuples(): data = """index,A,B,C,D foo,2,3,4,5 bar,7,8,9,10 baz,12,13,14,15 qux,12,13,14,15 foo2,12,13,14,15 bar2,12,13,14,15 """ msg = "Each column specification must be.+" with pytest.raises(TypeError, match=msg): read_fwf(StringIO(data), [("a", 1)]) @pytest.mark.parametrize( "colspecs,exp_data", [ ([(0, 3), (3, None)], [[123, 456], [456, 789]]), ([(None, 3), (3, 6)], [[123, 456], [456, 789]]), ([(0, None), (3, None)], [[123456, 456], [456789, 789]]), ([(None, None), (3, 6)], [[123456, 456], [456789, 789]]), ], ) def test_fwf_colspecs_none(colspecs, exp_data): # see gh-7079 data = """\ 123456 456789 """ expected = DataFrame(exp_data) result = read_fwf(StringIO(data), colspecs=colspecs, header=None) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "infer_nrows,exp_data", [ # infer_nrows --> colspec == [(2, 3), (5, 6)] (1, [[1, 2], [3, 8]]), # infer_nrows > number of rows (10, [[1, 2], [123, 98]]), ], ) def test_fwf_colspecs_infer_nrows(infer_nrows, exp_data): # see gh-15138 data = """\ 1 2 123 98 """ expected = DataFrame(exp_data) result = read_fwf(StringIO(data), infer_nrows=infer_nrows, header=None) tm.assert_frame_equal(result, expected) def test_fwf_regression(): # see gh-3594 # # Turns out "T060" is parsable as a datetime slice! tz_list = [1, 10, 20, 30, 60, 80, 100] widths = [16] + [8] * len(tz_list) names = ["SST"] + [f"T{z:03d}" for z in tz_list[1:]] data = """ 2009164202000 9.5403 9.4105 8.6571 7.8372 6.0612 5.8843 5.5192 2009164203000 9.5435 9.2010 8.6167 7.8176 6.0804 5.8728 5.4869 2009164204000 9.5873 9.1326 8.4694 7.5889 6.0422 5.8526 5.4657 2009164205000 9.5810 9.0896 8.4009 7.4652 6.0322 5.8189 5.4379 2009164210000 9.6034 9.0897 8.3822 7.4905 6.0908 5.7904 5.4039 """ result = read_fwf( StringIO(data), index_col=0, header=None, names=names, widths=widths, parse_dates=True, date_parser=lambda s: datetime.strptime(s, "%Y%j%H%M%S"), ) expected = DataFrame( [ [9.5403, 9.4105, 8.6571, 7.8372, 6.0612, 5.8843, 5.5192], [9.5435, 9.2010, 8.6167, 7.8176, 6.0804, 5.8728, 5.4869], [9.5873, 9.1326, 8.4694, 7.5889, 6.0422, 5.8526, 5.4657], [9.5810, 9.0896, 8.4009, 7.4652, 6.0322, 5.8189, 5.4379], [9.6034, 9.0897, 8.3822, 7.4905, 6.0908, 5.7904, 5.4039], ], index=DatetimeIndex( [ "2009-06-13 20:20:00", "2009-06-13 20:30:00", "2009-06-13 20:40:00", "2009-06-13 20:50:00", "2009-06-13 21:00:00", ] ), columns=["SST", "T010", "T020", "T030", "T060", "T080", "T100"], ) tm.assert_frame_equal(result, expected) def test_fwf_for_uint8(): data = """1421302965.213420 PRI=3 PGN=0xef00 DST=0x17 SRC=0x28 04 154 00 00 00 00 00 127 1421302964.226776 PRI=6 PGN=0xf002 SRC=0x47 243 00 00 255 247 00 00 71""" # noqa df = read_fwf( StringIO(data), colspecs=[(0, 17), (25, 26), (33, 37), (49, 51), (58, 62), (63, 1000)], names=["time", "pri", "pgn", "dst", "src", "data"], converters={ "pgn": lambda x: int(x, 16), "src": lambda x: int(x, 16), "dst": lambda x: int(x, 16), "data": lambda x: len(x.split(" ")), }, ) expected = DataFrame( [ [1421302965.213420, 3, 61184, 23, 40, 8], [1421302964.226776, 6, 61442, None, 71, 8], ], columns=["time", "pri", "pgn", "dst", "src", "data"], ) expected["dst"] = expected["dst"].astype(object) tm.assert_frame_equal(df, expected) @pytest.mark.parametrize("comment", ["#", "~", "!"]) def test_fwf_comment(comment): data = """\ 1 2. 4 #hello world 5 NaN 10.0 """ data = data.replace("#", comment) colspecs = [(0, 3), (4, 9), (9, 25)] expected = DataFrame([[1, 2.0, 4], [5, np.nan, 10.0]]) result = read_fwf(StringIO(data), colspecs=colspecs, header=None, comment=comment) tm.assert_almost_equal(result, expected) @pytest.mark.parametrize("thousands", [",", "#", "~"]) def test_fwf_thousands(thousands): data = """\ 1 2,334.0 5 10 13 10. """ data = data.replace(",", thousands) colspecs = [(0, 3), (3, 11), (12, 16)] expected = DataFrame([[1, 2334.0, 5], [10, 13, 10.0]]) result = read_fwf( StringIO(data), header=None, colspecs=colspecs, thousands=thousands ) tm.assert_almost_equal(result, expected) @pytest.mark.parametrize("header", [True, False]) def test_bool_header_arg(header): # see gh-6114 data = """\ MyColumn a b a b""" msg = "Passing a bool to header is invalid" with pytest.raises(TypeError, match=msg): read_fwf(StringIO(data), header=header) def test_full_file(): # File with all values. test = """index A B C 2000-01-03T00:00:00 0.980268513777 3 foo 2000-01-04T00:00:00 1.04791624281 -4 bar 2000-01-05T00:00:00 0.498580885705 73 baz 2000-01-06T00:00:00 1.12020151869 1 foo 2000-01-07T00:00:00 0.487094399463 0 bar 2000-01-10T00:00:00 0.836648671666 2 baz 2000-01-11T00:00:00 0.157160753327 34 foo""" colspecs = ((0, 19), (21, 35), (38, 40), (42, 45)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_full_file_with_missing(): # File with missing values. test = """index A B C 2000-01-03T00:00:00 0.980268513777 3 foo 2000-01-04T00:00:00 1.04791624281 -4 bar 0.498580885705 73 baz 2000-01-06T00:00:00 1.12020151869 1 foo 2000-01-07T00:00:00 0 bar 2000-01-10T00:00:00 0.836648671666 2 baz 34""" colspecs = ((0, 19), (21, 35), (38, 40), (42, 45)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_full_file_with_spaces(): # File with spaces in columns. test = """ Account Name Balance CreditLimit AccountCreated 101 Keanu Reeves 9315.45 10000.00 1/17/1998 312 Gerard Butler 90.00 1000.00 8/6/2003 868 Jennifer Love Hewitt 0 17000.00 5/25/1985 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 317 Bill Murray 789.65 5000.00 2/5/2007 """.strip( "\r\n" ) colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_full_file_with_spaces_and_missing(): # File with spaces and missing values in columns. test = """ Account Name Balance CreditLimit AccountCreated 101 10000.00 1/17/1998 312 Gerard Butler 90.00 1000.00 8/6/2003 868 5/25/1985 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 317 Bill Murray 789.65 """.strip( "\r\n" ) colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_messed_up_data(): # Completely messed up file. test = """ Account Name Balance Credit Limit Account Created 101 10000.00 1/17/1998 312 Gerard Butler 90.00 1000.00 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 317 Bill Murray 789.65 """.strip( "\r\n" ) colspecs = ((2, 10), (15, 33), (37, 45), (49, 61), (64, 79)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_multiple_delimiters(): test = r""" col1~~~~~col2 col3++++++++++++++++++col4 ~~22.....11.0+++foo~~~~~~~~~~Keanu Reeves 33+++122.33\\\bar.........Gerard Butler ++44~~~~12.01 baz~~Jennifer Love Hewitt ~~55 11+++foo++++Jada Pinkett-Smith ..66++++++.03~~~bar Bill Murray """.strip( "\r\n" ) delimiter = " +~.\\" colspecs = ((0, 4), (7, 13), (15, 19), (21, 41)) expected = read_fwf(StringIO(test), colspecs=colspecs, delimiter=delimiter) result = read_fwf(StringIO(test), delimiter=delimiter) tm.assert_frame_equal(result, expected) def test_variable_width_unicode(): data = """ שלום שלום ום שלל של ום """.strip( "\r\n" ) encoding = "utf8" kwargs = dict(header=None, encoding=encoding) expected = read_fwf( BytesIO(data.encode(encoding)), colspecs=[(0, 4), (5, 9)], **kwargs ) result = read_fwf(BytesIO(data.encode(encoding)), **kwargs) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", [dict(), {"a": "float64", "b": str, "c": "int32"}]) def test_dtype(dtype): data = """ a b c 1 2 3.2 3 4 5.2 """ colspecs = [(0, 5), (5, 10), (10, None)] result = read_fwf(StringIO(data), colspecs=colspecs, dtype=dtype) expected = pd.DataFrame( {"a": [1, 3], "b": [2, 4], "c": [3.2, 5.2]}, columns=["a", "b", "c"] ) for col, dt in dtype.items(): expected[col] = expected[col].astype(dt) tm.assert_frame_equal(result, expected) def test_skiprows_inference(): # see gh-11256 data = """ Text contained in the file header DataCol1 DataCol2 0.0 1.0 101.6 956.1 """.strip() skiprows = 2 expected = read_csv(StringIO(data), skiprows=skiprows, delim_whitespace=True) result = read_fwf(StringIO(data), skiprows=skiprows) tm.assert_frame_equal(result, expected) def test_skiprows_by_index_inference(): data = """ To be skipped Not To Be Skipped Once more to be skipped 123 34 8 123 456 78 9 456 """.strip() skiprows = [0, 2] expected = read_csv(StringIO(data), skiprows=skiprows, delim_whitespace=True) result = read_fwf(StringIO(data), skiprows=skiprows) tm.assert_frame_equal(result, expected) def test_skiprows_inference_empty(): data = """ AA BBB C 12 345 6 78 901 2 """.strip() msg = "No rows from which to infer column width" with pytest.raises(EmptyDataError, match=msg): read_fwf(StringIO(data), skiprows=3) def test_whitespace_preservation(): # see gh-16772 header = None csv_data = """ a ,bbb cc,dd """ fwf_data = """ a bbb ccdd """ result = read_fwf( StringIO(fwf_data), widths=[3, 3], header=header, skiprows=[0], delimiter="\n\t" ) expected = read_csv(StringIO(csv_data), header=header) tm.assert_frame_equal(result, expected) def test_default_delimiter(): header = None csv_data = """ a,bbb cc,dd""" fwf_data = """ a \tbbb cc\tdd """ result = read_fwf(StringIO(fwf_data), widths=[3, 3], header=header, skiprows=[0]) expected = read_csv(StringIO(csv_data), header=header) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("infer", [True, False, None]) def test_fwf_compression(compression_only, infer): data = """1111111111 2222222222 3333333333""".strip() compression = compression_only extension = "gz" if compression == "gzip" else compression kwargs = dict(widths=[5, 5], names=["one", "two"]) expected = read_fwf(StringIO(data), **kwargs) data = bytes(data, encoding="utf-8") with tm.ensure_clean(filename="tmp." + extension) as path: tm.write_to_compressed(compression, path, data) if infer is not None: kwargs["compression"] = "infer" if infer else compression result = read_fwf(path, **kwargs) tm.assert_frame_equal(result, expected)
TomAugspurger/pandas
pandas/tests/io/parser/test_read_fwf.py
pandas/tests/dtypes/test_generic.py
import pandas as pd import pandas._testing as tm class TestUnaryOps: def test_invert(self): a = pd.array([True, False, None], dtype="boolean") expected = pd.array([False, True, None], dtype="boolean") tm.assert_extension_array_equal(~a, expected) expected = pd.Series(expected, index=["a", "b", "c"], name="name") result = ~pd.Series(a, index=["a", "b", "c"], name="name") tm.assert_series_equal(result, expected) df = pd.DataFrame({"A": a, "B": [True, False, False]}, index=["a", "b", "c"]) result = ~df expected = pd.DataFrame( {"A": expected, "B": [False, True, True]}, index=["a", "b", "c"] ) tm.assert_frame_equal(result, expected)
""" Tests the 'read_fwf' function in parsers.py. This test suite is independent of the others because the engine is set to 'python-fwf' internally. """ from datetime import datetime from io import BytesIO, StringIO import numpy as np import pytest import pandas as pd from pandas import DataFrame, DatetimeIndex import pandas._testing as tm from pandas.io.parsers import EmptyDataError, read_csv, read_fwf def test_basic(): data = """\ A B C D 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ result = read_fwf(StringIO(data)) expected = DataFrame( [ [201158, 360.242940, 149.910199, 11950.7], [201159, 444.953632, 166.985655, 11788.4], [201160, 364.136849, 183.628767, 11806.2], [201161, 413.836124, 184.375703, 11916.8], [201162, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D"], ) tm.assert_frame_equal(result, expected) def test_colspecs(): data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] result = read_fwf(StringIO(data), colspecs=colspecs) expected = DataFrame( [ [2011, 58, 360.242940, 149.910199, 11950.7], [2011, 59, 444.953632, 166.985655, 11788.4], [2011, 60, 364.136849, 183.628767, 11806.2], [2011, 61, 413.836124, 184.375703, 11916.8], [2011, 62, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D", "E"], ) tm.assert_frame_equal(result, expected) def test_widths(): data = """\ A B C D E 2011 58 360.242940 149.910199 11950.7 2011 59 444.953632 166.985655 11788.4 2011 60 364.136849 183.628767 11806.2 2011 61 413.836124 184.375703 11916.8 2011 62 502.953953 173.237159 12468.3 """ result = read_fwf(StringIO(data), widths=[5, 5, 13, 13, 7]) expected = DataFrame( [ [2011, 58, 360.242940, 149.910199, 11950.7], [2011, 59, 444.953632, 166.985655, 11788.4], [2011, 60, 364.136849, 183.628767, 11806.2], [2011, 61, 413.836124, 184.375703, 11916.8], [2011, 62, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D", "E"], ) tm.assert_frame_equal(result, expected) def test_non_space_filler(): # From Thomas Kluyver: # # Apparently, some non-space filler characters can be seen, this is # supported by specifying the 'delimiter' character: # # http://publib.boulder.ibm.com/infocenter/dmndhelp/v6r1mx/index.jsp?topic=/com.ibm.wbit.612.help.config.doc/topics/rfixwidth.html data = """\ A~~~~B~~~~C~~~~~~~~~~~~D~~~~~~~~~~~~E 201158~~~~360.242940~~~149.910199~~~11950.7 201159~~~~444.953632~~~166.985655~~~11788.4 201160~~~~364.136849~~~183.628767~~~11806.2 201161~~~~413.836124~~~184.375703~~~11916.8 201162~~~~502.953953~~~173.237159~~~12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] result = read_fwf(StringIO(data), colspecs=colspecs, delimiter="~") expected = DataFrame( [ [2011, 58, 360.242940, 149.910199, 11950.7], [2011, 59, 444.953632, 166.985655, 11788.4], [2011, 60, 364.136849, 183.628767, 11806.2], [2011, 61, 413.836124, 184.375703, 11916.8], [2011, 62, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D", "E"], ) tm.assert_frame_equal(result, expected) def test_over_specified(): data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] with pytest.raises(ValueError, match="must specify only one of"): read_fwf(StringIO(data), colspecs=colspecs, widths=[6, 10, 10, 7]) def test_under_specified(): data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ with pytest.raises(ValueError, match="Must specify either"): read_fwf(StringIO(data), colspecs=None, widths=None) def test_read_csv_compat(): csv_data = """\ A,B,C,D,E 2011,58,360.242940,149.910199,11950.7 2011,59,444.953632,166.985655,11788.4 2011,60,364.136849,183.628767,11806.2 2011,61,413.836124,184.375703,11916.8 2011,62,502.953953,173.237159,12468.3 """ expected = read_csv(StringIO(csv_data), engine="python") fwf_data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] result = read_fwf(StringIO(fwf_data), colspecs=colspecs) tm.assert_frame_equal(result, expected) def test_bytes_io_input(): result = read_fwf( BytesIO("שלום\nשלום".encode("utf8")), widths=[2, 2], encoding="utf8" ) expected = DataFrame([["של", "ום"]], columns=["של", "ום"]) tm.assert_frame_equal(result, expected) def test_fwf_colspecs_is_list_or_tuple(): data = """index,A,B,C,D foo,2,3,4,5 bar,7,8,9,10 baz,12,13,14,15 qux,12,13,14,15 foo2,12,13,14,15 bar2,12,13,14,15 """ msg = "column specifications must be a list or tuple.+" with pytest.raises(TypeError, match=msg): read_fwf(StringIO(data), colspecs={"a": 1}, delimiter=",") def test_fwf_colspecs_is_list_or_tuple_of_two_element_tuples(): data = """index,A,B,C,D foo,2,3,4,5 bar,7,8,9,10 baz,12,13,14,15 qux,12,13,14,15 foo2,12,13,14,15 bar2,12,13,14,15 """ msg = "Each column specification must be.+" with pytest.raises(TypeError, match=msg): read_fwf(StringIO(data), [("a", 1)]) @pytest.mark.parametrize( "colspecs,exp_data", [ ([(0, 3), (3, None)], [[123, 456], [456, 789]]), ([(None, 3), (3, 6)], [[123, 456], [456, 789]]), ([(0, None), (3, None)], [[123456, 456], [456789, 789]]), ([(None, None), (3, 6)], [[123456, 456], [456789, 789]]), ], ) def test_fwf_colspecs_none(colspecs, exp_data): # see gh-7079 data = """\ 123456 456789 """ expected = DataFrame(exp_data) result = read_fwf(StringIO(data), colspecs=colspecs, header=None) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "infer_nrows,exp_data", [ # infer_nrows --> colspec == [(2, 3), (5, 6)] (1, [[1, 2], [3, 8]]), # infer_nrows > number of rows (10, [[1, 2], [123, 98]]), ], ) def test_fwf_colspecs_infer_nrows(infer_nrows, exp_data): # see gh-15138 data = """\ 1 2 123 98 """ expected = DataFrame(exp_data) result = read_fwf(StringIO(data), infer_nrows=infer_nrows, header=None) tm.assert_frame_equal(result, expected) def test_fwf_regression(): # see gh-3594 # # Turns out "T060" is parsable as a datetime slice! tz_list = [1, 10, 20, 30, 60, 80, 100] widths = [16] + [8] * len(tz_list) names = ["SST"] + [f"T{z:03d}" for z in tz_list[1:]] data = """ 2009164202000 9.5403 9.4105 8.6571 7.8372 6.0612 5.8843 5.5192 2009164203000 9.5435 9.2010 8.6167 7.8176 6.0804 5.8728 5.4869 2009164204000 9.5873 9.1326 8.4694 7.5889 6.0422 5.8526 5.4657 2009164205000 9.5810 9.0896 8.4009 7.4652 6.0322 5.8189 5.4379 2009164210000 9.6034 9.0897 8.3822 7.4905 6.0908 5.7904 5.4039 """ result = read_fwf( StringIO(data), index_col=0, header=None, names=names, widths=widths, parse_dates=True, date_parser=lambda s: datetime.strptime(s, "%Y%j%H%M%S"), ) expected = DataFrame( [ [9.5403, 9.4105, 8.6571, 7.8372, 6.0612, 5.8843, 5.5192], [9.5435, 9.2010, 8.6167, 7.8176, 6.0804, 5.8728, 5.4869], [9.5873, 9.1326, 8.4694, 7.5889, 6.0422, 5.8526, 5.4657], [9.5810, 9.0896, 8.4009, 7.4652, 6.0322, 5.8189, 5.4379], [9.6034, 9.0897, 8.3822, 7.4905, 6.0908, 5.7904, 5.4039], ], index=DatetimeIndex( [ "2009-06-13 20:20:00", "2009-06-13 20:30:00", "2009-06-13 20:40:00", "2009-06-13 20:50:00", "2009-06-13 21:00:00", ] ), columns=["SST", "T010", "T020", "T030", "T060", "T080", "T100"], ) tm.assert_frame_equal(result, expected) def test_fwf_for_uint8(): data = """1421302965.213420 PRI=3 PGN=0xef00 DST=0x17 SRC=0x28 04 154 00 00 00 00 00 127 1421302964.226776 PRI=6 PGN=0xf002 SRC=0x47 243 00 00 255 247 00 00 71""" # noqa df = read_fwf( StringIO(data), colspecs=[(0, 17), (25, 26), (33, 37), (49, 51), (58, 62), (63, 1000)], names=["time", "pri", "pgn", "dst", "src", "data"], converters={ "pgn": lambda x: int(x, 16), "src": lambda x: int(x, 16), "dst": lambda x: int(x, 16), "data": lambda x: len(x.split(" ")), }, ) expected = DataFrame( [ [1421302965.213420, 3, 61184, 23, 40, 8], [1421302964.226776, 6, 61442, None, 71, 8], ], columns=["time", "pri", "pgn", "dst", "src", "data"], ) expected["dst"] = expected["dst"].astype(object) tm.assert_frame_equal(df, expected) @pytest.mark.parametrize("comment", ["#", "~", "!"]) def test_fwf_comment(comment): data = """\ 1 2. 4 #hello world 5 NaN 10.0 """ data = data.replace("#", comment) colspecs = [(0, 3), (4, 9), (9, 25)] expected = DataFrame([[1, 2.0, 4], [5, np.nan, 10.0]]) result = read_fwf(StringIO(data), colspecs=colspecs, header=None, comment=comment) tm.assert_almost_equal(result, expected) @pytest.mark.parametrize("thousands", [",", "#", "~"]) def test_fwf_thousands(thousands): data = """\ 1 2,334.0 5 10 13 10. """ data = data.replace(",", thousands) colspecs = [(0, 3), (3, 11), (12, 16)] expected = DataFrame([[1, 2334.0, 5], [10, 13, 10.0]]) result = read_fwf( StringIO(data), header=None, colspecs=colspecs, thousands=thousands ) tm.assert_almost_equal(result, expected) @pytest.mark.parametrize("header", [True, False]) def test_bool_header_arg(header): # see gh-6114 data = """\ MyColumn a b a b""" msg = "Passing a bool to header is invalid" with pytest.raises(TypeError, match=msg): read_fwf(StringIO(data), header=header) def test_full_file(): # File with all values. test = """index A B C 2000-01-03T00:00:00 0.980268513777 3 foo 2000-01-04T00:00:00 1.04791624281 -4 bar 2000-01-05T00:00:00 0.498580885705 73 baz 2000-01-06T00:00:00 1.12020151869 1 foo 2000-01-07T00:00:00 0.487094399463 0 bar 2000-01-10T00:00:00 0.836648671666 2 baz 2000-01-11T00:00:00 0.157160753327 34 foo""" colspecs = ((0, 19), (21, 35), (38, 40), (42, 45)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_full_file_with_missing(): # File with missing values. test = """index A B C 2000-01-03T00:00:00 0.980268513777 3 foo 2000-01-04T00:00:00 1.04791624281 -4 bar 0.498580885705 73 baz 2000-01-06T00:00:00 1.12020151869 1 foo 2000-01-07T00:00:00 0 bar 2000-01-10T00:00:00 0.836648671666 2 baz 34""" colspecs = ((0, 19), (21, 35), (38, 40), (42, 45)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_full_file_with_spaces(): # File with spaces in columns. test = """ Account Name Balance CreditLimit AccountCreated 101 Keanu Reeves 9315.45 10000.00 1/17/1998 312 Gerard Butler 90.00 1000.00 8/6/2003 868 Jennifer Love Hewitt 0 17000.00 5/25/1985 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 317 Bill Murray 789.65 5000.00 2/5/2007 """.strip( "\r\n" ) colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_full_file_with_spaces_and_missing(): # File with spaces and missing values in columns. test = """ Account Name Balance CreditLimit AccountCreated 101 10000.00 1/17/1998 312 Gerard Butler 90.00 1000.00 8/6/2003 868 5/25/1985 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 317 Bill Murray 789.65 """.strip( "\r\n" ) colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_messed_up_data(): # Completely messed up file. test = """ Account Name Balance Credit Limit Account Created 101 10000.00 1/17/1998 312 Gerard Butler 90.00 1000.00 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 317 Bill Murray 789.65 """.strip( "\r\n" ) colspecs = ((2, 10), (15, 33), (37, 45), (49, 61), (64, 79)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_multiple_delimiters(): test = r""" col1~~~~~col2 col3++++++++++++++++++col4 ~~22.....11.0+++foo~~~~~~~~~~Keanu Reeves 33+++122.33\\\bar.........Gerard Butler ++44~~~~12.01 baz~~Jennifer Love Hewitt ~~55 11+++foo++++Jada Pinkett-Smith ..66++++++.03~~~bar Bill Murray """.strip( "\r\n" ) delimiter = " +~.\\" colspecs = ((0, 4), (7, 13), (15, 19), (21, 41)) expected = read_fwf(StringIO(test), colspecs=colspecs, delimiter=delimiter) result = read_fwf(StringIO(test), delimiter=delimiter) tm.assert_frame_equal(result, expected) def test_variable_width_unicode(): data = """ שלום שלום ום שלל של ום """.strip( "\r\n" ) encoding = "utf8" kwargs = dict(header=None, encoding=encoding) expected = read_fwf( BytesIO(data.encode(encoding)), colspecs=[(0, 4), (5, 9)], **kwargs ) result = read_fwf(BytesIO(data.encode(encoding)), **kwargs) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", [dict(), {"a": "float64", "b": str, "c": "int32"}]) def test_dtype(dtype): data = """ a b c 1 2 3.2 3 4 5.2 """ colspecs = [(0, 5), (5, 10), (10, None)] result = read_fwf(StringIO(data), colspecs=colspecs, dtype=dtype) expected = pd.DataFrame( {"a": [1, 3], "b": [2, 4], "c": [3.2, 5.2]}, columns=["a", "b", "c"] ) for col, dt in dtype.items(): expected[col] = expected[col].astype(dt) tm.assert_frame_equal(result, expected) def test_skiprows_inference(): # see gh-11256 data = """ Text contained in the file header DataCol1 DataCol2 0.0 1.0 101.6 956.1 """.strip() skiprows = 2 expected = read_csv(StringIO(data), skiprows=skiprows, delim_whitespace=True) result = read_fwf(StringIO(data), skiprows=skiprows) tm.assert_frame_equal(result, expected) def test_skiprows_by_index_inference(): data = """ To be skipped Not To Be Skipped Once more to be skipped 123 34 8 123 456 78 9 456 """.strip() skiprows = [0, 2] expected = read_csv(StringIO(data), skiprows=skiprows, delim_whitespace=True) result = read_fwf(StringIO(data), skiprows=skiprows) tm.assert_frame_equal(result, expected) def test_skiprows_inference_empty(): data = """ AA BBB C 12 345 6 78 901 2 """.strip() msg = "No rows from which to infer column width" with pytest.raises(EmptyDataError, match=msg): read_fwf(StringIO(data), skiprows=3) def test_whitespace_preservation(): # see gh-16772 header = None csv_data = """ a ,bbb cc,dd """ fwf_data = """ a bbb ccdd """ result = read_fwf( StringIO(fwf_data), widths=[3, 3], header=header, skiprows=[0], delimiter="\n\t" ) expected = read_csv(StringIO(csv_data), header=header) tm.assert_frame_equal(result, expected) def test_default_delimiter(): header = None csv_data = """ a,bbb cc,dd""" fwf_data = """ a \tbbb cc\tdd """ result = read_fwf(StringIO(fwf_data), widths=[3, 3], header=header, skiprows=[0]) expected = read_csv(StringIO(csv_data), header=header) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("infer", [True, False, None]) def test_fwf_compression(compression_only, infer): data = """1111111111 2222222222 3333333333""".strip() compression = compression_only extension = "gz" if compression == "gzip" else compression kwargs = dict(widths=[5, 5], names=["one", "two"]) expected = read_fwf(StringIO(data), **kwargs) data = bytes(data, encoding="utf-8") with tm.ensure_clean(filename="tmp." + extension) as path: tm.write_to_compressed(compression, path, data) if infer is not None: kwargs["compression"] = "infer" if infer else compression result = read_fwf(path, **kwargs) tm.assert_frame_equal(result, expected)
TomAugspurger/pandas
pandas/tests/io/parser/test_read_fwf.py
pandas/tests/arrays/boolean/test_ops.py
from contextlib import contextmanager from pandas.plotting._core import _get_plot_backend def table(ax, data, rowLabels=None, colLabels=None, **kwargs): """ Helper function to convert DataFrame and Series to matplotlib.table. Parameters ---------- ax : Matplotlib axes object data : DataFrame or Series Data for table contents. **kwargs Keyword arguments to be passed to matplotlib.table.table. If `rowLabels` or `colLabels` is not specified, data index or column name will be used. Returns ------- matplotlib table object """ plot_backend = _get_plot_backend("matplotlib") return plot_backend.table( ax=ax, data=data, rowLabels=None, colLabels=None, **kwargs ) def register(): """ Register pandas formatters and converters with matplotlib. This function modifies the global ``matplotlib.units.registry`` dictionary. pandas adds custom converters for * pd.Timestamp * pd.Period * np.datetime64 * datetime.datetime * datetime.date * datetime.time See Also -------- deregister_matplotlib_converters : Remove pandas formatters and converters. """ plot_backend = _get_plot_backend("matplotlib") plot_backend.register() def deregister(): """ Remove pandas formatters and converters. Removes the custom converters added by :func:`register`. This attempts to set the state of the registry back to the state before pandas registered its own units. Converters for pandas' own types like Timestamp and Period are removed completely. Converters for types pandas overwrites, like ``datetime.datetime``, are restored to their original value. See Also -------- register_matplotlib_converters : Register pandas formatters and converters with matplotlib. """ plot_backend = _get_plot_backend("matplotlib") plot_backend.deregister() def scatter_matrix( frame, alpha=0.5, figsize=None, ax=None, grid=False, diagonal="hist", marker=".", density_kwds=None, hist_kwds=None, range_padding=0.05, **kwargs, ): """ Draw a matrix of scatter plots. Parameters ---------- frame : DataFrame alpha : float, optional Amount of transparency applied. figsize : (float,float), optional A tuple (width, height) in inches. ax : Matplotlib axis object, optional grid : bool, optional Setting this to True will show the grid. diagonal : {'hist', 'kde'} Pick between 'kde' and 'hist' for either Kernel Density Estimation or Histogram plot in the diagonal. marker : str, optional Matplotlib marker type, default '.'. density_kwds : keywords Keyword arguments to be passed to kernel density estimate plot. hist_kwds : keywords Keyword arguments to be passed to hist function. range_padding : float, default 0.05 Relative extension of axis range in x and y with respect to (x_max - x_min) or (y_max - y_min). **kwargs Keyword arguments to be passed to scatter function. Returns ------- numpy.ndarray A matrix of scatter plots. Examples -------- .. plot:: :context: close-figs >>> df = pd.DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D']) >>> pd.plotting.scatter_matrix(df, alpha=0.2) """ plot_backend = _get_plot_backend("matplotlib") return plot_backend.scatter_matrix( frame=frame, alpha=alpha, figsize=figsize, ax=ax, grid=grid, diagonal=diagonal, marker=marker, density_kwds=density_kwds, hist_kwds=hist_kwds, range_padding=range_padding, **kwargs, ) def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds): """ Plot a multidimensional dataset in 2D. Each Series in the DataFrame is represented as a evenly distributed slice on a circle. Each data point is rendered in the circle according to the value on each Series. Highly correlated `Series` in the `DataFrame` are placed closer on the unit circle. RadViz allow to project a N-dimensional data set into a 2D space where the influence of each dimension can be interpreted as a balance between the influence of all dimensions. More info available at the `original article <https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.135.889>`_ describing RadViz. Parameters ---------- frame : `DataFrame` pandas object holding the data. class_column : str Column name containing the name of the data point category. ax : :class:`matplotlib.axes.Axes`, optional A plot instance to which to add the information. color : list[str] or tuple[str], optional Assign a color to each category. Example: ['blue', 'green']. colormap : str or :class:`matplotlib.colors.Colormap`, default None Colormap to select colors from. If string, load colormap with that name from matplotlib. **kwds Options to pass to matplotlib scatter plotting method. Returns ------- class:`matplotlib.axes.Axes` See Also -------- plotting.andrews_curves : Plot clustering visualization. Examples -------- .. plot:: :context: close-figs >>> df = pd.DataFrame( ... { ... 'SepalLength': [6.5, 7.7, 5.1, 5.8, 7.6, 5.0, 5.4, 4.6, 6.7, 4.6], ... 'SepalWidth': [3.0, 3.8, 3.8, 2.7, 3.0, 2.3, 3.0, 3.2, 3.3, 3.6], ... 'PetalLength': [5.5, 6.7, 1.9, 5.1, 6.6, 3.3, 4.5, 1.4, 5.7, 1.0], ... 'PetalWidth': [1.8, 2.2, 0.4, 1.9, 2.1, 1.0, 1.5, 0.2, 2.1, 0.2], ... 'Category': [ ... 'virginica', ... 'virginica', ... 'setosa', ... 'virginica', ... 'virginica', ... 'versicolor', ... 'versicolor', ... 'setosa', ... 'virginica', ... 'setosa' ... ] ... } ... ) >>> pd.plotting.radviz(df, 'Category') """ plot_backend = _get_plot_backend("matplotlib") return plot_backend.radviz( frame=frame, class_column=class_column, ax=ax, color=color, colormap=colormap, **kwds, ) def andrews_curves( frame, class_column, ax=None, samples=200, color=None, colormap=None, **kwargs ): """ Generate a matplotlib plot of Andrews curves, for visualising clusters of multivariate data. Andrews curves have the functional form: f(t) = x_1/sqrt(2) + x_2 sin(t) + x_3 cos(t) + x_4 sin(2t) + x_5 cos(2t) + ... Where x coefficients correspond to the values of each dimension and t is linearly spaced between -pi and +pi. Each row of frame then corresponds to a single curve. Parameters ---------- frame : DataFrame Data to be plotted, preferably normalized to (0.0, 1.0). class_column : Name of the column containing class names ax : matplotlib axes object, default None samples : Number of points to plot in each curve color : list or tuple, optional Colors to use for the different classes. colormap : str or matplotlib colormap object, default None Colormap to select colors from. If string, load colormap with that name from matplotlib. **kwargs Options to pass to matplotlib plotting method. Returns ------- class:`matplotlip.axis.Axes` Examples -------- .. plot:: :context: close-figs >>> df = pd.read_csv( ... 'https://raw.github.com/pandas-dev/' ... 'pandas/master/pandas/tests/io/data/csv/iris.csv' ... ) >>> pd.plotting.andrews_curves(df, 'Name') """ plot_backend = _get_plot_backend("matplotlib") return plot_backend.andrews_curves( frame=frame, class_column=class_column, ax=ax, samples=samples, color=color, colormap=colormap, **kwargs, ) def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds): """ Bootstrap plot on mean, median and mid-range statistics. The bootstrap plot is used to estimate the uncertainty of a statistic by relaying on random sampling with replacement [1]_. This function will generate bootstrapping plots for mean, median and mid-range statistics for the given number of samples of the given size. .. [1] "Bootstrapping (statistics)" in \ https://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29 Parameters ---------- series : pandas.Series pandas Series from where to get the samplings for the bootstrapping. fig : matplotlib.figure.Figure, default None If given, it will use the `fig` reference for plotting instead of creating a new one with default parameters. size : int, default 50 Number of data points to consider during each sampling. It must be greater or equal than the length of the `series`. samples : int, default 500 Number of times the bootstrap procedure is performed. **kwds Options to pass to matplotlib plotting method. Returns ------- matplotlib.figure.Figure Matplotlib figure. See Also -------- DataFrame.plot : Basic plotting for DataFrame objects. Series.plot : Basic plotting for Series objects. Examples -------- This example draws a basic bootstap plot for a Series. .. plot:: :context: close-figs >>> s = pd.Series(np.random.uniform(size=100)) >>> pd.plotting.bootstrap_plot(s) """ plot_backend = _get_plot_backend("matplotlib") return plot_backend.bootstrap_plot( series=series, fig=fig, size=size, samples=samples, **kwds ) def parallel_coordinates( frame, class_column, cols=None, ax=None, color=None, use_columns=False, xticks=None, colormap=None, axvlines=True, axvlines_kwds=None, sort_labels=False, **kwargs, ): """ Parallel coordinates plotting. Parameters ---------- frame : DataFrame class_column : str Column name containing class names. cols : list, optional A list of column names to use. ax : matplotlib.axis, optional Matplotlib axis object. color : list or tuple, optional Colors to use for the different classes. use_columns : bool, optional If true, columns will be used as xticks. xticks : list or tuple, optional A list of values to use for xticks. colormap : str or matplotlib colormap, default None Colormap to use for line colors. axvlines : bool, optional If true, vertical lines will be added at each xtick. axvlines_kwds : keywords, optional Options to be passed to axvline method for vertical lines. sort_labels : bool, default False Sort class_column labels, useful when assigning colors. **kwargs Options to pass to matplotlib plotting method. Returns ------- class:`matplotlib.axis.Axes` Examples -------- .. plot:: :context: close-figs >>> df = pd.read_csv( ... 'https://raw.github.com/pandas-dev/' ... 'pandas/master/pandas/tests/io/data/csv/iris.csv' ... ) >>> pd.plotting.parallel_coordinates( ... df, 'Name', color=('#556270', '#4ECDC4', '#C7F464') ... ) """ plot_backend = _get_plot_backend("matplotlib") return plot_backend.parallel_coordinates( frame=frame, class_column=class_column, cols=cols, ax=ax, color=color, use_columns=use_columns, xticks=xticks, colormap=colormap, axvlines=axvlines, axvlines_kwds=axvlines_kwds, sort_labels=sort_labels, **kwargs, ) def lag_plot(series, lag=1, ax=None, **kwds): """ Lag plot for time series. Parameters ---------- series : Time series lag : lag of the scatter plot, default 1 ax : Matplotlib axis object, optional **kwds Matplotlib scatter method keyword arguments. Returns ------- class:`matplotlib.axis.Axes` Examples -------- Lag plots are most commonly used to look for patterns in time series data. Given the following time series .. plot:: :context: close-figs >>> np.random.seed(5) >>> x = np.cumsum(np.random.normal(loc=1, scale=5, size=50)) >>> s = pd.Series(x) >>> s.plot() A lag plot with ``lag=1`` returns .. plot:: :context: close-figs >>> pd.plotting.lag_plot(s, lag=1) """ plot_backend = _get_plot_backend("matplotlib") return plot_backend.lag_plot(series=series, lag=lag, ax=ax, **kwds) def autocorrelation_plot(series, ax=None, **kwargs): """ Autocorrelation plot for time series. Parameters ---------- series : Time series ax : Matplotlib axis object, optional **kwargs Options to pass to matplotlib plotting method. Returns ------- class:`matplotlib.axis.Axes` Examples -------- The horizontal lines in the plot correspond to 95% and 99% confidence bands. The dashed line is 99% confidence band. .. plot:: :context: close-figs >>> spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000) >>> s = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing)) >>> pd.plotting.autocorrelation_plot(s) """ plot_backend = _get_plot_backend("matplotlib") return plot_backend.autocorrelation_plot(series=series, ax=ax, **kwargs) class _Options(dict): """ Stores pandas plotting options. Allows for parameter aliasing so you can just use parameter names that are the same as the plot function parameters, but is stored in a canonical format that makes it easy to breakdown into groups later. """ # alias so the names are same as plotting method parameter names _ALIASES = {"x_compat": "xaxis.compat"} _DEFAULT_KEYS = ["xaxis.compat"] def __init__(self, deprecated=False): self._deprecated = deprecated super().__setitem__("xaxis.compat", False) def __getitem__(self, key): key = self._get_canonical_key(key) if key not in self: raise ValueError(f"{key} is not a valid pandas plotting option") return super().__getitem__(key) def __setitem__(self, key, value): key = self._get_canonical_key(key) return super().__setitem__(key, value) def __delitem__(self, key): key = self._get_canonical_key(key) if key in self._DEFAULT_KEYS: raise ValueError(f"Cannot remove default parameter {key}") return super().__delitem__(key) def __contains__(self, key) -> bool: key = self._get_canonical_key(key) return super().__contains__(key) def reset(self): """ Reset the option store to its initial state Returns ------- None """ self.__init__() def _get_canonical_key(self, key): return self._ALIASES.get(key, key) @contextmanager def use(self, key, value): """ Temporarily set a parameter value using the with statement. Aliasing allowed. """ old_value = self[key] try: self[key] = value yield self finally: self[key] = old_value plot_params = _Options()
""" Tests the 'read_fwf' function in parsers.py. This test suite is independent of the others because the engine is set to 'python-fwf' internally. """ from datetime import datetime from io import BytesIO, StringIO import numpy as np import pytest import pandas as pd from pandas import DataFrame, DatetimeIndex import pandas._testing as tm from pandas.io.parsers import EmptyDataError, read_csv, read_fwf def test_basic(): data = """\ A B C D 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ result = read_fwf(StringIO(data)) expected = DataFrame( [ [201158, 360.242940, 149.910199, 11950.7], [201159, 444.953632, 166.985655, 11788.4], [201160, 364.136849, 183.628767, 11806.2], [201161, 413.836124, 184.375703, 11916.8], [201162, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D"], ) tm.assert_frame_equal(result, expected) def test_colspecs(): data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] result = read_fwf(StringIO(data), colspecs=colspecs) expected = DataFrame( [ [2011, 58, 360.242940, 149.910199, 11950.7], [2011, 59, 444.953632, 166.985655, 11788.4], [2011, 60, 364.136849, 183.628767, 11806.2], [2011, 61, 413.836124, 184.375703, 11916.8], [2011, 62, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D", "E"], ) tm.assert_frame_equal(result, expected) def test_widths(): data = """\ A B C D E 2011 58 360.242940 149.910199 11950.7 2011 59 444.953632 166.985655 11788.4 2011 60 364.136849 183.628767 11806.2 2011 61 413.836124 184.375703 11916.8 2011 62 502.953953 173.237159 12468.3 """ result = read_fwf(StringIO(data), widths=[5, 5, 13, 13, 7]) expected = DataFrame( [ [2011, 58, 360.242940, 149.910199, 11950.7], [2011, 59, 444.953632, 166.985655, 11788.4], [2011, 60, 364.136849, 183.628767, 11806.2], [2011, 61, 413.836124, 184.375703, 11916.8], [2011, 62, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D", "E"], ) tm.assert_frame_equal(result, expected) def test_non_space_filler(): # From Thomas Kluyver: # # Apparently, some non-space filler characters can be seen, this is # supported by specifying the 'delimiter' character: # # http://publib.boulder.ibm.com/infocenter/dmndhelp/v6r1mx/index.jsp?topic=/com.ibm.wbit.612.help.config.doc/topics/rfixwidth.html data = """\ A~~~~B~~~~C~~~~~~~~~~~~D~~~~~~~~~~~~E 201158~~~~360.242940~~~149.910199~~~11950.7 201159~~~~444.953632~~~166.985655~~~11788.4 201160~~~~364.136849~~~183.628767~~~11806.2 201161~~~~413.836124~~~184.375703~~~11916.8 201162~~~~502.953953~~~173.237159~~~12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] result = read_fwf(StringIO(data), colspecs=colspecs, delimiter="~") expected = DataFrame( [ [2011, 58, 360.242940, 149.910199, 11950.7], [2011, 59, 444.953632, 166.985655, 11788.4], [2011, 60, 364.136849, 183.628767, 11806.2], [2011, 61, 413.836124, 184.375703, 11916.8], [2011, 62, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D", "E"], ) tm.assert_frame_equal(result, expected) def test_over_specified(): data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] with pytest.raises(ValueError, match="must specify only one of"): read_fwf(StringIO(data), colspecs=colspecs, widths=[6, 10, 10, 7]) def test_under_specified(): data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ with pytest.raises(ValueError, match="Must specify either"): read_fwf(StringIO(data), colspecs=None, widths=None) def test_read_csv_compat(): csv_data = """\ A,B,C,D,E 2011,58,360.242940,149.910199,11950.7 2011,59,444.953632,166.985655,11788.4 2011,60,364.136849,183.628767,11806.2 2011,61,413.836124,184.375703,11916.8 2011,62,502.953953,173.237159,12468.3 """ expected = read_csv(StringIO(csv_data), engine="python") fwf_data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] result = read_fwf(StringIO(fwf_data), colspecs=colspecs) tm.assert_frame_equal(result, expected) def test_bytes_io_input(): result = read_fwf( BytesIO("שלום\nשלום".encode("utf8")), widths=[2, 2], encoding="utf8" ) expected = DataFrame([["של", "ום"]], columns=["של", "ום"]) tm.assert_frame_equal(result, expected) def test_fwf_colspecs_is_list_or_tuple(): data = """index,A,B,C,D foo,2,3,4,5 bar,7,8,9,10 baz,12,13,14,15 qux,12,13,14,15 foo2,12,13,14,15 bar2,12,13,14,15 """ msg = "column specifications must be a list or tuple.+" with pytest.raises(TypeError, match=msg): read_fwf(StringIO(data), colspecs={"a": 1}, delimiter=",") def test_fwf_colspecs_is_list_or_tuple_of_two_element_tuples(): data = """index,A,B,C,D foo,2,3,4,5 bar,7,8,9,10 baz,12,13,14,15 qux,12,13,14,15 foo2,12,13,14,15 bar2,12,13,14,15 """ msg = "Each column specification must be.+" with pytest.raises(TypeError, match=msg): read_fwf(StringIO(data), [("a", 1)]) @pytest.mark.parametrize( "colspecs,exp_data", [ ([(0, 3), (3, None)], [[123, 456], [456, 789]]), ([(None, 3), (3, 6)], [[123, 456], [456, 789]]), ([(0, None), (3, None)], [[123456, 456], [456789, 789]]), ([(None, None), (3, 6)], [[123456, 456], [456789, 789]]), ], ) def test_fwf_colspecs_none(colspecs, exp_data): # see gh-7079 data = """\ 123456 456789 """ expected = DataFrame(exp_data) result = read_fwf(StringIO(data), colspecs=colspecs, header=None) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "infer_nrows,exp_data", [ # infer_nrows --> colspec == [(2, 3), (5, 6)] (1, [[1, 2], [3, 8]]), # infer_nrows > number of rows (10, [[1, 2], [123, 98]]), ], ) def test_fwf_colspecs_infer_nrows(infer_nrows, exp_data): # see gh-15138 data = """\ 1 2 123 98 """ expected = DataFrame(exp_data) result = read_fwf(StringIO(data), infer_nrows=infer_nrows, header=None) tm.assert_frame_equal(result, expected) def test_fwf_regression(): # see gh-3594 # # Turns out "T060" is parsable as a datetime slice! tz_list = [1, 10, 20, 30, 60, 80, 100] widths = [16] + [8] * len(tz_list) names = ["SST"] + [f"T{z:03d}" for z in tz_list[1:]] data = """ 2009164202000 9.5403 9.4105 8.6571 7.8372 6.0612 5.8843 5.5192 2009164203000 9.5435 9.2010 8.6167 7.8176 6.0804 5.8728 5.4869 2009164204000 9.5873 9.1326 8.4694 7.5889 6.0422 5.8526 5.4657 2009164205000 9.5810 9.0896 8.4009 7.4652 6.0322 5.8189 5.4379 2009164210000 9.6034 9.0897 8.3822 7.4905 6.0908 5.7904 5.4039 """ result = read_fwf( StringIO(data), index_col=0, header=None, names=names, widths=widths, parse_dates=True, date_parser=lambda s: datetime.strptime(s, "%Y%j%H%M%S"), ) expected = DataFrame( [ [9.5403, 9.4105, 8.6571, 7.8372, 6.0612, 5.8843, 5.5192], [9.5435, 9.2010, 8.6167, 7.8176, 6.0804, 5.8728, 5.4869], [9.5873, 9.1326, 8.4694, 7.5889, 6.0422, 5.8526, 5.4657], [9.5810, 9.0896, 8.4009, 7.4652, 6.0322, 5.8189, 5.4379], [9.6034, 9.0897, 8.3822, 7.4905, 6.0908, 5.7904, 5.4039], ], index=DatetimeIndex( [ "2009-06-13 20:20:00", "2009-06-13 20:30:00", "2009-06-13 20:40:00", "2009-06-13 20:50:00", "2009-06-13 21:00:00", ] ), columns=["SST", "T010", "T020", "T030", "T060", "T080", "T100"], ) tm.assert_frame_equal(result, expected) def test_fwf_for_uint8(): data = """1421302965.213420 PRI=3 PGN=0xef00 DST=0x17 SRC=0x28 04 154 00 00 00 00 00 127 1421302964.226776 PRI=6 PGN=0xf002 SRC=0x47 243 00 00 255 247 00 00 71""" # noqa df = read_fwf( StringIO(data), colspecs=[(0, 17), (25, 26), (33, 37), (49, 51), (58, 62), (63, 1000)], names=["time", "pri", "pgn", "dst", "src", "data"], converters={ "pgn": lambda x: int(x, 16), "src": lambda x: int(x, 16), "dst": lambda x: int(x, 16), "data": lambda x: len(x.split(" ")), }, ) expected = DataFrame( [ [1421302965.213420, 3, 61184, 23, 40, 8], [1421302964.226776, 6, 61442, None, 71, 8], ], columns=["time", "pri", "pgn", "dst", "src", "data"], ) expected["dst"] = expected["dst"].astype(object) tm.assert_frame_equal(df, expected) @pytest.mark.parametrize("comment", ["#", "~", "!"]) def test_fwf_comment(comment): data = """\ 1 2. 4 #hello world 5 NaN 10.0 """ data = data.replace("#", comment) colspecs = [(0, 3), (4, 9), (9, 25)] expected = DataFrame([[1, 2.0, 4], [5, np.nan, 10.0]]) result = read_fwf(StringIO(data), colspecs=colspecs, header=None, comment=comment) tm.assert_almost_equal(result, expected) @pytest.mark.parametrize("thousands", [",", "#", "~"]) def test_fwf_thousands(thousands): data = """\ 1 2,334.0 5 10 13 10. """ data = data.replace(",", thousands) colspecs = [(0, 3), (3, 11), (12, 16)] expected = DataFrame([[1, 2334.0, 5], [10, 13, 10.0]]) result = read_fwf( StringIO(data), header=None, colspecs=colspecs, thousands=thousands ) tm.assert_almost_equal(result, expected) @pytest.mark.parametrize("header", [True, False]) def test_bool_header_arg(header): # see gh-6114 data = """\ MyColumn a b a b""" msg = "Passing a bool to header is invalid" with pytest.raises(TypeError, match=msg): read_fwf(StringIO(data), header=header) def test_full_file(): # File with all values. test = """index A B C 2000-01-03T00:00:00 0.980268513777 3 foo 2000-01-04T00:00:00 1.04791624281 -4 bar 2000-01-05T00:00:00 0.498580885705 73 baz 2000-01-06T00:00:00 1.12020151869 1 foo 2000-01-07T00:00:00 0.487094399463 0 bar 2000-01-10T00:00:00 0.836648671666 2 baz 2000-01-11T00:00:00 0.157160753327 34 foo""" colspecs = ((0, 19), (21, 35), (38, 40), (42, 45)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_full_file_with_missing(): # File with missing values. test = """index A B C 2000-01-03T00:00:00 0.980268513777 3 foo 2000-01-04T00:00:00 1.04791624281 -4 bar 0.498580885705 73 baz 2000-01-06T00:00:00 1.12020151869 1 foo 2000-01-07T00:00:00 0 bar 2000-01-10T00:00:00 0.836648671666 2 baz 34""" colspecs = ((0, 19), (21, 35), (38, 40), (42, 45)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_full_file_with_spaces(): # File with spaces in columns. test = """ Account Name Balance CreditLimit AccountCreated 101 Keanu Reeves 9315.45 10000.00 1/17/1998 312 Gerard Butler 90.00 1000.00 8/6/2003 868 Jennifer Love Hewitt 0 17000.00 5/25/1985 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 317 Bill Murray 789.65 5000.00 2/5/2007 """.strip( "\r\n" ) colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_full_file_with_spaces_and_missing(): # File with spaces and missing values in columns. test = """ Account Name Balance CreditLimit AccountCreated 101 10000.00 1/17/1998 312 Gerard Butler 90.00 1000.00 8/6/2003 868 5/25/1985 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 317 Bill Murray 789.65 """.strip( "\r\n" ) colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_messed_up_data(): # Completely messed up file. test = """ Account Name Balance Credit Limit Account Created 101 10000.00 1/17/1998 312 Gerard Butler 90.00 1000.00 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 317 Bill Murray 789.65 """.strip( "\r\n" ) colspecs = ((2, 10), (15, 33), (37, 45), (49, 61), (64, 79)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_multiple_delimiters(): test = r""" col1~~~~~col2 col3++++++++++++++++++col4 ~~22.....11.0+++foo~~~~~~~~~~Keanu Reeves 33+++122.33\\\bar.........Gerard Butler ++44~~~~12.01 baz~~Jennifer Love Hewitt ~~55 11+++foo++++Jada Pinkett-Smith ..66++++++.03~~~bar Bill Murray """.strip( "\r\n" ) delimiter = " +~.\\" colspecs = ((0, 4), (7, 13), (15, 19), (21, 41)) expected = read_fwf(StringIO(test), colspecs=colspecs, delimiter=delimiter) result = read_fwf(StringIO(test), delimiter=delimiter) tm.assert_frame_equal(result, expected) def test_variable_width_unicode(): data = """ שלום שלום ום שלל של ום """.strip( "\r\n" ) encoding = "utf8" kwargs = dict(header=None, encoding=encoding) expected = read_fwf( BytesIO(data.encode(encoding)), colspecs=[(0, 4), (5, 9)], **kwargs ) result = read_fwf(BytesIO(data.encode(encoding)), **kwargs) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", [dict(), {"a": "float64", "b": str, "c": "int32"}]) def test_dtype(dtype): data = """ a b c 1 2 3.2 3 4 5.2 """ colspecs = [(0, 5), (5, 10), (10, None)] result = read_fwf(StringIO(data), colspecs=colspecs, dtype=dtype) expected = pd.DataFrame( {"a": [1, 3], "b": [2, 4], "c": [3.2, 5.2]}, columns=["a", "b", "c"] ) for col, dt in dtype.items(): expected[col] = expected[col].astype(dt) tm.assert_frame_equal(result, expected) def test_skiprows_inference(): # see gh-11256 data = """ Text contained in the file header DataCol1 DataCol2 0.0 1.0 101.6 956.1 """.strip() skiprows = 2 expected = read_csv(StringIO(data), skiprows=skiprows, delim_whitespace=True) result = read_fwf(StringIO(data), skiprows=skiprows) tm.assert_frame_equal(result, expected) def test_skiprows_by_index_inference(): data = """ To be skipped Not To Be Skipped Once more to be skipped 123 34 8 123 456 78 9 456 """.strip() skiprows = [0, 2] expected = read_csv(StringIO(data), skiprows=skiprows, delim_whitespace=True) result = read_fwf(StringIO(data), skiprows=skiprows) tm.assert_frame_equal(result, expected) def test_skiprows_inference_empty(): data = """ AA BBB C 12 345 6 78 901 2 """.strip() msg = "No rows from which to infer column width" with pytest.raises(EmptyDataError, match=msg): read_fwf(StringIO(data), skiprows=3) def test_whitespace_preservation(): # see gh-16772 header = None csv_data = """ a ,bbb cc,dd """ fwf_data = """ a bbb ccdd """ result = read_fwf( StringIO(fwf_data), widths=[3, 3], header=header, skiprows=[0], delimiter="\n\t" ) expected = read_csv(StringIO(csv_data), header=header) tm.assert_frame_equal(result, expected) def test_default_delimiter(): header = None csv_data = """ a,bbb cc,dd""" fwf_data = """ a \tbbb cc\tdd """ result = read_fwf(StringIO(fwf_data), widths=[3, 3], header=header, skiprows=[0]) expected = read_csv(StringIO(csv_data), header=header) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("infer", [True, False, None]) def test_fwf_compression(compression_only, infer): data = """1111111111 2222222222 3333333333""".strip() compression = compression_only extension = "gz" if compression == "gzip" else compression kwargs = dict(widths=[5, 5], names=["one", "two"]) expected = read_fwf(StringIO(data), **kwargs) data = bytes(data, encoding="utf-8") with tm.ensure_clean(filename="tmp." + extension) as path: tm.write_to_compressed(compression, path, data) if infer is not None: kwargs["compression"] = "infer" if infer else compression result = read_fwf(path, **kwargs) tm.assert_frame_equal(result, expected)
TomAugspurger/pandas
pandas/tests/io/parser/test_read_fwf.py
pandas/plotting/_misc.py
""" Helper functions to generate range-like data for DatetimeArray (and possibly TimedeltaArray/PeriodArray) """ from typing import Union import numpy as np from pandas._libs.tslibs import OutOfBoundsDatetime, Timedelta, Timestamp from pandas.tseries.offsets import DateOffset def generate_regular_range( start: Union[Timestamp, Timedelta], end: Union[Timestamp, Timedelta], periods: int, freq: DateOffset, ): """ Generate a range of dates or timestamps with the spans between dates described by the given `freq` DateOffset. Parameters ---------- start : Timedelta, Timestamp or None First point of produced date range. end : Timedelta, Timestamp or None Last point of produced date range. periods : int Number of periods in produced date range. freq : Tick Describes space between dates in produced date range. Returns ------- ndarray[np.int64] Representing nanoseconds. """ start = start.value if start is not None else None end = end.value if end is not None else None stride = freq.nanos if periods is None: b = start # cannot just use e = Timestamp(end) + 1 because arange breaks when # stride is too large, see GH10887 e = b + (end - b) // stride * stride + stride // 2 + 1 elif start is not None: b = start e = _generate_range_overflow_safe(b, periods, stride, side="start") elif end is not None: e = end + stride b = _generate_range_overflow_safe(e, periods, stride, side="end") else: raise ValueError( "at least 'start' or 'end' should be specified if a 'period' is given." ) with np.errstate(over="raise"): # If the range is sufficiently large, np.arange may overflow # and incorrectly return an empty array if not caught. try: values = np.arange(b, e, stride, dtype=np.int64) except FloatingPointError: xdr = [b] while xdr[-1] != e: xdr.append(xdr[-1] + stride) values = np.array(xdr[:-1], dtype=np.int64) return values def _generate_range_overflow_safe( endpoint: int, periods: int, stride: int, side: str = "start" ) -> int: """ Calculate the second endpoint for passing to np.arange, checking to avoid an integer overflow. Catch OverflowError and re-raise as OutOfBoundsDatetime. Parameters ---------- endpoint : int nanosecond timestamp of the known endpoint of the desired range periods : int number of periods in the desired range stride : int nanoseconds between periods in the desired range side : {'start', 'end'} which end of the range `endpoint` refers to Returns ------- other_end : int Raises ------ OutOfBoundsDatetime """ # GH#14187 raise instead of incorrectly wrapping around assert side in ["start", "end"] i64max = np.uint64(np.iinfo(np.int64).max) msg = f"Cannot generate range with {side}={endpoint} and periods={periods}" with np.errstate(over="raise"): # if periods * strides cannot be multiplied within the *uint64* bounds, # we cannot salvage the operation by recursing, so raise try: addend = np.uint64(periods) * np.uint64(np.abs(stride)) except FloatingPointError as err: raise OutOfBoundsDatetime(msg) from err if np.abs(addend) <= i64max: # relatively easy case without casting concerns return _generate_range_overflow_safe_signed(endpoint, periods, stride, side) elif (endpoint > 0 and side == "start" and stride > 0) or ( endpoint < 0 and side == "end" and stride > 0 ): # no chance of not-overflowing raise OutOfBoundsDatetime(msg) elif side == "end" and endpoint > i64max and endpoint - stride <= i64max: # in _generate_regular_range we added `stride` thereby overflowing # the bounds. Adjust to fix this. return _generate_range_overflow_safe( endpoint - stride, periods - 1, stride, side ) # split into smaller pieces mid_periods = periods // 2 remaining = periods - mid_periods assert 0 < remaining < periods, (remaining, periods, endpoint, stride) midpoint = _generate_range_overflow_safe(endpoint, mid_periods, stride, side) return _generate_range_overflow_safe(midpoint, remaining, stride, side) def _generate_range_overflow_safe_signed( endpoint: int, periods: int, stride: int, side: str ) -> int: """ A special case for _generate_range_overflow_safe where `periods * stride` can be calculated without overflowing int64 bounds. """ assert side in ["start", "end"] if side == "end": stride *= -1 with np.errstate(over="raise"): addend = np.int64(periods) * np.int64(stride) try: # easy case with no overflows return np.int64(endpoint) + addend except (FloatingPointError, OverflowError): # with endpoint negative and addend positive we risk # FloatingPointError; with reversed signed we risk OverflowError pass # if stride and endpoint had opposite signs, then endpoint + addend # should never overflow. so they must have the same signs assert (stride > 0 and endpoint >= 0) or (stride < 0 and endpoint <= 0) if stride > 0: # watch out for very special case in which we just slightly # exceed implementation bounds, but when passing the result to # np.arange will get a result slightly within the bounds result = np.uint64(endpoint) + np.uint64(addend) i64max = np.uint64(np.iinfo(np.int64).max) assert result > i64max if result <= i64max + np.uint64(stride): return result raise OutOfBoundsDatetime( f"Cannot generate range with {side}={endpoint} and periods={periods}" )
""" Tests the 'read_fwf' function in parsers.py. This test suite is independent of the others because the engine is set to 'python-fwf' internally. """ from datetime import datetime from io import BytesIO, StringIO import numpy as np import pytest import pandas as pd from pandas import DataFrame, DatetimeIndex import pandas._testing as tm from pandas.io.parsers import EmptyDataError, read_csv, read_fwf def test_basic(): data = """\ A B C D 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ result = read_fwf(StringIO(data)) expected = DataFrame( [ [201158, 360.242940, 149.910199, 11950.7], [201159, 444.953632, 166.985655, 11788.4], [201160, 364.136849, 183.628767, 11806.2], [201161, 413.836124, 184.375703, 11916.8], [201162, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D"], ) tm.assert_frame_equal(result, expected) def test_colspecs(): data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] result = read_fwf(StringIO(data), colspecs=colspecs) expected = DataFrame( [ [2011, 58, 360.242940, 149.910199, 11950.7], [2011, 59, 444.953632, 166.985655, 11788.4], [2011, 60, 364.136849, 183.628767, 11806.2], [2011, 61, 413.836124, 184.375703, 11916.8], [2011, 62, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D", "E"], ) tm.assert_frame_equal(result, expected) def test_widths(): data = """\ A B C D E 2011 58 360.242940 149.910199 11950.7 2011 59 444.953632 166.985655 11788.4 2011 60 364.136849 183.628767 11806.2 2011 61 413.836124 184.375703 11916.8 2011 62 502.953953 173.237159 12468.3 """ result = read_fwf(StringIO(data), widths=[5, 5, 13, 13, 7]) expected = DataFrame( [ [2011, 58, 360.242940, 149.910199, 11950.7], [2011, 59, 444.953632, 166.985655, 11788.4], [2011, 60, 364.136849, 183.628767, 11806.2], [2011, 61, 413.836124, 184.375703, 11916.8], [2011, 62, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D", "E"], ) tm.assert_frame_equal(result, expected) def test_non_space_filler(): # From Thomas Kluyver: # # Apparently, some non-space filler characters can be seen, this is # supported by specifying the 'delimiter' character: # # http://publib.boulder.ibm.com/infocenter/dmndhelp/v6r1mx/index.jsp?topic=/com.ibm.wbit.612.help.config.doc/topics/rfixwidth.html data = """\ A~~~~B~~~~C~~~~~~~~~~~~D~~~~~~~~~~~~E 201158~~~~360.242940~~~149.910199~~~11950.7 201159~~~~444.953632~~~166.985655~~~11788.4 201160~~~~364.136849~~~183.628767~~~11806.2 201161~~~~413.836124~~~184.375703~~~11916.8 201162~~~~502.953953~~~173.237159~~~12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] result = read_fwf(StringIO(data), colspecs=colspecs, delimiter="~") expected = DataFrame( [ [2011, 58, 360.242940, 149.910199, 11950.7], [2011, 59, 444.953632, 166.985655, 11788.4], [2011, 60, 364.136849, 183.628767, 11806.2], [2011, 61, 413.836124, 184.375703, 11916.8], [2011, 62, 502.953953, 173.237159, 12468.3], ], columns=["A", "B", "C", "D", "E"], ) tm.assert_frame_equal(result, expected) def test_over_specified(): data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] with pytest.raises(ValueError, match="must specify only one of"): read_fwf(StringIO(data), colspecs=colspecs, widths=[6, 10, 10, 7]) def test_under_specified(): data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ with pytest.raises(ValueError, match="Must specify either"): read_fwf(StringIO(data), colspecs=None, widths=None) def test_read_csv_compat(): csv_data = """\ A,B,C,D,E 2011,58,360.242940,149.910199,11950.7 2011,59,444.953632,166.985655,11788.4 2011,60,364.136849,183.628767,11806.2 2011,61,413.836124,184.375703,11916.8 2011,62,502.953953,173.237159,12468.3 """ expected = read_csv(StringIO(csv_data), engine="python") fwf_data = """\ A B C D E 201158 360.242940 149.910199 11950.7 201159 444.953632 166.985655 11788.4 201160 364.136849 183.628767 11806.2 201161 413.836124 184.375703 11916.8 201162 502.953953 173.237159 12468.3 """ colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)] result = read_fwf(StringIO(fwf_data), colspecs=colspecs) tm.assert_frame_equal(result, expected) def test_bytes_io_input(): result = read_fwf( BytesIO("שלום\nשלום".encode("utf8")), widths=[2, 2], encoding="utf8" ) expected = DataFrame([["של", "ום"]], columns=["של", "ום"]) tm.assert_frame_equal(result, expected) def test_fwf_colspecs_is_list_or_tuple(): data = """index,A,B,C,D foo,2,3,4,5 bar,7,8,9,10 baz,12,13,14,15 qux,12,13,14,15 foo2,12,13,14,15 bar2,12,13,14,15 """ msg = "column specifications must be a list or tuple.+" with pytest.raises(TypeError, match=msg): read_fwf(StringIO(data), colspecs={"a": 1}, delimiter=",") def test_fwf_colspecs_is_list_or_tuple_of_two_element_tuples(): data = """index,A,B,C,D foo,2,3,4,5 bar,7,8,9,10 baz,12,13,14,15 qux,12,13,14,15 foo2,12,13,14,15 bar2,12,13,14,15 """ msg = "Each column specification must be.+" with pytest.raises(TypeError, match=msg): read_fwf(StringIO(data), [("a", 1)]) @pytest.mark.parametrize( "colspecs,exp_data", [ ([(0, 3), (3, None)], [[123, 456], [456, 789]]), ([(None, 3), (3, 6)], [[123, 456], [456, 789]]), ([(0, None), (3, None)], [[123456, 456], [456789, 789]]), ([(None, None), (3, 6)], [[123456, 456], [456789, 789]]), ], ) def test_fwf_colspecs_none(colspecs, exp_data): # see gh-7079 data = """\ 123456 456789 """ expected = DataFrame(exp_data) result = read_fwf(StringIO(data), colspecs=colspecs, header=None) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "infer_nrows,exp_data", [ # infer_nrows --> colspec == [(2, 3), (5, 6)] (1, [[1, 2], [3, 8]]), # infer_nrows > number of rows (10, [[1, 2], [123, 98]]), ], ) def test_fwf_colspecs_infer_nrows(infer_nrows, exp_data): # see gh-15138 data = """\ 1 2 123 98 """ expected = DataFrame(exp_data) result = read_fwf(StringIO(data), infer_nrows=infer_nrows, header=None) tm.assert_frame_equal(result, expected) def test_fwf_regression(): # see gh-3594 # # Turns out "T060" is parsable as a datetime slice! tz_list = [1, 10, 20, 30, 60, 80, 100] widths = [16] + [8] * len(tz_list) names = ["SST"] + [f"T{z:03d}" for z in tz_list[1:]] data = """ 2009164202000 9.5403 9.4105 8.6571 7.8372 6.0612 5.8843 5.5192 2009164203000 9.5435 9.2010 8.6167 7.8176 6.0804 5.8728 5.4869 2009164204000 9.5873 9.1326 8.4694 7.5889 6.0422 5.8526 5.4657 2009164205000 9.5810 9.0896 8.4009 7.4652 6.0322 5.8189 5.4379 2009164210000 9.6034 9.0897 8.3822 7.4905 6.0908 5.7904 5.4039 """ result = read_fwf( StringIO(data), index_col=0, header=None, names=names, widths=widths, parse_dates=True, date_parser=lambda s: datetime.strptime(s, "%Y%j%H%M%S"), ) expected = DataFrame( [ [9.5403, 9.4105, 8.6571, 7.8372, 6.0612, 5.8843, 5.5192], [9.5435, 9.2010, 8.6167, 7.8176, 6.0804, 5.8728, 5.4869], [9.5873, 9.1326, 8.4694, 7.5889, 6.0422, 5.8526, 5.4657], [9.5810, 9.0896, 8.4009, 7.4652, 6.0322, 5.8189, 5.4379], [9.6034, 9.0897, 8.3822, 7.4905, 6.0908, 5.7904, 5.4039], ], index=DatetimeIndex( [ "2009-06-13 20:20:00", "2009-06-13 20:30:00", "2009-06-13 20:40:00", "2009-06-13 20:50:00", "2009-06-13 21:00:00", ] ), columns=["SST", "T010", "T020", "T030", "T060", "T080", "T100"], ) tm.assert_frame_equal(result, expected) def test_fwf_for_uint8(): data = """1421302965.213420 PRI=3 PGN=0xef00 DST=0x17 SRC=0x28 04 154 00 00 00 00 00 127 1421302964.226776 PRI=6 PGN=0xf002 SRC=0x47 243 00 00 255 247 00 00 71""" # noqa df = read_fwf( StringIO(data), colspecs=[(0, 17), (25, 26), (33, 37), (49, 51), (58, 62), (63, 1000)], names=["time", "pri", "pgn", "dst", "src", "data"], converters={ "pgn": lambda x: int(x, 16), "src": lambda x: int(x, 16), "dst": lambda x: int(x, 16), "data": lambda x: len(x.split(" ")), }, ) expected = DataFrame( [ [1421302965.213420, 3, 61184, 23, 40, 8], [1421302964.226776, 6, 61442, None, 71, 8], ], columns=["time", "pri", "pgn", "dst", "src", "data"], ) expected["dst"] = expected["dst"].astype(object) tm.assert_frame_equal(df, expected) @pytest.mark.parametrize("comment", ["#", "~", "!"]) def test_fwf_comment(comment): data = """\ 1 2. 4 #hello world 5 NaN 10.0 """ data = data.replace("#", comment) colspecs = [(0, 3), (4, 9), (9, 25)] expected = DataFrame([[1, 2.0, 4], [5, np.nan, 10.0]]) result = read_fwf(StringIO(data), colspecs=colspecs, header=None, comment=comment) tm.assert_almost_equal(result, expected) @pytest.mark.parametrize("thousands", [",", "#", "~"]) def test_fwf_thousands(thousands): data = """\ 1 2,334.0 5 10 13 10. """ data = data.replace(",", thousands) colspecs = [(0, 3), (3, 11), (12, 16)] expected = DataFrame([[1, 2334.0, 5], [10, 13, 10.0]]) result = read_fwf( StringIO(data), header=None, colspecs=colspecs, thousands=thousands ) tm.assert_almost_equal(result, expected) @pytest.mark.parametrize("header", [True, False]) def test_bool_header_arg(header): # see gh-6114 data = """\ MyColumn a b a b""" msg = "Passing a bool to header is invalid" with pytest.raises(TypeError, match=msg): read_fwf(StringIO(data), header=header) def test_full_file(): # File with all values. test = """index A B C 2000-01-03T00:00:00 0.980268513777 3 foo 2000-01-04T00:00:00 1.04791624281 -4 bar 2000-01-05T00:00:00 0.498580885705 73 baz 2000-01-06T00:00:00 1.12020151869 1 foo 2000-01-07T00:00:00 0.487094399463 0 bar 2000-01-10T00:00:00 0.836648671666 2 baz 2000-01-11T00:00:00 0.157160753327 34 foo""" colspecs = ((0, 19), (21, 35), (38, 40), (42, 45)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_full_file_with_missing(): # File with missing values. test = """index A B C 2000-01-03T00:00:00 0.980268513777 3 foo 2000-01-04T00:00:00 1.04791624281 -4 bar 0.498580885705 73 baz 2000-01-06T00:00:00 1.12020151869 1 foo 2000-01-07T00:00:00 0 bar 2000-01-10T00:00:00 0.836648671666 2 baz 34""" colspecs = ((0, 19), (21, 35), (38, 40), (42, 45)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_full_file_with_spaces(): # File with spaces in columns. test = """ Account Name Balance CreditLimit AccountCreated 101 Keanu Reeves 9315.45 10000.00 1/17/1998 312 Gerard Butler 90.00 1000.00 8/6/2003 868 Jennifer Love Hewitt 0 17000.00 5/25/1985 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 317 Bill Murray 789.65 5000.00 2/5/2007 """.strip( "\r\n" ) colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_full_file_with_spaces_and_missing(): # File with spaces and missing values in columns. test = """ Account Name Balance CreditLimit AccountCreated 101 10000.00 1/17/1998 312 Gerard Butler 90.00 1000.00 8/6/2003 868 5/25/1985 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 317 Bill Murray 789.65 """.strip( "\r\n" ) colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_messed_up_data(): # Completely messed up file. test = """ Account Name Balance Credit Limit Account Created 101 10000.00 1/17/1998 312 Gerard Butler 90.00 1000.00 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 317 Bill Murray 789.65 """.strip( "\r\n" ) colspecs = ((2, 10), (15, 33), (37, 45), (49, 61), (64, 79)) expected = read_fwf(StringIO(test), colspecs=colspecs) result = read_fwf(StringIO(test)) tm.assert_frame_equal(result, expected) def test_multiple_delimiters(): test = r""" col1~~~~~col2 col3++++++++++++++++++col4 ~~22.....11.0+++foo~~~~~~~~~~Keanu Reeves 33+++122.33\\\bar.........Gerard Butler ++44~~~~12.01 baz~~Jennifer Love Hewitt ~~55 11+++foo++++Jada Pinkett-Smith ..66++++++.03~~~bar Bill Murray """.strip( "\r\n" ) delimiter = " +~.\\" colspecs = ((0, 4), (7, 13), (15, 19), (21, 41)) expected = read_fwf(StringIO(test), colspecs=colspecs, delimiter=delimiter) result = read_fwf(StringIO(test), delimiter=delimiter) tm.assert_frame_equal(result, expected) def test_variable_width_unicode(): data = """ שלום שלום ום שלל של ום """.strip( "\r\n" ) encoding = "utf8" kwargs = dict(header=None, encoding=encoding) expected = read_fwf( BytesIO(data.encode(encoding)), colspecs=[(0, 4), (5, 9)], **kwargs ) result = read_fwf(BytesIO(data.encode(encoding)), **kwargs) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", [dict(), {"a": "float64", "b": str, "c": "int32"}]) def test_dtype(dtype): data = """ a b c 1 2 3.2 3 4 5.2 """ colspecs = [(0, 5), (5, 10), (10, None)] result = read_fwf(StringIO(data), colspecs=colspecs, dtype=dtype) expected = pd.DataFrame( {"a": [1, 3], "b": [2, 4], "c": [3.2, 5.2]}, columns=["a", "b", "c"] ) for col, dt in dtype.items(): expected[col] = expected[col].astype(dt) tm.assert_frame_equal(result, expected) def test_skiprows_inference(): # see gh-11256 data = """ Text contained in the file header DataCol1 DataCol2 0.0 1.0 101.6 956.1 """.strip() skiprows = 2 expected = read_csv(StringIO(data), skiprows=skiprows, delim_whitespace=True) result = read_fwf(StringIO(data), skiprows=skiprows) tm.assert_frame_equal(result, expected) def test_skiprows_by_index_inference(): data = """ To be skipped Not To Be Skipped Once more to be skipped 123 34 8 123 456 78 9 456 """.strip() skiprows = [0, 2] expected = read_csv(StringIO(data), skiprows=skiprows, delim_whitespace=True) result = read_fwf(StringIO(data), skiprows=skiprows) tm.assert_frame_equal(result, expected) def test_skiprows_inference_empty(): data = """ AA BBB C 12 345 6 78 901 2 """.strip() msg = "No rows from which to infer column width" with pytest.raises(EmptyDataError, match=msg): read_fwf(StringIO(data), skiprows=3) def test_whitespace_preservation(): # see gh-16772 header = None csv_data = """ a ,bbb cc,dd """ fwf_data = """ a bbb ccdd """ result = read_fwf( StringIO(fwf_data), widths=[3, 3], header=header, skiprows=[0], delimiter="\n\t" ) expected = read_csv(StringIO(csv_data), header=header) tm.assert_frame_equal(result, expected) def test_default_delimiter(): header = None csv_data = """ a,bbb cc,dd""" fwf_data = """ a \tbbb cc\tdd """ result = read_fwf(StringIO(fwf_data), widths=[3, 3], header=header, skiprows=[0]) expected = read_csv(StringIO(csv_data), header=header) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("infer", [True, False, None]) def test_fwf_compression(compression_only, infer): data = """1111111111 2222222222 3333333333""".strip() compression = compression_only extension = "gz" if compression == "gzip" else compression kwargs = dict(widths=[5, 5], names=["one", "two"]) expected = read_fwf(StringIO(data), **kwargs) data = bytes(data, encoding="utf-8") with tm.ensure_clean(filename="tmp." + extension) as path: tm.write_to_compressed(compression, path, data) if infer is not None: kwargs["compression"] = "infer" if infer else compression result = read_fwf(path, **kwargs) tm.assert_frame_equal(result, expected)
TomAugspurger/pandas
pandas/tests/io/parser/test_read_fwf.py
pandas/core/arrays/_ranges.py
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin from past.builtins import basestring import logging import os import re import locale from copy import copy from datetime import datetime, date, time from email.utils import parsedate from time import mktime import jinja2.filters from jinja2 import (Environment, StrictUndefined, ChoiceLoader, FileSystemLoader, PackageLoader, Template, TemplateNotFound, TemplateSyntaxError) from flexget.event import event from flexget.utils.lazy_dict import LazyDict from flexget.utils.pathscrub import pathscrub log = logging.getLogger('utils.template') # The environment will be created after the manager has started environment = None class RenderError(Exception): """Error raised when there is a problem with jinja rendering.""" pass def filter_pathbase(val): """Base name of a path.""" return os.path.basename(val or '') def filter_pathname(val): """Base name of a path, without its extension.""" return os.path.splitext(os.path.basename(val or ''))[0] def filter_pathext(val): """Extension of a path (including the '.').""" return os.path.splitext(val or '')[1] def filter_pathdir(val): """Directory containing the given path.""" return os.path.dirname(val or '') def filter_pathscrub(val, os_mode=None): """Replace problematic characters in a path.""" return pathscrub(val, os_mode) def filter_re_replace(val, pattern, repl): """Perform a regexp replacement on the given string.""" return re.sub(pattern, repl, str(val)) def filter_re_search(val, pattern): """Perform a search for given regexp pattern, return the matching portion of the text.""" if not isinstance(val, basestring): return val result = re.search(pattern, val) if result: return result.group(0) return '' def filter_formatdate(val, format): """Returns a string representation of a datetime object according to format string.""" encoding = locale.getpreferredencoding() if not isinstance(val, (datetime, date, time)): return val return val.strftime(format.encode(encoding)).decode(encoding) def filter_parsedate(val): """Attempts to parse a date according to the rules in RFC 2822""" return datetime.fromtimestamp(mktime(parsedate(val))) def filter_date_suffix(date): day = int(date[-2:]) if 4 <= day <= 20 or 24 <= day <= 30: suffix = "th" else: suffix = ["st", "nd", "rd"][day % 10 - 1] return date + suffix def filter_format_number(val, places=None, grouping=True): """Formats a number according to the user's locale.""" if not isinstance(val, (int, float, int)): return val if places is not None: format = '%.' + str(places) + 'f' elif isinstance(val, (int, int)): format = '%d' else: format = '%.02f' locale.setlocale(locale.LC_ALL, '') return locale.format(format, val, grouping) def filter_pad(val, width, fillchar='0'): """Pads a number or string with fillchar to the specified width.""" return str(val).rjust(width, fillchar) def filter_to_date(date_time_val): if not isinstance(date_time_val, (datetime, date, time)): return date_time_val return date_time_val.date() # Override the built-in Jinja default filter to change the `boolean` param to True by default def filter_default(value, default_value='', boolean=True): return jinja2.filters.do_default(value, default_value, boolean) filter_d = filter_default # TODO: In Jinja 2.8 we will be able to override the Context class to be used explicitly class FlexGetTemplate(Template): """Adds lazy lookup support when rendering templates.""" def new_context(self, vars=None, shared=False, locals=None): context = super(FlexGetTemplate, self).new_context(vars, shared, locals) context.parent = LazyDict(context.parent) return context @event('manager.initialize') def make_environment(manager): """Create our environment and add our custom filters""" global environment environment = Environment(undefined=StrictUndefined, loader=ChoiceLoader([PackageLoader('flexget'), FileSystemLoader(os.path.join(manager.config_base, 'templates'))]), extensions=['jinja2.ext.loopcontrols']) environment.template_class = FlexGetTemplate for name, filt in list(globals().items()): if name.startswith('filter_'): environment.filters[name.split('_', 1)[1]] = filt # TODO: list_templates function def get_template(templatename, pluginname=None): """Loads a template from disk. Looks in both included plugins and users custom plugin dir.""" if not templatename.endswith('.template'): templatename += '.template' locations = [] if pluginname: locations.append(pluginname + '/' + templatename) locations.append(templatename) for location in locations: try: return environment.get_template(location) except TemplateNotFound: pass else: # TODO: Plugins need to catch and reraise this as PluginError, or perhaps we should have # a validator for template files raise ValueError('Template not found: %s (%s)' % (templatename, pluginname)) def render(template, context): """ Renders a Template with `context` as its context. :param template: Template or template string to render. :param context: Context to render the template from. :return: The rendered template text. """ if isinstance(template, basestring): try: template = environment.from_string(template) except TemplateSyntaxError as e: raise RenderError('Error in template syntax: ' + e.message) try: result = template.render(context) except Exception as e: error = RenderError('(%s) %s' % (type(e).__name__, e)) log.debug('Error during rendering: %s' % error) raise error return result def render_from_entry(template_string, entry): """Renders a Template or template string with an Entry as its context.""" # Make a copy of the Entry so we can add some more fields variables = copy(entry.store) variables['now'] = datetime.now() # Add task name to variables, usually it's there because metainfo_task plugin, but not always if 'task' not in variables and hasattr(entry, 'task'): variables['task'] = entry.task.name result = render(template_string, variables) # Only try string replacement if jinja didn't do anything if result == template_string: try: result = template_string % entry except KeyError as e: raise RenderError('Does not contain the field `%s` for string replacement.' % e) except ValueError as e: raise RenderError('Invalid string replacement template: %s (%s)' % (template_string, e)) except TypeError as e: raise RenderError('Error during string replacement: %s' % e.message) return result def render_from_task(template, task): """ Renders a Template with a task as its context. :param template: Template or template string to render. :param task: Task to render the template from. :return: The rendered template text. """ return render(template, {'task': task, 'now': datetime.now()})
# -*- coding: utf-8 -*- from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin import pytest from flexget.utils import json from flexget.plugins.api.trakt_lookup import objects_container as oc @pytest.mark.online class TestTraktSeriesLookupAPI(object): config = 'tasks: {}' def test_trakt_series_lookup_no_params(self, api_client, schema_match): # Bad API call rsp = api_client.get('/trakt/series/') assert rsp.status_code == 404, 'Response code is %s' % rsp.status_code rsp = api_client.get('/trakt/series/the x-files/') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.series_return_object, data) assert not errors values = { 'id': 4063, 'imdb_id': 'tt0106179', 'language': 'en', 'title': 'The X-Files', 'tmdb_id': 4087, 'tvdb_id': 77398, 'tvrage_id': 6312, 'year': 1993 } for field, value in values.items(): assert data.get(field) == value def test_trakt_series_lookup_with_year_param(self, api_client, schema_match): values = { 'id': 235, 'imdb_id': 'tt0098798', 'language': 'en', 'title': 'The Flash', 'tmdb_id': 236, 'tvdb_id': 78650, 'tvrage_id': 5781, 'year': 1990 } rsp = api_client.get('/trakt/series/the flash/?year=1990') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.series_return_object, data) assert not errors for field, value in values.items(): assert data.get(field) == value def test_trakt_series_lookup_with_trakt_slug_id_param(self, api_client, schema_match): values = { 'id': 75481, 'title': 'The Flash', 'tvdb_id': 272094, 'year': 1967 } rsp = api_client.get('/trakt/series/the flash/?trakt_slug=the-flash-1967') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.series_return_object, data) assert not errors for field, value in values.items(): assert data.get(field) == value def test_trakt_series_lookup_with_tmdb_id_param(self, api_client, schema_match): values = { 'id': 60300, 'imdb_id': 'tt3107288', 'title': 'The Flash', 'tmdb_id': 60735, 'tvdb_id': 279121, 'tvrage_id': 36939, 'year': 2014 } rsp = api_client.get('/trakt/series/the flash/?tmdb_id=60735') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.series_return_object, data) assert not errors for field, value in values.items(): assert data.get(field) == value def test_trakt_series_lookup_with_imdb_id_param(self, api_client): values = { 'id': 60300, 'imdb_id': 'tt3107288', 'title': 'The Flash', 'tmdb_id': 60735, 'tvdb_id': 279121, 'tvrage_id': 36939, 'year': 2014 } rsp = api_client.get('/trakt/series/the flash/?imdb_id=tt3107288') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) for field, value in values.items(): assert data.get(field) == value def test_trakt_series_lookup_with_tvdb_id_param(self, api_client, schema_match): values = { 'id': 60300, 'imdb_id': 'tt3107288', 'title': 'The Flash', 'tmdb_id': 60735, 'tvdb_id': 279121, 'tvrage_id': 36939, 'year': 2014 } rsp = api_client.get('/trakt/series/the flash/?tvdb_id=279121') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.series_return_object, data) assert not errors for field, value in values.items(): assert data.get(field) == value def test_trakt_series_lookup_with_tvrage_id_param(self, api_client, schema_match): values = { 'id': 60300, 'imdb_id': 'tt3107288', 'title': 'The Flash', 'tmdb_id': 60735, 'tvdb_id': 279121, 'tvrage_id': 36939, 'year': 2014 } rsp = api_client.get('/trakt/series/the flash/?tvrage_id=36939') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.series_return_object, data) assert not errors for field, value in values.items(): assert data.get(field) == value def test_trakt_series_lookup_with_trakt_id_param(self, api_client, schema_match): values = { 'id': 75481, 'title': 'The Flash', 'year': 1967 } rsp = api_client.get('/trakt/series/the flash/?trakt_id=75481') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.series_return_object, data) assert not errors for field, value in values.items(): assert data.get(field) == value def test_trakt_series_lookup_with_actors_param(self, api_client, schema_match): rsp = api_client.get('/trakt/series/the x-files/?include_actors=true') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.series_return_object, data) assert not errors assert 'actors' in data assert len(data['actors']) > 0 def test_trakt_series_lookup_with_translations_param(self, api_client, schema_match): rsp = api_client.get('/trakt/series/game of thrones/?include_translations=true') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.series_return_object, data) assert not errors assert 'translations' in data @pytest.mark.online class TestTraktMovieLookupAPI(object): config = 'tasks: {}' def test_trakt_movies_lookup_no_params(self, api_client, schema_match): # Bad API call rsp = api_client.get('/trakt/movies/') assert rsp.status_code == 404, 'Response code is %s' % rsp.status_code rsp = api_client.get('/trakt/movies/the matrix/') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.movie_return_object, data) assert not errors values = { 'id': 481, 'title': 'The Matrix', 'year': 1999, 'tmdb_id': 603, 'imdb_id': 'tt0133093' } for field, value in values.items(): assert data.get(field) == value def test_trakt_movies_lookup_year_param(self, api_client, schema_match): rsp = api_client.get('/trakt/movies/the matrix/?year=2003') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.movie_return_object, data) assert not errors values = { 'id': 483, 'title': 'The Matrix Revolutions', 'year': 2003, 'tmdb_id': 605, 'imdb_id': 'tt0242653' } for field, value in values.items(): assert data.get(field) == value def test_trakt_movies_lookup_slug_param(self, api_client, schema_match): rsp = api_client.get('/trakt/movies/the matrix/?trakt_slug=the-matrix-reloaded-2003') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.movie_return_object, data) assert not errors values = { 'id': 482, 'title': 'The Matrix Reloaded', 'year': 2003, 'tmdb_id': 604, 'imdb_id': 'tt0234215' } for field, value in values.items(): assert data.get(field) == value def test_trakt_movies_lookup_actors_params(self, api_client, schema_match): rsp = api_client.get('/trakt/movies/the matrix/?include_actors=true') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.movie_return_object, data) assert not errors values = { 'id': 481, 'title': 'The Matrix', 'year': 1999, 'tmdb_id': 603, 'imdb_id': 'tt0133093' } for field, value in values.items(): assert data.get(field) == value assert 'actors' in data assert len(data['actors']) > 0 def test_trakt_movies_lookup_translations_params(self, api_client, schema_match): rsp = api_client.get('/trakt/movies/the matrix/?include_translations=true') assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code data = json.loads(rsp.get_data(as_text=True)) errors = schema_match(oc.movie_return_object, data) assert not errors values = { 'id': 481, 'title': 'The Matrix', 'year': 1999, 'tmdb_id': 603, 'imdb_id': 'tt0133093' } for field, value in values.items(): assert data.get(field) == value assert 'translations' in data assert len(data['translations']) > 0
oxc/Flexget
flexget/tests/test_trakt_lookup_api.py
flexget/utils/template.py
try: import Crypto.Hash.SHA3_256 as _SHA3_256 # from pycryptodome sha3_256 = _SHA3_256.new except ImportError: from sha3 import sha3_256 from bitcoin import privtopub import sys import rlp from rlp.sedes import big_endian_int, BigEndianInt, Binary from rlp.utils import decode_hex, encode_hex, ascii_chr, str_to_bytes import random big_endian_to_int = lambda x: big_endian_int.deserialize(str_to_bytes(x).lstrip(b'\x00')) int_to_big_endian = lambda x: big_endian_int.serialize(x) TT256 = 2 ** 256 TT256M1 = 2 ** 256 - 1 TT255 = 2 ** 255 if sys.version_info.major == 2: is_numeric = lambda x: isinstance(x, (int, long)) is_string = lambda x: isinstance(x, (str, unicode)) def to_string(value): return str(value) def int_to_bytes(value): if isinstance(value, str): return value return int_to_big_endian(value) def to_string_for_regexp(value): return str(value) unicode = unicode else: is_numeric = lambda x: isinstance(x, int) is_string = lambda x: isinstance(x, bytes) def to_string(value): if isinstance(value, bytes): return value if isinstance(value, str): return bytes(value, 'utf-8') if isinstance(value, int): return bytes(str(value), 'utf-8') def int_to_bytes(value): if isinstance(value, bytes): return value return int_to_big_endian(value) def to_string_for_regexp(value): return str(to_string(value), 'utf-8') unicode = str isnumeric = is_numeric def safe_ord(value): if isinstance(value, int): return value else: return ord(value) # decorator def debug(label): def deb(f): def inner(*args, **kwargs): i = random.randrange(1000000) print(label, i, 'start', args) x = f(*args, **kwargs) print(label, i, 'end', x) return x return inner return deb def flatten(li): o = [] for l in li: o.extend(l) return o def bytearray_to_int(arr): o = 0 for a in arr: o = (o << 8) + a return o def int_to_32bytearray(i): o = [0] * 32 for x in range(32): o[31 - x] = i & 0xff i >>= 8 return o def sha3(seed): return sha3_256(to_string(seed)).digest() assert sha3('').encode('hex') == 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' def privtoaddr(x, extended=False): if len(x) > 32: x = decode_hex(x) o = sha3(privtopub(x)[1:])[12:] return add_checksum(o) if extended else o def add_checksum(x): if len(x) in (40, 48): x = decode_hex(x) if len(x) == 24: return x return x + sha3(x)[:4] def check_and_strip_checksum(x): if len(x) in (40, 48): x = decode_hex(x) assert len(x) == 24 and sha3(x[:20])[:4] == x[-4:] return x[:20] def zpad(x, l): return b'\x00' * max(0, l - len(x)) + x def zunpad(x): i = 0 while i < len(x) and (x[i] == 0 or x[i] == '\x00'): i += 1 return x[i:] def int_to_addr(x): o = [''] * 20 for i in range(20): o[19 - i] = ascii_chr(x & 0xff) x >>= 8 return b''.join(o) def coerce_addr_to_bin(x): if is_numeric(x): return encode_hex(zpad(big_endian_int.serialize(x), 20)) elif len(x) == 40 or len(x) == 0: return decode_hex(x) else: return zpad(x, 20)[-20:] def coerce_addr_to_hex(x): if is_numeric(x): return encode_hex(zpad(big_endian_int.serialize(x), 20)) elif len(x) == 40 or len(x) == 0: return x else: return encode_hex(zpad(x, 20)[-20:]) def coerce_to_int(x): if is_numeric(x): return x elif len(x) == 40: return big_endian_to_int(decode_hex(x)) else: return big_endian_to_int(x) def coerce_to_bytes(x): if is_numeric(x): return big_endian_int.serialize(x) elif len(x) == 40: return decode_hex(x) else: return x def parse_int_or_hex(s): if is_numeric(s): return s elif s[:2] in (b'0x', '0x'): s = to_string(s) tail = (b'0' if len(s) % 2 else b'') + s[2:] return big_endian_to_int(decode_hex(tail)) else: return int(s) def ceil32(x): return x if x % 32 == 0 else x + 32 - (x % 32) def to_signed(i): return i if i < TT255 else i - TT256 def sha3rlp(x): return sha3(rlp.encode(x)) # Format encoders/decoders for bin, addr, int def decode_bin(v): '''decodes a bytearray from serialization''' if not is_string(v): raise Exception("Value must be binary, not RLP array") return v def decode_addr(v): '''decodes an address from serialization''' if len(v) not in [0, 20]: raise Exception("Serialized addresses must be empty or 20 bytes long!") return encode_hex(v) def decode_int(v): '''decodes and integer from serialization''' if len(v) > 0 and (v[0] == '\x00' or v[0] == 0): raise Exception("No leading zero bytes allowed for integers") return big_endian_to_int(v) def decode_int256(v): return big_endian_to_int(v) def encode_bin(v): '''encodes a bytearray into serialization''' return v def encode_root(v): '''encodes a trie root into serialization''' return v def encode_int(v): '''encodes an integer into serialization''' if not is_numeric(v) or v < 0 or v >= TT256: raise Exception("Integer invalid or out of range: %r" % v) return int_to_big_endian(v) def encode_int256(v): return zpad(int_to_big_endian(v), 256) def scan_bin(v): if v[:2] in ('0x', b'0x'): return decode_hex(v[2:]) else: return decode_hex(v) def scan_int(v): if v[:2] in ('0x', b'0x'): return big_endian_to_int(decode_hex(v[2:])) else: return int(v) # Decoding from RLP serialization decoders = { "bin": decode_bin, "addr": decode_addr, "int": decode_int, "int256b": decode_int256, } # Encoding to RLP serialization encoders = { "bin": encode_bin, "int": encode_int, "trie_root": encode_root, "int256b": encode_int256, } # Encoding to printable format printers = { "bin": lambda v: b'0x' + encode_hex(v), "addr": lambda v: v, "int": lambda v: to_string(v), "trie_root": lambda v: encode_hex(v), "int256b": lambda x: encode_hex(zpad(encode_int256(x), 256)) } # Decoding from printable format scanners = { "bin": scan_bin, "addr": lambda x: x[2:] if x[:2] == b'0x' else x, "int": scan_int, "trie_root": lambda x: scan_bin, "int256b": lambda x: big_endian_to_int(decode_hex(x)) } def int_to_hex(x): o = encode_hex(encode_int(x)) return '0x' + (o[1:] if (len(o) > 0 and o[0] == '0') else o) def remove_0x_head(s): return s[2:] if s[:2] == b'0x' else s def print_func_call(ignore_first_arg=False, max_call_number=100): ''' utility function to facilitate debug, it will print input args before function call, and print return value after function call usage: @print_func_call def some_func_to_be_debu(): pass :param ignore_first_arg: whether print the first arg or not. useful when ignore the `self` parameter of an object method call ''' from functools import wraps def display(x): x = to_string(x) try: x.decode('ascii') except: return 'NON_PRINTABLE' return x local = {'call_number': 0} def inner(f): @wraps(f) def wrapper(*args, **kwargs): local['call_number'] += 1 tmp_args = args[1:] if ignore_first_arg and len(args) else args this_call_number = local['call_number'] print(('{0}#{1} args: {2}, {3}'.format( f.__name__, this_call_number, ', '.join([display(x) for x in tmp_args]), ', '.join(display(key) + '=' + to_string(value) for key, value in kwargs.items()) ))) res = f(*args, **kwargs) print(('{0}#{1} return: {2}'.format( f.__name__, this_call_number, display(res)))) if local['call_number'] > 100: raise Exception("Touch max call number!") return res return wrapper return inner def dump_state(trie): res = '' for k, v in list(trie.to_dict().items()): res += '%r:%r\n' % (encode_hex(k), encode_hex(v)) return res class Denoms(): def __init__(self): self.wei = 1 self.babbage = 10 ** 3 self.lovelace = 10 ** 6 self.shannon = 10 ** 9 self.szabo = 10 ** 12 self.finney = 10 ** 15 self.ether = 10 ** 18 self.turing = 2 ** 256 denoms = Denoms() address = Binary.fixed_length(20, allow_empty=True) int20 = BigEndianInt(20) int32 = BigEndianInt(32) int256 = BigEndianInt(256) hash32 = Binary.fixed_length(32) trie_root = Binary.fixed_length(32, allow_empty=True) class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[91m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def DEBUG(msg, *args, **kwargs): from ethereum import slogging slogging.DEBUG(msg, *args, **kwargs)
import pytest import json import ethereum.processblock as pb import ethereum.utils as utils import ethereum.testutils as testutils import ethereum.bloom as bloom import os from rlp.utils import decode_hex, encode_hex, str_to_bytes def check_testdata(data_keys, expected_keys): assert set(data_keys) == set(expected_keys), \ "test data changed, please adjust tests" @pytest.fixture(scope="module") def vm_tests_fixtures(): """ Read vm tests from fixtures fixtures/VMTests/* """ # FIXME: assert that repo is uptodate # cd fixtures; git pull origin develop; cd ..; git commit fixtures filenames = os.listdir(os.path.join(testutils.fixture_path, 'VMTests')) files = [os.path.join(testutils.fixture_path, 'VMTests', f) for f in filenames] vm_fixtures = {} try: for f, fn in zip(files, filenames): if f[-5:] == '.json': vm_fixtures[fn[:-5]] = json.load(open(f, 'r')) except IOError as e: raise IOError("Could not read vmtests.json from fixtures", "Make sure you did 'git submodule init'") return vm_fixtures # SETUP TESTS IN GLOBAL NAME SPACE def gen_func(testdata): return lambda: do_test_bloom(testdata) for filename, tests in list(vm_tests_fixtures().items()): for testname, testdata in list(tests.items()): if 'logs' not in testdata or 'log' not in testname.lower(): continue func_name = 'test_%s_%s' % (filename, testname) globals()[func_name] = gen_func(testdata['logs']) def decode_int_from_hex(x): r = utils.decode_int(decode_hex(x).lstrip(b"\x00")) return r def encode_hex_from_int(x): return encode_hex(utils.zpad(utils.int_to_big_endian(x), 256)) def do_test_bloom(test_logs): """ The logs sections is a mapping between the blooms and their corresponding logentries. Each logentry has the format: address: The address of the logentry. data: The data of the logentry. topics: The topics of the logentry, given as an array of values. """ for data in test_logs: address = data['address'] # Test via bloom b = bloom.bloom_insert(0, decode_hex(address)) for t in data['topics']: b = bloom.bloom_insert(b, decode_hex(t)) # Test via Log topics = [decode_int_from_hex(x) for x in data['topics']] log = pb.Log(decode_hex(address), topics, '') log_bloom = bloom.b64(bloom.bloom_from_list(log.bloomables())) assert encode_hex(log_bloom) == encode_hex_from_int(b) assert str_to_bytes(data['bloom']) == encode_hex(log_bloom)
holiman/pyethereum
ethereum/tests/test_bloom.py
ethereum/utils.py
''' Jottings to work out format for __function_workspace__ matrix at end of mat file. ''' import os.path import io from numpy.compat import asstr from scipy.io.matlab.mio5 import MatFile5Reader test_data_path = os.path.join(os.path.dirname(__file__), 'data') def read_minimat_vars(rdr): rdr.initialize_read() mdict = {'__globals__': []} i = 0 while not rdr.end_of_stream(): hdr, next_position = rdr.read_var_header() name = asstr(hdr.name) if name == '': name = 'var_%d' % i i += 1 res = rdr.read_var_array(hdr, process=False) rdr.mat_stream.seek(next_position) mdict[name] = res if hdr.is_global: mdict['__globals__'].append(name) return mdict def read_workspace_vars(fname): fp = open(fname, 'rb') rdr = MatFile5Reader(fp, struct_as_record=True) vars = rdr.get_variables() fws = vars['__function_workspace__'] ws_bs = io.BytesIO(fws.tostring()) ws_bs.seek(2) rdr.mat_stream = ws_bs # Guess byte order. mi = rdr.mat_stream.read(2) rdr.byte_order = mi == b'IM' and '<' or '>' rdr.mat_stream.read(4) # presumably byte padding mdict = read_minimat_vars(rdr) fp.close() return mdict def test_jottings(): # example fname = os.path.join(test_data_path, 'parabola.mat') read_workspace_vars(fname)
# this program corresponds to special.py ### Means test is not done yet # E Means test is giving error (E) # F Means test is failing (F) # EF Means test is giving error and Failing #! Means test is segfaulting # 8 Means test runs forever ### test_besselpoly ### test_mathieu_a ### test_mathieu_even_coef ### test_mathieu_odd_coef ### test_modfresnelp ### test_modfresnelm # test_pbdv_seq ### test_pbvv_seq ### test_sph_harm import itertools import platform import numpy as np from numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp, log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, float_) import pytest from pytest import raises as assert_raises from numpy.testing import (assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_approx_equal, assert_, assert_allclose, assert_array_almost_equal_nulp, suppress_warnings) from scipy import special import scipy.special._ufuncs as cephes from scipy.special import ellipk from scipy.special._testutils import with_special_errors, \ assert_func_equal, FuncData import math class TestCephes(object): def test_airy(self): cephes.airy(0) def test_airye(self): cephes.airye(0) def test_binom(self): n = np.array([0.264, 4, 5.2, 17]) k = np.array([2, 0.4, 7, 3.3]) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389, -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846], [10.92, 2.22993515861399, -0.00585728, 10.468891352063146], [136, 3.5252179590758828, 19448, 1024.5526916174495]]) assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13) # Test branches in implementation np.random.seed(1234) n = np.r_[np.arange(-7, 30), 1000*np.random.rand(30) - 500] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_2(self): # Test branches in implementation np.random.seed(1234) n = np.r_[np.logspace(1, 300, 20)] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_exact(self): @np.vectorize def binom_int(n, k): n = int(n) k = int(k) num = int(1) den = int(1) for i in range(1, k+1): num *= i + n - k den *= i return float(num/den) np.random.seed(1234) n = np.arange(1, 15) k = np.arange(0, 15) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T nk = nk[nk[:,0] >= nk[:,1]] assert_func_equal(cephes.binom, binom_int(nk[:,0], nk[:,1]), nk, atol=0, rtol=0) def test_binom_nooverflow_8346(self): # Test (binom(n, k) doesn't overflow prematurely */ dataset = [ (1000, 500, 2.70288240945436551e+299), (1002, 501, 1.08007396880791225e+300), (1004, 502, 4.31599279169058121e+300), (1006, 503, 1.72468101616263781e+301), (1008, 504, 6.89188009236419153e+301), (1010, 505, 2.75402257948335448e+302), (1012, 506, 1.10052048531923757e+303), (1014, 507, 4.39774063758732849e+303), (1016, 508, 1.75736486108312519e+304), (1018, 509, 7.02255427788423734e+304), (1020, 510, 2.80626776829962255e+305), (1022, 511, 1.12140876377061240e+306), (1024, 512, 4.48125455209897109e+306), (1026, 513, 1.79075474304149900e+307), (1028, 514, 7.15605105487789676e+307) ] dataset = np.asarray(dataset) FuncData(cephes.binom, dataset, (0, 1), 2, rtol=1e-12).check() def test_bdtr(self): assert_equal(cephes.bdtr(1,1,0.5),1.0) def test_bdtri(self): assert_equal(cephes.bdtri(1,3,0.5),0.5) def test_bdtrc(self): assert_equal(cephes.bdtrc(1,3,0.5),0.5) def test_bdtrin(self): assert_equal(cephes.bdtrin(1,0,1),5.0) def test_bdtrik(self): cephes.bdtrik(1,3,0.5) def test_bei(self): assert_equal(cephes.bei(0),0.0) def test_beip(self): assert_equal(cephes.beip(0),0.0) def test_ber(self): assert_equal(cephes.ber(0),1.0) def test_berp(self): assert_equal(cephes.berp(0),0.0) def test_besselpoly(self): assert_equal(cephes.besselpoly(0,0,0),1.0) def test_beta(self): assert_equal(cephes.beta(1,1),1.0) assert_allclose(cephes.beta(-100.3, 1e-200), cephes.gamma(1e-200)) assert_allclose(cephes.beta(0.0342, 171), 24.070498359873497, rtol=1e-13, atol=0) def test_betainc(self): assert_equal(cephes.betainc(1,1,1),1.0) assert_allclose(cephes.betainc(0.0342, 171, 1e-10), 0.55269916901806648) def test_betaln(self): assert_equal(cephes.betaln(1,1),0.0) assert_allclose(cephes.betaln(-100.3, 1e-200), cephes.gammaln(1e-200)) assert_allclose(cephes.betaln(0.0342, 170), 3.1811881124242447, rtol=1e-14, atol=0) def test_betaincinv(self): assert_equal(cephes.betaincinv(1,1,1),1.0) assert_allclose(cephes.betaincinv(0.0342, 171, 0.25), 8.4231316935498957e-21, rtol=3e-12, atol=0) def test_beta_inf(self): assert_(np.isinf(special.beta(-1, 2))) def test_btdtr(self): assert_equal(cephes.btdtr(1,1,1),1.0) def test_btdtri(self): assert_equal(cephes.btdtri(1,1,1),1.0) def test_btdtria(self): assert_equal(cephes.btdtria(1,1,1),5.0) def test_btdtrib(self): assert_equal(cephes.btdtrib(1,1,1),5.0) def test_cbrt(self): assert_approx_equal(cephes.cbrt(1),1.0) def test_chdtr(self): assert_equal(cephes.chdtr(1,0),0.0) def test_chdtrc(self): assert_equal(cephes.chdtrc(1,0),1.0) def test_chdtri(self): assert_equal(cephes.chdtri(1,1),0.0) def test_chdtriv(self): assert_equal(cephes.chdtriv(0,0),5.0) def test_chndtr(self): assert_equal(cephes.chndtr(0,1,0),0.0) # Each row holds (x, nu, lam, expected_value) # These values were computed using Wolfram Alpha with # CDF[NoncentralChiSquareDistribution[nu, lam], x] values = np.array([ [25.00, 20.0, 400, 4.1210655112396197139e-57], [25.00, 8.00, 250, 2.3988026526832425878e-29], [0.001, 8.00, 40., 5.3761806201366039084e-24], [0.010, 8.00, 40., 5.45396231055999457039e-20], [20.00, 2.00, 107, 1.39390743555819597802e-9], [22.50, 2.00, 107, 7.11803307138105870671e-9], [25.00, 2.00, 107, 3.11041244829864897313e-8], [3.000, 2.00, 1.0, 0.62064365321954362734], [350.0, 300., 10., 0.93880128006276407710], [100.0, 13.5, 10., 0.99999999650104210949], [700.0, 20.0, 400, 0.99999999925680650105], [150.0, 13.5, 10., 0.99999999999999983046], [160.0, 13.5, 10., 0.99999999999999999518], # 1.0 ]) cdf = cephes.chndtr(values[:, 0], values[:, 1], values[:, 2]) assert_allclose(cdf, values[:, 3], rtol=1e-12) assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0) assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0) assert_(np.isnan(cephes.chndtr(np.nan, 1, 2))) assert_(np.isnan(cephes.chndtr(5, np.nan, 2))) assert_(np.isnan(cephes.chndtr(5, 1, np.nan))) def test_chndtridf(self): assert_equal(cephes.chndtridf(0,0,1),5.0) def test_chndtrinc(self): assert_equal(cephes.chndtrinc(0,1,0),5.0) def test_chndtrix(self): assert_equal(cephes.chndtrix(0,1,0),0.0) def test_cosdg(self): assert_equal(cephes.cosdg(0),1.0) def test_cosm1(self): assert_equal(cephes.cosm1(0),0.0) def test_cotdg(self): assert_almost_equal(cephes.cotdg(45),1.0) def test_dawsn(self): assert_equal(cephes.dawsn(0),0.0) assert_allclose(cephes.dawsn(1.23), 0.50053727749081767) def test_diric(self): # Test behavior near multiples of 2pi. Regression test for issue # described in gh-4001. n_odd = [1, 5, 25] x = np.array(2*np.pi + 5e-5).astype(np.float32) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7) x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) x = np.array(2*np.pi + 1e-15).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) if hasattr(np, 'float128'): # No float128 available in 32-bit numpy x = np.array(2*np.pi + 1e-12).astype(np.float128) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19) n_even = [2, 4, 24] x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15) # Test at some values not near a multiple of pi x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi) octave_result = [0.872677996249965, 0.539344662916632, 0.127322003750035, -0.206011329583298] assert_almost_equal(special.diric(x, 3), octave_result, decimal=15) def test_diric_broadcasting(self): x = np.arange(5) n = np.array([1, 3, 7]) assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size)) def test_ellipe(self): assert_equal(cephes.ellipe(1),1.0) def test_ellipeinc(self): assert_equal(cephes.ellipeinc(0,1),0.0) def test_ellipj(self): cephes.ellipj(0,1) def test_ellipk(self): assert_allclose(ellipk(0), pi/2) def test_ellipkinc(self): assert_equal(cephes.ellipkinc(0,0),0.0) def test_erf(self): assert_equal(cephes.erf(0), 0.0) def test_erf_symmetry(self): x = 5.905732037710919 assert_equal(cephes.erf(x) + cephes.erf(-x), 0.0) def test_erfc(self): assert_equal(cephes.erfc(0), 1.0) def test_exp10(self): assert_approx_equal(cephes.exp10(2),100.0) def test_exp2(self): assert_equal(cephes.exp2(2),4.0) def test_expm1(self): assert_equal(cephes.expm1(0),0.0) assert_equal(cephes.expm1(np.inf), np.inf) assert_equal(cephes.expm1(-np.inf), -1) assert_equal(cephes.expm1(np.nan), np.nan) def test_expm1_complex(self): expm1 = cephes.expm1 assert_equal(expm1(0 + 0j), 0 + 0j) assert_equal(expm1(complex(np.inf, 0)), complex(np.inf, 0)) assert_equal(expm1(complex(np.inf, 1)), complex(np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 2)), complex(-np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 4)), complex(-np.inf, -np.inf)) assert_equal(expm1(complex(np.inf, 5)), complex(np.inf, -np.inf)) assert_equal(expm1(complex(1, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(0, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.inf, np.inf)), complex(np.inf, np.nan)) assert_equal(expm1(complex(-np.inf, np.inf)), complex(-1, 0)) assert_equal(expm1(complex(-np.inf, np.nan)), complex(-1, 0)) assert_equal(expm1(complex(np.inf, np.nan)), complex(np.inf, np.nan)) assert_equal(expm1(complex(0, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(1, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, 1)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, np.nan)), complex(np.nan, np.nan)) @pytest.mark.xfail(reason='The real part of expm1(z) bad at these points') def test_expm1_complex_hard(self): # The real part of this function is difficult to evaluate when # z.real = -log(cos(z.imag)). y = np.array([0.1, 0.2, 0.3, 5, 11, 20]) x = -np.log(np.cos(y)) z = x + 1j*y # evaluate using mpmath.expm1 with dps=1000 expected = np.array([-5.5507901846769623e-17+0.10033467208545054j, 2.4289354732893695e-18+0.20271003550867248j, 4.5235500262585768e-17+0.30933624960962319j, 7.8234305217489006e-17-3.3805150062465863j, -1.3685191953697676e-16-225.95084645419513j, 8.7175620481291045e-17+2.2371609442247422j]) found = cephes.expm1(z) # this passes. assert_array_almost_equal_nulp(found.imag, expected.imag, 3) # this fails. assert_array_almost_equal_nulp(found.real, expected.real, 20) def test_fdtr(self): assert_equal(cephes.fdtr(1, 1, 0), 0.0) # Computed using Wolfram Alpha: CDF[FRatioDistribution[1e-6, 5], 10] assert_allclose(cephes.fdtr(1e-6, 5, 10), 0.9999940790193488, rtol=1e-12) def test_fdtrc(self): assert_equal(cephes.fdtrc(1, 1, 0), 1.0) # Computed using Wolfram Alpha: # 1 - CDF[FRatioDistribution[2, 1/10], 1e10] assert_allclose(cephes.fdtrc(2, 0.1, 1e10), 0.27223784621293512, rtol=1e-12) def test_fdtri(self): assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]), array([0.9937365, 1.00630298]), rtol=1e-6) # From Wolfram Alpha: # CDF[FRatioDistribution[1/10, 1], 3] = 0.8756751669632105666874... p = 0.8756751669632105666874 assert_allclose(cephes.fdtri(0.1, 1, p), 3, rtol=1e-12) @pytest.mark.xfail(reason='Returns nan on i686.') def test_fdtri_mysterious_failure(self): assert_allclose(cephes.fdtri(1, 1, 0.5), 1) def test_fdtridfd(self): assert_equal(cephes.fdtridfd(1,0,0),5.0) def test_fresnel(self): assert_equal(cephes.fresnel(0),(0.0,0.0)) def test_gamma(self): assert_equal(cephes.gamma(5),24.0) def test_gammainccinv(self): assert_equal(cephes.gammainccinv(5,1),0.0) def test_gammaln(self): cephes.gammaln(10) def test_gammasgn(self): vals = np.array([-4, -3.5, -2.3, 1, 4.2], np.float64) assert_array_equal(cephes.gammasgn(vals), np.sign(cephes.rgamma(vals))) def test_gdtr(self): assert_equal(cephes.gdtr(1,1,0),0.0) def test_gdtr_inf(self): assert_equal(cephes.gdtr(1,1,np.inf),1.0) def test_gdtrc(self): assert_equal(cephes.gdtrc(1,1,0),1.0) def test_gdtria(self): assert_equal(cephes.gdtria(0,1,1),0.0) def test_gdtrib(self): cephes.gdtrib(1,0,1) # assert_equal(cephes.gdtrib(1,0,1),5.0) def test_gdtrix(self): cephes.gdtrix(1,1,.1) def test_hankel1(self): cephes.hankel1(1,1) def test_hankel1e(self): cephes.hankel1e(1,1) def test_hankel2(self): cephes.hankel2(1,1) def test_hankel2e(self): cephes.hankel2e(1,1) def test_hyp1f1(self): assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) cephes.hyp1f1(1,1,1) def test_hyp2f1(self): assert_equal(cephes.hyp2f1(1,1,1,0),1.0) def test_i0(self): assert_equal(cephes.i0(0),1.0) def test_i0e(self): assert_equal(cephes.i0e(0),1.0) def test_i1(self): assert_equal(cephes.i1(0),0.0) def test_i1e(self): assert_equal(cephes.i1e(0),0.0) def test_it2i0k0(self): cephes.it2i0k0(1) def test_it2j0y0(self): cephes.it2j0y0(1) def test_it2struve0(self): cephes.it2struve0(1) def test_itairy(self): cephes.itairy(1) def test_iti0k0(self): assert_equal(cephes.iti0k0(0),(0.0,0.0)) def test_itj0y0(self): assert_equal(cephes.itj0y0(0),(0.0,0.0)) def test_itmodstruve0(self): assert_equal(cephes.itmodstruve0(0),0.0) def test_itstruve0(self): assert_equal(cephes.itstruve0(0),0.0) def test_iv(self): assert_equal(cephes.iv(1,0),0.0) def _check_ive(self): assert_equal(cephes.ive(1,0),0.0) def test_j0(self): assert_equal(cephes.j0(0),1.0) def test_j1(self): assert_equal(cephes.j1(0),0.0) def test_jn(self): assert_equal(cephes.jn(0,0),1.0) def test_jv(self): assert_equal(cephes.jv(0,0),1.0) def _check_jve(self): assert_equal(cephes.jve(0,0),1.0) def test_k0(self): cephes.k0(2) def test_k0e(self): cephes.k0e(2) def test_k1(self): cephes.k1(2) def test_k1e(self): cephes.k1e(2) def test_kei(self): cephes.kei(2) def test_keip(self): assert_equal(cephes.keip(0),0.0) def test_ker(self): cephes.ker(2) def test_kerp(self): cephes.kerp(2) def _check_kelvin(self): cephes.kelvin(2) def test_kn(self): cephes.kn(1,1) def test_kolmogi(self): assert_equal(cephes.kolmogi(1),0.0) assert_(np.isnan(cephes.kolmogi(np.nan))) def test_kolmogorov(self): assert_equal(cephes.kolmogorov(0), 1.0) def test_kolmogp(self): assert_equal(cephes._kolmogp(0), -0.0) def test_kolmogc(self): assert_equal(cephes._kolmogc(0), 0.0) def test_kolmogci(self): assert_equal(cephes._kolmogci(0), 0.0) assert_(np.isnan(cephes._kolmogci(np.nan))) def _check_kv(self): cephes.kv(1,1) def _check_kve(self): cephes.kve(1,1) def test_log1p(self): log1p = cephes.log1p assert_equal(log1p(0), 0.0) assert_equal(log1p(-1), -np.inf) assert_equal(log1p(-2), np.nan) assert_equal(log1p(np.inf), np.inf) def test_log1p_complex(self): log1p = cephes.log1p c = complex assert_equal(log1p(0 + 0j), 0 + 0j) assert_equal(log1p(c(-1, 0)), c(-np.inf, 0)) with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in multiply") assert_allclose(log1p(c(1, np.inf)), c(np.inf, np.pi/2)) assert_equal(log1p(c(1, np.nan)), c(np.nan, np.nan)) assert_allclose(log1p(c(-np.inf, 1)), c(np.inf, np.pi)) assert_equal(log1p(c(np.inf, 1)), c(np.inf, 0)) assert_allclose(log1p(c(-np.inf, np.inf)), c(np.inf, 3*np.pi/4)) assert_allclose(log1p(c(np.inf, np.inf)), c(np.inf, np.pi/4)) assert_equal(log1p(c(np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(-np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, np.inf)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, 1)), c(np.nan, np.nan)) assert_equal(log1p(c(np.nan, np.nan)), c(np.nan, np.nan)) def test_lpmv(self): assert_equal(cephes.lpmv(0,0,1),1.0) def test_mathieu_a(self): assert_equal(cephes.mathieu_a(1,0),1.0) def test_mathieu_b(self): assert_equal(cephes.mathieu_b(1,0),1.0) def test_mathieu_cem(self): assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) # Test AMS 20.2.27 @np.vectorize def ce_smallq(m, q, z): z *= np.pi/180 if m == 0: return 2**(-0.5) * (1 - .5*q*cos(2*z)) # + O(q^2) elif m == 1: return cos(z) - q/8 * cos(3*z) # + O(q^2) elif m == 2: return cos(2*z) - q*(cos(4*z)/12 - 1/4) # + O(q^2) else: return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(0, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0], ce_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_sem(self): assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) # Test AMS 20.2.27 @np.vectorize def se_smallq(m, q, z): z *= np.pi/180 if m == 1: return sin(z) - q/8 * sin(3*z) # + O(q^2) elif m == 2: return sin(2*z) - q*sin(4*z)/12 # + O(q^2) else: return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(1, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0], se_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_modcem1(self): assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) def test_mathieu_modcem2(self): cephes.mathieu_modcem2(1,1,1) # Test reflection relation AMS 20.6.19 m = np.arange(0, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modcem2(m, q, -z)[0] fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0] y2 = -cephes.mathieu_modcem2(m, q, z)[0] - 2*fr*cephes.mathieu_modcem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_modsem1(self): assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) def test_mathieu_modsem2(self): cephes.mathieu_modsem2(1,1,1) # Test reflection relation AMS 20.6.20 m = np.arange(1, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modsem2(m, q, -z)[0] fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1] y2 = cephes.mathieu_modsem2(m, q, z)[0] - 2*fr*cephes.mathieu_modsem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_overflow(self): # Check that these return NaNs instead of causing a SEGV assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan)) def test_mathieu_ticket_1847(self): # Regression test --- this call had some out-of-bounds access # and could return nan occasionally for k in range(60): v = cephes.mathieu_modsem2(2, 100, -1) # Values from ACM TOMS 804 (derivate by numerical differentiation) assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10) assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4) def test_modfresnelm(self): cephes.modfresnelm(0) def test_modfresnelp(self): cephes.modfresnelp(0) def _check_modstruve(self): assert_equal(cephes.modstruve(1,0),0.0) def test_nbdtr(self): assert_equal(cephes.nbdtr(1,1,1),1.0) def test_nbdtrc(self): assert_equal(cephes.nbdtrc(1,1,1),0.0) def test_nbdtri(self): assert_equal(cephes.nbdtri(1,1,1),1.0) def __check_nbdtrik(self): cephes.nbdtrik(1,.4,.5) def test_nbdtrin(self): assert_equal(cephes.nbdtrin(1,0,0),5.0) def test_ncfdtr(self): assert_equal(cephes.ncfdtr(1,1,1,0),0.0) def test_ncfdtri(self): assert_equal(cephes.ncfdtri(1, 1, 1, 0), 0.0) f = [0.5, 1, 1.5] p = cephes.ncfdtr(2, 3, 1.5, f) assert_allclose(cephes.ncfdtri(2, 3, 1.5, p), f) def test_ncfdtridfd(self): dfd = [1, 2, 3] p = cephes.ncfdtr(2, dfd, 0.25, 15) assert_allclose(cephes.ncfdtridfd(2, p, 0.25, 15), dfd) def test_ncfdtridfn(self): dfn = [0.1, 1, 2, 3, 1e4] p = cephes.ncfdtr(dfn, 2, 0.25, 15) assert_allclose(cephes.ncfdtridfn(p, 2, 0.25, 15), dfn, rtol=1e-5) def test_ncfdtrinc(self): nc = [0.5, 1.5, 2.0] p = cephes.ncfdtr(2, 3, nc, 15) assert_allclose(cephes.ncfdtrinc(2, 3, p, 15), nc) def test_nctdtr(self): assert_equal(cephes.nctdtr(1,0,0),0.5) assert_equal(cephes.nctdtr(9, 65536, 45), 0.0) assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5) assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.))) assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.) assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.))) assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.))) assert_(np.isnan(cephes.nctdtr(2., 1., np.nan))) def __check_nctdtridf(self): cephes.nctdtridf(1,0.5,0) def test_nctdtrinc(self): cephes.nctdtrinc(1,0,0) def test_nctdtrit(self): cephes.nctdtrit(.1,0.2,.5) def test_nrdtrimn(self): assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) def test_nrdtrisd(self): assert_allclose(cephes.nrdtrisd(0.5,0.5,0.5), 0.0, atol=0, rtol=0) def test_obl_ang1(self): cephes.obl_ang1(1,1,1,0) def test_obl_ang1_cv(self): result = cephes.obl_ang1_cv(1,1,1,1,0) assert_almost_equal(result[0],1.0) assert_almost_equal(result[1],0.0) def _check_obl_cv(self): assert_equal(cephes.obl_cv(1,1,0),2.0) def test_obl_rad1(self): cephes.obl_rad1(1,1,1,0) def test_obl_rad1_cv(self): cephes.obl_rad1_cv(1,1,1,1,0) def test_obl_rad2(self): cephes.obl_rad2(1,1,1,0) def test_obl_rad2_cv(self): cephes.obl_rad2_cv(1,1,1,1,0) def test_pbdv(self): assert_equal(cephes.pbdv(1,0),(0.0,1.0)) def test_pbvv(self): cephes.pbvv(1,0) def test_pbwa(self): cephes.pbwa(1,0) def test_pdtr(self): val = cephes.pdtr(0, 1) assert_almost_equal(val, np.exp(-1)) # Edge case: m = 0. val = cephes.pdtr([0, 1, 2], 0) assert_array_equal(val, [1, 1, 1]) def test_pdtrc(self): val = cephes.pdtrc(0, 1) assert_almost_equal(val, 1 - np.exp(-1)) # Edge case: m = 0. val = cephes.pdtrc([0, 1, 2], 0.0) assert_array_equal(val, [0, 0, 0]) def test_pdtri(self): with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") cephes.pdtri(0.5,0.5) def test_pdtrik(self): k = cephes.pdtrik(0.5, 1) assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5) # Edge case: m = 0 or very small. k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6]) assert_array_equal(k, np.zeros((3, 3))) def test_pro_ang1(self): cephes.pro_ang1(1,1,1,0) def test_pro_ang1_cv(self): assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), array((1.0,0.0))) def _check_pro_cv(self): assert_equal(cephes.pro_cv(1,1,0),2.0) def test_pro_rad1(self): cephes.pro_rad1(1,1,1,0.1) def test_pro_rad1_cv(self): cephes.pro_rad1_cv(1,1,1,1,0) def test_pro_rad2(self): cephes.pro_rad2(1,1,1,0) def test_pro_rad2_cv(self): cephes.pro_rad2_cv(1,1,1,1,0) def test_psi(self): cephes.psi(1) def test_radian(self): assert_equal(cephes.radian(0,0,0),0) def test_rgamma(self): assert_equal(cephes.rgamma(1),1.0) def test_round(self): assert_equal(cephes.round(3.4),3.0) assert_equal(cephes.round(-3.4),-3.0) assert_equal(cephes.round(3.6),4.0) assert_equal(cephes.round(-3.6),-4.0) assert_equal(cephes.round(3.5),4.0) assert_equal(cephes.round(-3.5),-4.0) def test_shichi(self): cephes.shichi(1) def test_sici(self): cephes.sici(1) s, c = cephes.sici(np.inf) assert_almost_equal(s, np.pi * 0.5) assert_almost_equal(c, 0) s, c = cephes.sici(-np.inf) assert_almost_equal(s, -np.pi * 0.5) assert_(np.isnan(c), "cosine integral(-inf) is not nan") def test_sindg(self): assert_equal(cephes.sindg(90),1.0) def test_smirnov(self): assert_equal(cephes.smirnov(1,.1),0.9) assert_(np.isnan(cephes.smirnov(1,np.nan))) def test_smirnovp(self): assert_equal(cephes._smirnovp(1, .1), -1) assert_equal(cephes._smirnovp(2, 0.75), -2*(0.25)**(2-1)) assert_equal(cephes._smirnovp(3, 0.75), -3*(0.25)**(3-1)) assert_(np.isnan(cephes._smirnovp(1, np.nan))) def test_smirnovc(self): assert_equal(cephes._smirnovc(1,.1),0.1) assert_(np.isnan(cephes._smirnovc(1,np.nan))) x10 = np.linspace(0, 1, 11, endpoint=True) assert_almost_equal(cephes._smirnovc(3, x10), 1-cephes.smirnov(3, x10)) x4 = np.linspace(0, 1, 5, endpoint=True) assert_almost_equal(cephes._smirnovc(4, x4), 1-cephes.smirnov(4, x4)) def test_smirnovi(self): assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) assert_(np.isnan(cephes.smirnovi(1,np.nan))) def test_smirnovci(self): assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.4)),0.4) assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.6)),0.6) assert_(np.isnan(cephes._smirnovci(1,np.nan))) def test_spence(self): assert_equal(cephes.spence(1),0.0) def test_stdtr(self): assert_equal(cephes.stdtr(1,0),0.5) assert_almost_equal(cephes.stdtr(1,1), 0.75) assert_almost_equal(cephes.stdtr(1,2), 0.852416382349) def test_stdtridf(self): cephes.stdtridf(0.7,1) def test_stdtrit(self): cephes.stdtrit(1,0.7) def test_struve(self): assert_equal(cephes.struve(0,0),0.0) def test_tandg(self): assert_equal(cephes.tandg(45),1.0) def test_tklmbda(self): assert_almost_equal(cephes.tklmbda(1,1),1.0) def test_y0(self): cephes.y0(1) def test_y1(self): cephes.y1(1) def test_yn(self): cephes.yn(1,1) def test_yv(self): cephes.yv(1,1) def _check_yve(self): cephes.yve(1,1) def test_wofz(self): z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.), complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.), complex(-0.0000000234545,1.1234), complex(-3.,5.1), complex(-53,30.1), complex(0.0,0.12345), complex(11,1), complex(-22,-2), complex(9,-28), complex(21,-33), complex(1e5,1e5), complex(1e14,1e14) ] w = [ complex(-3.78270245518980507452677445620103199303131110e-7, 0.000903861276433172057331093754199933411710053155), complex(0.1764906227004816847297495349730234591778719532788, -0.02146550539468457616788719893991501311573031095617), complex(0.2410250715772692146133539023007113781272362309451, 0.06087579663428089745895459735240964093522265589350), complex(0.30474420525691259245713884106959496013413834051768, -0.20821893820283162728743734725471561394145872072738), complex(7.317131068972378096865595229600561710140617977e34, 8.321873499714402777186848353320412813066170427e34), complex(0.0615698507236323685519612934241429530190806818395, -0.00676005783716575013073036218018565206070072304635), complex(0.3960793007699874918961319170187598400134746631, -5.593152259116644920546186222529802777409274656e-9), complex(0.08217199226739447943295069917990417630675021771804, -0.04701291087643609891018366143118110965272615832184), complex(0.00457246000350281640952328010227885008541748668738, -0.00804900791411691821818731763401840373998654987934), complex(0.8746342859608052666092782112565360755791467973338452, 0.), complex(0.00468190164965444174367477874864366058339647648741, 0.0510735563901306197993676329845149741675029197050), complex(-0.0023193175200187620902125853834909543869428763219, -0.025460054739731556004902057663500272721780776336), complex(9.11463368405637174660562096516414499772662584e304, 3.97101807145263333769664875189354358563218932e305), complex(-4.4927207857715598976165541011143706155432296e281, -2.8019591213423077494444700357168707775769028e281), complex(2.820947917809305132678577516325951485807107151e-6, 2.820947917668257736791638444590253942253354058e-6), complex(2.82094791773878143474039725787438662716372268e-15, 2.82094791773878143474039725773333923127678361e-15) ] assert_func_equal(cephes.wofz, w, z, rtol=1e-13) class TestAiry(object): def test_airy(self): # This tests the airy function to ensure 8 place accuracy in computation x = special.airy(.99) assert_array_almost_equal(x,array([0.13689066,-0.16050153,1.19815925,0.92046818]),8) x = special.airy(.41) assert_array_almost_equal(x,array([0.25238916,-.23480512,0.80686202,0.51053919]),8) x = special.airy(-.36) assert_array_almost_equal(x,array([0.44508477,-0.23186773,0.44939534,0.48105354]),8) def test_airye(self): a = special.airye(0.01) b = special.airy(0.01) b1 = [None]*4 for n in range(2): b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01)) for n in range(2,4): b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) assert_array_almost_equal(a,b1,6) def test_bi_zeros(self): bi = special.bi_zeros(2) bia = (array([-1.17371322, -3.2710930]), array([-2.29443968, -4.07315509]), array([-0.45494438, 0.39652284]), array([0.60195789, -0.76031014])) assert_array_almost_equal(bi,bia,4) bi = special.bi_zeros(5) assert_array_almost_equal(bi[0],array([-1.173713222709127, -3.271093302836352, -4.830737841662016, -6.169852128310251, -7.376762079367764]),11) assert_array_almost_equal(bi[1],array([-2.294439682614122, -4.073155089071828, -5.512395729663599, -6.781294445990305, -7.940178689168587]),10) assert_array_almost_equal(bi[2],array([-0.454944383639657, 0.396522836094465, -0.367969161486959, 0.349499116831805, -0.336026240133662]),11) assert_array_almost_equal(bi[3],array([0.601957887976239, -0.760310141492801, 0.836991012619261, -0.88947990142654, 0.929983638568022]),10) def test_ai_zeros(self): ai = special.ai_zeros(1) assert_array_almost_equal(ai,(array([-2.33810741]), array([-1.01879297]), array([0.5357]), array([0.7012])),4) def test_ai_zeros_big(self): z, zp, ai_zpx, aip_zx = special.ai_zeros(50000) ai_z, aip_z, _, _ = special.airy(z) ai_zp, aip_zp, _, _ = special.airy(zp) ai_envelope = 1/abs(z)**(1./4) aip_envelope = abs(zp)**(1./4) # Check values assert_allclose(ai_zpx, ai_zp, rtol=1e-10) assert_allclose(aip_zx, aip_z, rtol=1e-10) # Check they are zeros assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0) assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.1 assert_allclose(z[:6], [-2.3381074105, -4.0879494441, -5.5205598281, -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10) assert_allclose(zp[:6], [-1.0187929716, -3.2481975822, -4.8200992112, -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10) def test_bi_zeros_big(self): z, zp, bi_zpx, bip_zx = special.bi_zeros(50000) _, _, bi_z, bip_z = special.airy(z) _, _, bi_zp, bip_zp = special.airy(zp) bi_envelope = 1/abs(z)**(1./4) bip_envelope = abs(zp)**(1./4) # Check values assert_allclose(bi_zpx, bi_zp, rtol=1e-10) assert_allclose(bip_zx, bip_z, rtol=1e-10) # Check they are zeros assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0) assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.2 assert_allclose(z[:6], [-1.1737132227, -3.2710933028, -4.8307378417, -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10) assert_allclose(zp[:6], [-2.2944396826, -4.0731550891, -5.5123957297, -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10) class TestAssocLaguerre(object): def test_assoc_laguerre(self): a1 = special.genlaguerre(11,1) a2 = special.assoc_laguerre(.2,11,1) assert_array_almost_equal(a2,a1(.2),8) a2 = special.assoc_laguerre(1,11,1) assert_array_almost_equal(a2,a1(1),8) class TestBesselpoly(object): def test_besselpoly(self): pass class TestKelvin(object): def test_bei(self): mbei = special.bei(2) assert_almost_equal(mbei, 0.9722916273066613,5) # this may not be exact def test_beip(self): mbeip = special.beip(2) assert_almost_equal(mbeip,0.91701361338403631,5) # this may not be exact def test_ber(self): mber = special.ber(2) assert_almost_equal(mber,0.75173418271380821,5) # this may not be exact def test_berp(self): mberp = special.berp(2) assert_almost_equal(mberp,-0.49306712470943909,5) # this may not be exact def test_bei_zeros(self): # Abramowitz & Stegun, Table 9.12 bi = special.bei_zeros(5) assert_array_almost_equal(bi,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) def test_beip_zeros(self): bip = special.beip_zeros(5) assert_array_almost_equal(bip,array([3.772673304934953, 8.280987849760042, 12.742147523633703, 17.193431752512542, 21.641143941167325]),8) def test_ber_zeros(self): ber = special.ber_zeros(5) assert_array_almost_equal(ber,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) def test_berp_zeros(self): brp = special.berp_zeros(5) assert_array_almost_equal(brp,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) def test_kelvin(self): mkelv = special.kelvin(2) assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j, special.ker(2) + special.kei(2)*1j, special.berp(2) + special.beip(2)*1j, special.kerp(2) + special.keip(2)*1j),8) def test_kei(self): mkei = special.kei(2) assert_almost_equal(mkei,-0.20240006776470432,5) def test_keip(self): mkeip = special.keip(2) assert_almost_equal(mkeip,0.21980790991960536,5) def test_ker(self): mker = special.ker(2) assert_almost_equal(mker,-0.041664513991509472,5) def test_kerp(self): mkerp = special.kerp(2) assert_almost_equal(mkerp,-0.10660096588105264,5) def test_kei_zeros(self): kei = special.kei_zeros(5) assert_array_almost_equal(kei,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) def test_keip_zeros(self): keip = special.keip_zeros(5) assert_array_almost_equal(keip,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) # numbers come from 9.9 of A&S pg. 381 def test_kelvin_zeros(self): tmp = special.kelvin_zeros(5) berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp assert_array_almost_equal(berz,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) assert_array_almost_equal(beiz,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) assert_array_almost_equal(kerz,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44382]),4) assert_array_almost_equal(keiz,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) assert_array_almost_equal(berpz,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) assert_array_almost_equal(beipz,array([3.77267, # table from 1927 had 3.77320 # but this is more accurate 8.28099, 12.74215, 17.19343, 21.64114]),4) assert_array_almost_equal(kerpz,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) assert_array_almost_equal(keipz,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) def test_ker_zeros(self): ker = special.ker_zeros(5) assert_array_almost_equal(ker,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44381]),4) def test_kerp_zeros(self): kerp = special.kerp_zeros(5) assert_array_almost_equal(kerp,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) class TestBernoulli(object): def test_bernoulli(self): brn = special.bernoulli(5) assert_array_almost_equal(brn,array([1.0000, -0.5000, 0.1667, 0.0000, -0.0333, 0.0000]),4) class TestBeta(object): def test_beta(self): bet = special.beta(2,4) betg = (special.gamma(2)*special.gamma(4))/special.gamma(6) assert_almost_equal(bet,betg,8) def test_betaln(self): betln = special.betaln(2,4) bet = log(abs(special.beta(2,4))) assert_almost_equal(betln,bet,8) def test_betainc(self): btinc = special.betainc(1,1,.2) assert_almost_equal(btinc,0.2,8) def test_betaincinv(self): y = special.betaincinv(2,4,.5) comp = special.betainc(2,4,y) assert_almost_equal(comp,.5,5) class TestCombinatorics(object): def test_comb(self): assert_array_almost_equal(special.comb([10, 10], [3, 4]), [120., 210.]) assert_almost_equal(special.comb(10, 3), 120.) assert_equal(special.comb(10, 3, exact=True), 120) assert_equal(special.comb(10, 3, exact=True, repetition=True), 220) assert_allclose([special.comb(20, k, exact=True) for k in range(21)], special.comb(20, list(range(21))), atol=1e-15) ii = np.iinfo(int).max + 1 assert_equal(special.comb(ii, ii-1, exact=True), ii) expected = 100891344545564193334812497256 assert_equal(special.comb(100, 50, exact=True), expected) def test_comb_with_np_int64(self): n = 70 k = 30 np_n = np.int64(n) np_k = np.int64(k) assert_equal(special.comb(np_n, np_k, exact=True), special.comb(n, k, exact=True)) def test_comb_zeros(self): assert_equal(special.comb(2, 3, exact=True), 0) assert_equal(special.comb(-1, 3, exact=True), 0) assert_equal(special.comb(2, -1, exact=True), 0) assert_equal(special.comb(2, -1, exact=False), 0) assert_array_almost_equal(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 120.]) def test_perm(self): assert_array_almost_equal(special.perm([10, 10], [3, 4]), [720., 5040.]) assert_almost_equal(special.perm(10, 3), 720.) assert_equal(special.perm(10, 3, exact=True), 720) def test_perm_zeros(self): assert_equal(special.perm(2, 3, exact=True), 0) assert_equal(special.perm(-1, 3, exact=True), 0) assert_equal(special.perm(2, -1, exact=True), 0) assert_equal(special.perm(2, -1, exact=False), 0) assert_array_almost_equal(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 720.]) class TestTrigonometric(object): def test_cbrt(self): cb = special.cbrt(27) cbrl = 27**(1.0/3.0) assert_approx_equal(cb,cbrl) def test_cbrtmore(self): cb1 = special.cbrt(27.9) cbrl1 = 27.9**(1.0/3.0) assert_almost_equal(cb1,cbrl1,8) def test_cosdg(self): cdg = special.cosdg(90) cdgrl = cos(pi/2.0) assert_almost_equal(cdg,cdgrl,8) def test_cosdgmore(self): cdgm = special.cosdg(30) cdgmrl = cos(pi/6.0) assert_almost_equal(cdgm,cdgmrl,8) def test_cosm1(self): cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10)) csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) assert_array_almost_equal(cs,csrl,8) def test_cotdg(self): ct = special.cotdg(30) ctrl = tan(pi/6.0)**(-1) assert_almost_equal(ct,ctrl,8) def test_cotdgmore(self): ct1 = special.cotdg(45) ctrl1 = tan(pi/4.0)**(-1) assert_almost_equal(ct1,ctrl1,8) def test_specialpoints(self): assert_almost_equal(special.cotdg(45), 1.0, 14) assert_almost_equal(special.cotdg(-45), -1.0, 14) assert_almost_equal(special.cotdg(90), 0.0, 14) assert_almost_equal(special.cotdg(-90), 0.0, 14) assert_almost_equal(special.cotdg(135), -1.0, 14) assert_almost_equal(special.cotdg(-135), 1.0, 14) assert_almost_equal(special.cotdg(225), 1.0, 14) assert_almost_equal(special.cotdg(-225), -1.0, 14) assert_almost_equal(special.cotdg(270), 0.0, 14) assert_almost_equal(special.cotdg(-270), 0.0, 14) assert_almost_equal(special.cotdg(315), -1.0, 14) assert_almost_equal(special.cotdg(-315), 1.0, 14) assert_almost_equal(special.cotdg(765), 1.0, 14) def test_sinc(self): # the sinc implementation and more extensive sinc tests are in numpy assert_array_equal(special.sinc([0]), 1) assert_equal(special.sinc(0.0), 1.0) def test_sindg(self): sn = special.sindg(90) assert_equal(sn,1.0) def test_sindgmore(self): snm = special.sindg(30) snmrl = sin(pi/6.0) assert_almost_equal(snm,snmrl,8) snm1 = special.sindg(45) snmrl1 = sin(pi/4.0) assert_almost_equal(snm1,snmrl1,8) class TestTandg(object): def test_tandg(self): tn = special.tandg(30) tnrl = tan(pi/6.0) assert_almost_equal(tn,tnrl,8) def test_tandgmore(self): tnm = special.tandg(45) tnmrl = tan(pi/4.0) assert_almost_equal(tnm,tnmrl,8) tnm1 = special.tandg(60) tnmrl1 = tan(pi/3.0) assert_almost_equal(tnm1,tnmrl1,8) def test_specialpoints(self): assert_almost_equal(special.tandg(0), 0.0, 14) assert_almost_equal(special.tandg(45), 1.0, 14) assert_almost_equal(special.tandg(-45), -1.0, 14) assert_almost_equal(special.tandg(135), -1.0, 14) assert_almost_equal(special.tandg(-135), 1.0, 14) assert_almost_equal(special.tandg(180), 0.0, 14) assert_almost_equal(special.tandg(-180), 0.0, 14) assert_almost_equal(special.tandg(225), 1.0, 14) assert_almost_equal(special.tandg(-225), -1.0, 14) assert_almost_equal(special.tandg(315), -1.0, 14) assert_almost_equal(special.tandg(-315), 1.0, 14) class TestEllip(object): def test_ellipj_nan(self): """Regression test for #912.""" special.ellipj(0.5, np.nan) def test_ellipj(self): el = special.ellipj(0.2,0) rel = [sin(0.2),cos(0.2),1.0,0.20] assert_array_almost_equal(el,rel,13) def test_ellipk(self): elk = special.ellipk(.2) assert_almost_equal(elk,1.659623598610528,11) assert_equal(special.ellipkm1(0.0), np.inf) assert_equal(special.ellipkm1(1.0), pi/2) assert_equal(special.ellipkm1(np.inf), 0.0) assert_equal(special.ellipkm1(np.nan), np.nan) assert_equal(special.ellipkm1(-1), np.nan) assert_allclose(special.ellipk(-10), 0.7908718902387385) def test_ellipkinc(self): elkinc = special.ellipkinc(pi/2,.2) elk = special.ellipk(0.2) assert_almost_equal(elkinc,elk,15) alpha = 20*pi/180 phi = 45*pi/180 m = sin(alpha)**2 elkinc = special.ellipkinc(phi,m) assert_almost_equal(elkinc,0.79398143,8) # From pg. 614 of A & S assert_equal(special.ellipkinc(pi/2, 0.0), pi/2) assert_equal(special.ellipkinc(pi/2, 1.0), np.inf) assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0) assert_equal(special.ellipkinc(pi/2, np.nan), np.nan) assert_equal(special.ellipkinc(pi/2, 2), np.nan) assert_equal(special.ellipkinc(0, 0.5), 0.0) assert_equal(special.ellipkinc(np.inf, 0.5), np.inf) assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipkinc(np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.nan, 0.5), np.nan) assert_equal(special.ellipkinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14) assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946) def test_ellipkinc_2(self): # Regression test for gh-3550 # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipkinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 1.0259330100195334), 1) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipkinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 5.1296650500976675), 2) def test_ellipkinc_singular(self): # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2) xlog = np.logspace(-300, -17, 25) xlin = np.linspace(1e-17, 0.1, 25) xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False) assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)), rtol=1e14) assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)), rtol=1e14) assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)), rtol=1e14) assert_equal(special.ellipkinc(np.pi/2, 1), np.inf) assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)), rtol=1e14) assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf) def test_ellipe(self): ele = special.ellipe(.2) assert_almost_equal(ele,1.4890350580958529,8) assert_equal(special.ellipe(0.0), pi/2) assert_equal(special.ellipe(1.0), 1.0) assert_equal(special.ellipe(-np.inf), np.inf) assert_equal(special.ellipe(np.nan), np.nan) assert_equal(special.ellipe(2), np.nan) assert_allclose(special.ellipe(-10), 3.6391380384177689) def test_ellipeinc(self): eleinc = special.ellipeinc(pi/2,.2) ele = special.ellipe(0.2) assert_almost_equal(eleinc,ele,14) # pg 617 of A & S alpha, phi = 52*pi/180,35*pi/180 m = sin(alpha)**2 eleinc = special.ellipeinc(phi,m) assert_almost_equal(eleinc, 0.58823065, 8) assert_equal(special.ellipeinc(pi/2, 0.0), pi/2) assert_equal(special.ellipeinc(pi/2, 1.0), 1.0) assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf) assert_equal(special.ellipeinc(pi/2, np.nan), np.nan) assert_equal(special.ellipeinc(pi/2, 2), np.nan) assert_equal(special.ellipeinc(0, 0.5), 0.0) assert_equal(special.ellipeinc(np.inf, 0.5), np.inf) assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf) assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf) assert_equal(special.ellipeinc(np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(np.nan, 0.5), np.nan) assert_equal(special.ellipeinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876) def test_ellipeinc_2(self): # Regression test for gh-3550 # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipeinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 0.84442884574781019), 2) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipeinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 3.3471442287390509), 4) class TestErf(object): def test_erf(self): er = special.erf(.25) assert_almost_equal(er,0.2763263902,8) def test_erf_zeros(self): erz = special.erf_zeros(5) erzr = array([1.45061616+1.88094300j, 2.24465928+2.61657514j, 2.83974105+3.17562810j, 3.33546074+3.64617438j, 3.76900557+4.06069723j]) assert_array_almost_equal(erz,erzr,4) def _check_variant_func(self, func, other_func, rtol, atol=0): np.random.seed(1234) n = 10000 x = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) y = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) z = x + 1j*y old_errors = np.seterr(all='ignore') try: w = other_func(z) w_real = other_func(x).real mask = np.isfinite(w) w = w[mask] z = z[mask] mask = np.isfinite(w_real) w_real = w_real[mask] x = x[mask] # test both real and complex variants assert_func_equal(func, w, z, rtol=rtol, atol=atol) assert_func_equal(func, w_real, x, rtol=rtol, atol=atol) finally: np.seterr(**old_errors) def test_erfc_consistent(self): self._check_variant_func( cephes.erfc, lambda z: 1 - cephes.erf(z), rtol=1e-12, atol=1e-14 # <- the test function loses precision ) def test_erfcx_consistent(self): self._check_variant_func( cephes.erfcx, lambda z: np.exp(z*z) * cephes.erfc(z), rtol=1e-12 ) def test_erfi_consistent(self): self._check_variant_func( cephes.erfi, lambda z: -1j * cephes.erf(1j*z), rtol=1e-12 ) def test_dawsn_consistent(self): self._check_variant_func( cephes.dawsn, lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z), rtol=1e-12 ) def test_erf_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -1, 1] assert_allclose(special.erf(vals), expected, rtol=1e-15) def test_erfc_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, 2, 0] assert_allclose(special.erfc(vals), expected, rtol=1e-15) def test_erfcx_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, np.inf, 0] assert_allclose(special.erfcx(vals), expected, rtol=1e-15) def test_erfi_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -np.inf, np.inf] assert_allclose(special.erfi(vals), expected, rtol=1e-15) def test_dawsn_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -0.0, 0.0] assert_allclose(special.dawsn(vals), expected, rtol=1e-15) def test_wofz_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan + np.nan * 1.j, 0.-0.j, 0.+0.j] assert_allclose(special.wofz(vals), expected, rtol=1e-15) class TestEuler(object): def test_euler(self): eu0 = special.euler(0) eu1 = special.euler(1) eu2 = special.euler(2) # just checking segfaults assert_allclose(eu0, [1], rtol=1e-15) assert_allclose(eu1, [1, 0], rtol=1e-15) assert_allclose(eu2, [1, 0, -1], rtol=1e-15) eu24 = special.euler(24) mathworld = [1,1,5,61,1385,50521,2702765,199360981, 19391512145,2404879675441, 370371188237525,69348874393137901, 15514534163557086905] correct = zeros((25,),'d') for k in range(0,13): if (k % 2): correct[2*k] = -float(mathworld[k]) else: correct[2*k] = float(mathworld[k]) olderr = np.seterr(all='ignore') try: err = nan_to_num((eu24-correct)/correct) errmax = max(err) finally: np.seterr(**olderr) assert_almost_equal(errmax, 0.0, 14) class TestExp(object): def test_exp2(self): ex = special.exp2(2) exrl = 2**2 assert_equal(ex,exrl) def test_exp2more(self): exm = special.exp2(2.5) exmrl = 2**(2.5) assert_almost_equal(exm,exmrl,8) def test_exp10(self): ex = special.exp10(2) exrl = 10**2 assert_approx_equal(ex,exrl) def test_exp10more(self): exm = special.exp10(2.5) exmrl = 10**(2.5) assert_almost_equal(exm,exmrl,8) def test_expm1(self): ex = (special.expm1(2),special.expm1(3),special.expm1(4)) exrl = (exp(2)-1,exp(3)-1,exp(4)-1) assert_array_almost_equal(ex,exrl,8) def test_expm1more(self): ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2)) exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) assert_array_almost_equal(ex1,exrl1,8) class TestFactorialFunctions(object): def test_factorial(self): # Some known values, float math assert_array_almost_equal(special.factorial(0), 1) assert_array_almost_equal(special.factorial(1), 1) assert_array_almost_equal(special.factorial(2), 2) assert_array_almost_equal([6., 24., 120.], special.factorial([3, 4, 5], exact=False)) assert_array_almost_equal(special.factorial([[5, 3], [4, 3]]), [[120, 6], [24, 6]]) # Some known values, integer math assert_equal(special.factorial(0, exact=True), 1) assert_equal(special.factorial(1, exact=True), 1) assert_equal(special.factorial(2, exact=True), 2) assert_equal(special.factorial(5, exact=True), 120) assert_equal(special.factorial(15, exact=True), 1307674368000) # ndarray shape is maintained assert_equal(special.factorial([7, 4, 15, 10], exact=True), [5040, 24, 1307674368000, 3628800]) assert_equal(special.factorial([[5, 3], [4, 3]], True), [[120, 6], [24, 6]]) # object arrays assert_equal(special.factorial(np.arange(-3, 22), True), special.factorial(np.arange(-3, 22), False)) # int64 array assert_equal(special.factorial(np.arange(-3, 15), True), special.factorial(np.arange(-3, 15), False)) # int32 array assert_equal(special.factorial(np.arange(-3, 5), True), special.factorial(np.arange(-3, 5), False)) # Consistent output for n < 0 for exact in (True, False): assert_array_equal(0, special.factorial(-3, exact)) assert_array_equal([1, 2, 0, 0], special.factorial([1, 2, -5, -4], exact)) for n in range(0, 22): # Compare all with math.factorial correct = math.factorial(n) assert_array_equal(correct, special.factorial(n, True)) assert_array_equal(correct, special.factorial([n], True)[0]) assert_allclose(float(correct), special.factorial(n, False)) assert_allclose(float(correct), special.factorial([n], False)[0]) # Compare exact=True vs False, scalar vs array assert_array_equal(special.factorial(n, True), special.factorial(n, False)) assert_array_equal(special.factorial([n], True), special.factorial([n], False)) @pytest.mark.parametrize('x, exact', [ (1, True), (1, False), (np.array(1), True), (np.array(1), False), ]) def test_factorial_0d_return_type(self, x, exact): assert np.isscalar(special.factorial(x, exact=exact)) def test_factorial2(self): assert_array_almost_equal([105., 384., 945.], special.factorial2([7, 8, 9], exact=False)) assert_equal(special.factorial2(7, exact=True), 105) def test_factorialk(self): assert_equal(special.factorialk(5, 1, exact=True), 120) assert_equal(special.factorialk(5, 3, exact=True), 10) @pytest.mark.parametrize('x, exact', [ (np.nan, True), (np.nan, False), (np.array([np.nan]), True), (np.array([np.nan]), False), ]) def test_nan_inputs(self, x, exact): result = special.factorial(x, exact=exact) assert_(np.isnan(result)) def test_mixed_nan_inputs(self): x = np.array([np.nan, 1, 2, 3, np.nan]) result = special.factorial(x, exact=True) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) result = special.factorial(x, exact=False) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) class TestFresnel(object): def test_fresnel(self): frs = array(special.fresnel(.5)) assert_array_almost_equal(frs,array([0.064732432859999287, 0.49234422587144644]),8) def test_fresnel_inf1(self): frs = special.fresnel(np.inf) assert_equal(frs, (0.5, 0.5)) def test_fresnel_inf2(self): frs = special.fresnel(-np.inf) assert_equal(frs, (-0.5, -0.5)) # values from pg 329 Table 7.11 of A & S # slightly corrected in 4th decimal place def test_fresnel_zeros(self): szo, czo = special.fresnel_zeros(5) assert_array_almost_equal(szo, array([2.0093+0.2885j, 2.8335+0.2443j, 3.4675+0.2185j, 4.0026+0.2009j, 4.4742+0.1877j]),3) assert_array_almost_equal(czo, array([1.7437+0.3057j, 2.6515+0.2529j, 3.3204+0.2240j, 3.8757+0.2047j, 4.3611+0.1907j]),3) vals1 = special.fresnel(szo)[0] vals2 = special.fresnel(czo)[1] assert_array_almost_equal(vals1,0,14) assert_array_almost_equal(vals2,0,14) def test_fresnelc_zeros(self): szo, czo = special.fresnel_zeros(6) frc = special.fresnelc_zeros(6) assert_array_almost_equal(frc,czo,12) def test_fresnels_zeros(self): szo, czo = special.fresnel_zeros(5) frs = special.fresnels_zeros(5) assert_array_almost_equal(frs,szo,12) class TestGamma(object): def test_gamma(self): gam = special.gamma(5) assert_equal(gam,24.0) def test_gammaln(self): gamln = special.gammaln(3) lngam = log(special.gamma(3)) assert_almost_equal(gamln,lngam,8) def test_gammainccinv(self): gccinv = special.gammainccinv(.5,.5) gcinv = special.gammaincinv(.5,.5) assert_almost_equal(gccinv,gcinv,8) @with_special_errors def test_gammaincinv(self): y = special.gammaincinv(.4,.4) x = special.gammainc(.4,y) assert_almost_equal(x,0.4,1) y = special.gammainc(10, 0.05) x = special.gammaincinv(10, 2.5715803516000736e-20) assert_almost_equal(0.05, x, decimal=10) assert_almost_equal(y, 2.5715803516000736e-20, decimal=10) x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18) assert_almost_equal(11.0, x, decimal=10) @with_special_errors def test_975(self): # Regression test for ticket #975 -- switch point in algorithm # check that things work OK at the point, immediately next floats # around it, and a bit further away pts = [0.25, np.nextafter(0.25, 0), 0.25 - 1e-12, np.nextafter(0.25, 1), 0.25 + 1e-12] for xp in pts: y = special.gammaincinv(.4, xp) x = special.gammainc(0.4, y) assert_allclose(x, xp, rtol=1e-12) def test_rgamma(self): rgam = special.rgamma(8) rlgam = 1/special.gamma(8) assert_almost_equal(rgam,rlgam,8) def test_infinity(self): assert_(np.isinf(special.gamma(-1))) assert_equal(special.rgamma(-1), 0) class TestHankel(object): def test_negv1(self): assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14) def test_hankel1(self): hank1 = special.hankel1(1,.1) hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j) assert_almost_equal(hank1,hankrl,8) def test_negv1e(self): assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14) def test_hankel1e(self): hank1e = special.hankel1e(1,.1) hankrle = special.hankel1(1,.1)*exp(-.1j) assert_almost_equal(hank1e,hankrle,8) def test_negv2(self): assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14) def test_hankel2(self): hank2 = special.hankel2(1,.1) hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j) assert_almost_equal(hank2,hankrl2,8) def test_neg2e(self): assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14) def test_hankl2e(self): hank2e = special.hankel2e(1,.1) hankrl2e = special.hankel2e(1,.1) assert_almost_equal(hank2e,hankrl2e,8) class TestHyper(object): def test_h1vp(self): h1 = special.h1vp(1,.1) h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j) assert_almost_equal(h1,h1real,8) def test_h2vp(self): h2 = special.h2vp(1,.1) h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j) assert_almost_equal(h2,h2real,8) def test_hyp0f1(self): # scalar input assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12) assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15) # float input, expected values match mpmath x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5]) expected = np.array([0.58493659229143, 0.70566805723127, 1.0, 1.37789689539747, 1.60373685288480]) assert_allclose(x, expected, rtol=1e-12) # complex input x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j) assert_allclose(x, expected.astype(complex), rtol=1e-12) # test broadcasting x1 = [0.5, 1.5, 2.5] x2 = [0, 1, 0.5] x = special.hyp0f1(x1, x2) expected = [1.0, 1.8134302039235093, 1.21482702689997] assert_allclose(x, expected, rtol=1e-12) x = special.hyp0f1(np.row_stack([x1] * 2), x2) assert_allclose(x, np.row_stack([expected] * 2), rtol=1e-12) assert_raises(ValueError, special.hyp0f1, np.row_stack([x1] * 3), [0, 1]) def test_hyp0f1_gh5764(self): # Just checks the point that failed; there's a more systematic # test in test_mpmath res = special.hyp0f1(0.8, 0.5 + 0.5*1J) # The expected value was generated using mpmath assert_almost_equal(res, 1.6139719776441115 + 1J*0.80893054061790665) def test_hyp1f1(self): hyp1 = special.hyp1f1(.1,.1,.3) assert_almost_equal(hyp1, 1.3498588075760032,7) # test contributed by Moritz Deger (2008-05-29) # https://github.com/scipy/scipy/issues/1186 (Trac #659) # reference data obtained from mathematica [ a, b, x, m(a,b,x)]: # produced with test_hyp1f1.nb ref_data = array([[-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04], [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00], [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05], [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08], [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24], [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21], [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13], [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13], [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02], [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10], [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01], [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21], [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20], [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07], [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03], [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02], [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11], [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03], [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17], [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01], [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00], [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00], [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23], [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01], [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04], [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08], [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01], [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07], [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03], [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09], [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06], [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00], [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01], [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02], [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02], [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02], [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00], [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09], [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01], [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00], [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02], [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05], [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05], [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02], [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02], [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13], [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05], [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12], [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01], [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16], [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37], [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06], [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02], [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12], [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27], [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04], [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06], [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07], [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03], [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07], [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27], [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12], [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32], [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04], [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01], [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02], [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19], [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09], [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31], [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01], [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02], [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08], [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09], [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33], [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01], [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29], [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01], [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29], [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02], [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00], [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08], [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01], [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01], [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01], [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13], [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11], [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02], [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02], [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01], [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31], [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04], [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25], [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01], [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00], [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02], [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05], [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02], [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01], [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01], [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00]]) for a,b,c,expected in ref_data: result = special.hyp1f1(a,b,c) assert_(abs(expected - result)/expected < 1e-4) def test_hyp1f1_gh2957(self): hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933) hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934) assert_almost_equal(hyp1, hyp2, 12) def test_hyp1f1_gh2282(self): hyp = special.hyp1f1(0.5, 1.5, -1000) assert_almost_equal(hyp, 0.028024956081989643, 12) def test_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], [3, 4, 8, 1, special.gamma(8)*special.gamma(8-4-3)/special.gamma(8-3)/special.gamma(8-4)], [3, 2, 3-2+1, -1, 1./2**3*sqrt(pi) * special.gamma(1+3-2)/special.gamma(1+0.5*3-2)/special.gamma(0.5+0.5*3)], [5, 2, 5-2+1, -1, 1./2**5*sqrt(pi) * special.gamma(1+5-2)/special.gamma(1+0.5*5-2)/special.gamma(0.5+0.5*5)], [4, 0.5+4, 1.5-2*4, -1./3, (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4)/special.gamma(3./2)/special.gamma(4./3-2*4)], # and some others # ticket #424 [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484], # negative integer a or b, with c-a-b integer and x > 0.9 [-2,3,1,0.95,0.715], [2,-3,1,0.95,-0.007], [-6,3,1,0.95,0.0000810625], [2,-5,1,0.95,-0.000029375], # huge negative integers (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24), (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18), ] for i, (a, b, c, x, v) in enumerate(values): cv = special.hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_hyperu(self): val1 = special.hyperu(1,0.1,100) assert_almost_equal(val1,0.0098153,7) a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] a,b = asarray(a), asarray(b) z = 0.5 hypu = special.hyperu(a,b,z) hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) / (special.gamma(1+a-b)*special.gamma(b)) - z**(1-b)*special.hyp1f1(1+a-b,2-b,z) / (special.gamma(a)*special.gamma(2-b))) assert_array_almost_equal(hypu,hprl,12) def test_hyperu_gh2287(self): assert_almost_equal(special.hyperu(1, 1.5, 20.2), 0.048360918656699191, 12) class TestBessel(object): def test_itj0y0(self): it0 = array(special.itj0y0(.2)) assert_array_almost_equal(it0,array([0.19933433254006822, -0.34570883800412566]),8) def test_it2j0y0(self): it2 = array(special.it2j0y0(.2)) assert_array_almost_equal(it2,array([0.0049937546274601858, -0.43423067011231614]),8) def test_negv_iv(self): assert_equal(special.iv(3,2), special.iv(-3,2)) def test_j0(self): oz = special.j0(.1) ozr = special.jn(0,.1) assert_almost_equal(oz,ozr,8) def test_j1(self): o1 = special.j1(.1) o1r = special.jn(1,.1) assert_almost_equal(o1,o1r,8) def test_jn(self): jnnr = special.jn(1,.2) assert_almost_equal(jnnr,0.099500832639235995,8) def test_negv_jv(self): assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14) def test_jv(self): values = [[0, 0.1, 0.99750156206604002], [2./3, 1e-8, 0.3239028506761532e-5], [2./3, 1e-10, 0.1503423854873779e-6], [3.1, 1e-10, 0.1711956265409013e-32], [2./3, 4.0, -0.2325440850267039], ] for i, (v, x, y) in enumerate(values): yc = special.jv(v, x) assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) def test_negv_jve(self): assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14) def test_jve(self): jvexp = special.jve(1,.2) assert_almost_equal(jvexp,0.099500832639235995,8) jvexp1 = special.jve(1,.2+1j) z = .2+1j jvexpr = special.jv(1,z)*exp(-abs(z.imag)) assert_almost_equal(jvexp1,jvexpr,8) def test_jn_zeros(self): jn0 = special.jn_zeros(0,5) jn1 = special.jn_zeros(1,5) assert_array_almost_equal(jn0,array([2.4048255577, 5.5200781103, 8.6537279129, 11.7915344391, 14.9309177086]),4) assert_array_almost_equal(jn1,array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]),4) jn102 = special.jn_zeros(102,5) assert_allclose(jn102, array([110.89174935992040343, 117.83464175788308398, 123.70194191713507279, 129.02417238949092824, 134.00114761868422559]), rtol=1e-13) jn301 = special.jn_zeros(301,5) assert_allclose(jn301, array([313.59097866698830153, 323.21549776096288280, 331.22338738656748796, 338.39676338872084500, 345.03284233056064157]), rtol=1e-13) def test_jn_zeros_slow(self): jn0 = special.jn_zeros(0, 300) assert_allclose(jn0[260-1], 816.02884495068867280, rtol=1e-13) assert_allclose(jn0[280-1], 878.86068707124422606, rtol=1e-13) assert_allclose(jn0[300-1], 941.69253065317954064, rtol=1e-13) jn10 = special.jn_zeros(10, 300) assert_allclose(jn10[260-1], 831.67668514305631151, rtol=1e-13) assert_allclose(jn10[280-1], 894.51275095371316931, rtol=1e-13) assert_allclose(jn10[300-1], 957.34826370866539775, rtol=1e-13) jn3010 = special.jn_zeros(3010,5) assert_allclose(jn3010, array([3036.86590780927, 3057.06598526482, 3073.66360690272, 3088.37736494778, 3101.86438139042]), rtol=1e-8) def test_jnjnp_zeros(self): jn = special.jn def jnp(n, x): return (jn(n-1,x) - jn(n+1,x))/2 for nt in range(1, 30): z, n, m, t = special.jnjnp_zeros(nt) for zz, nn, tt in zip(z, n, t): if tt == 0: assert_allclose(jn(nn, zz), 0, atol=1e-6) elif tt == 1: assert_allclose(jnp(nn, zz), 0, atol=1e-6) else: raise AssertionError("Invalid t return for nt=%d" % nt) def test_jnp_zeros(self): jnp = special.jnp_zeros(1,5) assert_array_almost_equal(jnp, array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]),4) jnp = special.jnp_zeros(443,5) assert_allclose(special.jvp(443, jnp), 0, atol=1e-15) def test_jnyn_zeros(self): jnz = special.jnyn_zeros(1,5) assert_array_almost_equal(jnz,(array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]), array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]), array([2.19714, 5.42968, 8.59601, 11.74915, 14.89744]), array([3.68302, 6.94150, 10.12340, 13.28576, 16.44006])),5) def test_jvp(self): jvprim = special.jvp(2,2) jv0 = (special.jv(1,2)-special.jv(3,2))/2 assert_almost_equal(jvprim,jv0,10) def test_k0(self): ozk = special.k0(.1) ozkr = special.kv(0,.1) assert_almost_equal(ozk,ozkr,8) def test_k0e(self): ozke = special.k0e(.1) ozker = special.kve(0,.1) assert_almost_equal(ozke,ozker,8) def test_k1(self): o1k = special.k1(.1) o1kr = special.kv(1,.1) assert_almost_equal(o1k,o1kr,8) def test_k1e(self): o1ke = special.k1e(.1) o1ker = special.kve(1,.1) assert_almost_equal(o1ke,o1ker,8) def test_jacobi(self): a = 5*np.random.random() - 1 b = 5*np.random.random() - 1 P0 = special.jacobi(0,a,b) P1 = special.jacobi(1,a,b) P2 = special.jacobi(2,a,b) P3 = special.jacobi(3,a,b) assert_array_almost_equal(P0.c,[1],13) assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13) cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)] p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]] assert_array_almost_equal(P2.c,array(p2c)/8.0,13) cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3), 12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)] p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] assert_array_almost_equal(P3.c,array(p3c)/48.0,13) def test_kn(self): kn1 = special.kn(0,.2) assert_almost_equal(kn1,1.7527038555281462,8) def test_negv_kv(self): assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2)) def test_kv0(self): kv0 = special.kv(0,.2) assert_almost_equal(kv0, 1.7527038555281462, 10) def test_kv1(self): kv1 = special.kv(1,0.2) assert_almost_equal(kv1, 4.775972543220472, 10) def test_kv2(self): kv2 = special.kv(2,0.2) assert_almost_equal(kv2, 49.51242928773287, 10) def test_kn_largeorder(self): assert_allclose(special.kn(32, 1), 1.7516596664574289e+43) def test_kv_largearg(self): assert_equal(special.kv(0, 1e19), 0) def test_negv_kve(self): assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2)) def test_kve(self): kve1 = special.kve(0,.2) kv1 = special.kv(0,.2)*exp(.2) assert_almost_equal(kve1,kv1,8) z = .2+1j kve2 = special.kve(0,z) kv2 = special.kv(0,z)*exp(z) assert_almost_equal(kve2,kv2,8) def test_kvp_v0n1(self): z = 2.2 assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10) def test_kvp_n1(self): v = 3. z = 2.2 xc = -special.kv(v+1,z) + v/z*special.kv(v,z) x = special.kvp(v,z, n=1) assert_almost_equal(xc, x, 10) # this function (kvp) is broken def test_kvp_n2(self): v = 3. z = 2.2 xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z x = special.kvp(v, z, n=2) assert_almost_equal(xc, x, 10) def test_y0(self): oz = special.y0(.1) ozr = special.yn(0,.1) assert_almost_equal(oz,ozr,8) def test_y1(self): o1 = special.y1(.1) o1r = special.yn(1,.1) assert_almost_equal(o1,o1r,8) def test_y0_zeros(self): yo,ypo = special.y0_zeros(2) zo,zpo = special.y0_zeros(2,complex=1) all = r_[yo,zo] allval = r_[ypo,zpo] assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11) assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11) def test_y1_zeros(self): y1 = special.y1_zeros(1) assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) def test_y1p_zeros(self): y1p = special.y1p_zeros(1,complex=1) assert_array_almost_equal(y1p,(array([0.5768+0.904j]), array([-0.7635+0.5892j])),3) def test_yn_zeros(self): an = special.yn_zeros(4,2) assert_array_almost_equal(an,array([5.64515, 9.36162]),5) an = special.yn_zeros(443,5) assert_allclose(an, [450.13573091578090314, 463.05692376675001542, 472.80651546418663566, 481.27353184725625838, 488.98055964441374646], rtol=1e-15) def test_ynp_zeros(self): ao = special.ynp_zeros(0,2) assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6) ao = special.ynp_zeros(43,5) assert_allclose(special.yvp(43, ao), 0, atol=1e-15) ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-9) def test_ynp_zeros_large_order(self): ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-14) def test_yn(self): yn2n = special.yn(1,.2) assert_almost_equal(yn2n,-3.3238249881118471,8) def test_negv_yv(self): assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14) def test_yv(self): yv2 = special.yv(1,.2) assert_almost_equal(yv2,-3.3238249881118471,8) def test_negv_yve(self): assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14) def test_yve(self): yve2 = special.yve(1,.2) assert_almost_equal(yve2,-3.3238249881118471,8) yve2r = special.yv(1,.2+1j)*exp(-1) yve22 = special.yve(1,.2+1j) assert_almost_equal(yve22,yve2r,8) def test_yvp(self): yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0 yvp1 = special.yvp(2,.2) assert_array_almost_equal(yvp1,yvpr,10) def _cephes_vs_amos_points(self): """Yield points at which to compare Cephes implementation to AMOS""" # check several points, including large-amplitude ones for v in [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301]: for z in [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300, 10003]: yield v, z # check half-integers; these are problematic points at least # for cephes/iv for v in 0.5 + arange(-60, 60): yield v, 3.5 def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None): for v, z in self._cephes_vs_amos_points(): if skip is not None and skip(v, z): continue c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z) if np.isinf(c1): assert_(np.abs(c2) >= 1e300, (v, z)) elif np.isnan(c1): assert_(c2.imag != 0, (v, z)) else: assert_allclose(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol) if v == int(v): assert_allclose(c3, c2, err_msg=(v, z), rtol=rtol, atol=atol) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_jv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_yv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305) def test_yv_cephes_vs_amos_only_small_orders(self): skipper = lambda v, z: (abs(v) > 50) self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305, skip=skipper) def test_iv_cephes_vs_amos(self): olderr = np.seterr(all='ignore') try: self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305) finally: np.seterr(**olderr) @pytest.mark.slow def test_iv_cephes_vs_amos_mass_test(self): N = 1000000 np.random.seed(1) v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N) x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N) imsk = (np.random.randint(8, size=N) == 0) v[imsk] = v[imsk].astype(int) old_err = np.seterr(all='ignore') try: c1 = special.iv(v, x) c2 = special.iv(v, x+0j) # deal with differences in the inf and zero cutoffs c1[abs(c1) > 1e300] = np.inf c2[abs(c2) > 1e300] = np.inf c1[abs(c1) < 1e-300] = 0 c2[abs(c2) < 1e-300] = 0 dc = abs(c1/c2 - 1) dc[np.isnan(dc)] = 0 finally: np.seterr(**old_err) k = np.argmax(dc) # Most error apparently comes from AMOS and not our implementation; # there are some problems near integer orders there assert_(dc[k] < 2e-7, (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j))) def test_kv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305) self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305) def test_ticket_623(self): assert_allclose(special.jv(3, 4), 0.43017147387562193) assert_allclose(special.jv(301, 1300), 0.0183487151115275) assert_allclose(special.jv(301, 1296.0682), -0.0224174325312048) def test_ticket_853(self): """Negative-order Bessels""" # cephes assert_allclose(special.jv(-1, 1), -0.4400505857449335) assert_allclose(special.jv(-2, 1), 0.1149034849319005) assert_allclose(special.yv(-1, 1), 0.7812128213002887) assert_allclose(special.yv(-2, 1), -1.650682606816255) assert_allclose(special.iv(-1, 1), 0.5651591039924851) assert_allclose(special.iv(-2, 1), 0.1357476697670383) assert_allclose(special.kv(-1, 1), 0.6019072301972347) assert_allclose(special.kv(-2, 1), 1.624838898635178) assert_allclose(special.jv(-0.5, 1), 0.43109886801837607952) assert_allclose(special.yv(-0.5, 1), 0.6713967071418031) assert_allclose(special.iv(-0.5, 1), 1.231200214592967) assert_allclose(special.kv(-0.5, 1), 0.4610685044478945) # amos assert_allclose(special.jv(-1, 1+0j), -0.4400505857449335) assert_allclose(special.jv(-2, 1+0j), 0.1149034849319005) assert_allclose(special.yv(-1, 1+0j), 0.7812128213002887) assert_allclose(special.yv(-2, 1+0j), -1.650682606816255) assert_allclose(special.iv(-1, 1+0j), 0.5651591039924851) assert_allclose(special.iv(-2, 1+0j), 0.1357476697670383) assert_allclose(special.kv(-1, 1+0j), 0.6019072301972347) assert_allclose(special.kv(-2, 1+0j), 1.624838898635178) assert_allclose(special.jv(-0.5, 1+0j), 0.43109886801837607952) assert_allclose(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j) assert_allclose(special.yv(-0.5, 1+0j), 0.6713967071418031) assert_allclose(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j) assert_allclose(special.iv(-0.5, 1+0j), 1.231200214592967) assert_allclose(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j) assert_allclose(special.kv(-0.5, 1+0j), 0.4610685044478945) assert_allclose(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j) assert_allclose(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3)) assert_allclose(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j)) assert_allclose(special.hankel1(-0.5, 1+1j), special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j)) assert_allclose(special.hankel2(-0.5, 1+1j), special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j)) def test_ticket_854(self): """Real-valued Bessel domains""" assert_(isnan(special.jv(0.5, -1))) assert_(isnan(special.iv(0.5, -1))) assert_(isnan(special.yv(0.5, -1))) assert_(isnan(special.yv(1, -1))) assert_(isnan(special.kv(0.5, -1))) assert_(isnan(special.kv(1, -1))) assert_(isnan(special.jve(0.5, -1))) assert_(isnan(special.ive(0.5, -1))) assert_(isnan(special.yve(0.5, -1))) assert_(isnan(special.yve(1, -1))) assert_(isnan(special.kve(0.5, -1))) assert_(isnan(special.kve(1, -1))) assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1)) assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1)) def test_gh_7909(self): assert_(special.kv(1.5, 0) == np.inf) assert_(special.kve(1.5, 0) == np.inf) def test_ticket_503(self): """Real-valued Bessel I overflow""" assert_allclose(special.iv(1, 700), 1.528500390233901e302) assert_allclose(special.iv(1000, 1120), 1.301564549405821e301) def test_iv_hyperg_poles(self): assert_allclose(special.iv(-0.5, 1), 1.231200214592967) def iv_series(self, v, z, n=200): k = arange(0, n).astype(float_) r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1) r[isnan(r)] = inf r = exp(r) err = abs(r).max() * finfo(float_).eps * n + abs(r[-1])*10 return r.sum(), err def test_i0_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(0, z) assert_allclose(special.i0(z), value, atol=err, err_msg=z) def test_i1_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(1, z) assert_allclose(special.i1(z), value, atol=err, err_msg=z) def test_iv_series(self): for v in [-20., -10., -1., 0., 1., 12.49, 120.]: for z in [1., 10., 200.5, -1+2j]: value, err = self.iv_series(v, z) assert_allclose(special.iv(v, z), value, atol=err, err_msg=(v, z)) def test_i0(self): values = [[0.0, 1.0], [1e-10, 1.0], [0.1, 0.9071009258], [0.5, 0.6450352706], [1.0, 0.4657596077], [2.5, 0.2700464416], [5.0, 0.1835408126], [20.0, 0.0897803119], ] for i, (x, v) in enumerate(values): cv = special.i0(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i0e(self): oize = special.i0e(.1) oizer = special.ive(0,.1) assert_almost_equal(oize,oizer,8) def test_i1(self): values = [[0.0, 0.0], [1e-10, 0.4999999999500000e-10], [0.1, 0.0452984468], [0.5, 0.1564208032], [1.0, 0.2079104154], [5.0, 0.1639722669], [20.0, 0.0875062222], ] for i, (x, v) in enumerate(values): cv = special.i1(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i1e(self): oi1e = special.i1e(.1) oi1er = special.ive(1,.1) assert_almost_equal(oi1e,oi1er,8) def test_iti0k0(self): iti0 = array(special.iti0k0(5)) assert_array_almost_equal(iti0,array([31.848667776169801, 1.5673873907283657]),5) def test_it2i0k0(self): it2k = special.it2i0k0(.1) assert_array_almost_equal(it2k,array([0.0012503906973464409, 3.3309450354686687]),6) def test_iv(self): iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(iv1,0.90710092578230106,10) def test_negv_ive(self): assert_equal(special.ive(3,2), special.ive(-3,2)) def test_ive(self): ive1 = special.ive(0,.1) iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(ive1,iv1,10) def test_ivp0(self): assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10) def test_ivp(self): y = (special.iv(0,2) + special.iv(2,2))/2 x = special.ivp(1,2) assert_almost_equal(x,y,10) class TestLaguerre(object): def test_laguerre(self): lag0 = special.laguerre(0) lag1 = special.laguerre(1) lag2 = special.laguerre(2) lag3 = special.laguerre(3) lag4 = special.laguerre(4) lag5 = special.laguerre(5) assert_array_almost_equal(lag0.c,[1],13) assert_array_almost_equal(lag1.c,[-1,1],13) assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13) assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13) assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) def test_genlaguerre(self): k = 5*np.random.random() - 0.9 lag0 = special.genlaguerre(0,k) lag1 = special.genlaguerre(1,k) lag2 = special.genlaguerre(2,k) lag3 = special.genlaguerre(3,k) assert_equal(lag0.c,[1]) assert_equal(lag1.c,[-1,k+1]) assert_almost_equal(lag2.c,array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0) assert_almost_equal(lag3.c,array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0) # Base polynomials come from Abrahmowitz and Stegan class TestLegendre(object): def test_legendre(self): leg0 = special.legendre(0) leg1 = special.legendre(1) leg2 = special.legendre(2) leg3 = special.legendre(3) leg4 = special.legendre(4) leg5 = special.legendre(5) assert_equal(leg0.c, [1]) assert_equal(leg1.c, [1,0]) assert_almost_equal(leg2.c, array([3,0,-1])/2.0, decimal=13) assert_almost_equal(leg3.c, array([5,0,-3,0])/2.0) assert_almost_equal(leg4.c, array([35,0,-30,0,3])/8.0) assert_almost_equal(leg5.c, array([63,0,-70,0,15,0])/8.0) class TestLambda(object): def test_lmbda(self): lam = special.lmbda(1,.1) lamr = (array([special.jn(0,.1), 2*special.jn(1,.1)/.1]), array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])) assert_array_almost_equal(lam,lamr,8) class TestLog1p(object): def test_log1p(self): l1p = (special.log1p(10), special.log1p(11), special.log1p(12)) l1prl = (log(11), log(12), log(13)) assert_array_almost_equal(l1p,l1prl,8) def test_log1pmore(self): l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2)) l1pmrl = (log(2),log(2.1),log(2.2)) assert_array_almost_equal(l1pm,l1pmrl,8) class TestLegendreFunctions(object): def test_clpmn(self): z = 0.5+0.3j clp = special.clpmn(2, 2, z, 3) assert_array_almost_equal(clp, (array([[1.0000, z, 0.5*(3*z*z-1)], [0.0000, sqrt(z*z-1), 3*z*sqrt(z*z-1)], [0.0000, 0.0000, 3*(z*z-1)]]), array([[0.0000, 1.0000, 3*z], [0.0000, z/sqrt(z*z-1), 3*(2*z*z-1)/sqrt(z*z-1)], [0.0000, 0.0000, 6*z]])), 7) def test_clpmn_close_to_real_2(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x), special.lpmv(m, n, x)]), 7) def test_clpmn_close_to_real_3(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi), special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]), 7) def test_clpmn_across_unit_circle(self): eps = 1e-7 m = 1 n = 1 x = 1j for type in [2, 3]: assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n], special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6) def test_inf(self): for z in (1, -1): for n in range(4): for m in range(1, n): lp = special.clpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) lp = special.lpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) def test_deriv_clpmn(self): # data inside and outside of the unit circle zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j, 1+1j, -1+1j, -1-1j, 1-1j] m = 2 n = 3 for type in [2, 3]: for z in zvals: for h in [1e-3, 1e-3j]: approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0] - special.clpmn(m, n, z-0.5*h, type)[0])/h assert_allclose(special.clpmn(m, n, z, type)[1], approx_derivative, rtol=1e-4) def test_lpmn(self): lp = special.lpmn(0,2,.5) assert_array_almost_equal(lp,(array([[1.00000, 0.50000, -0.12500]]), array([[0.00000, 1.00000, 1.50000]])),4) def test_lpn(self): lpnf = special.lpn(2,.5) assert_array_almost_equal(lpnf,(array([1.00000, 0.50000, -0.12500]), array([0.00000, 1.00000, 1.50000])),4) def test_lpmv(self): lp = special.lpmv(0,2,.5) assert_almost_equal(lp,-0.125,7) lp = special.lpmv(0,40,.001) assert_almost_equal(lp,0.1252678976534484,7) # XXX: this is outside the domain of the current implementation, # so ensure it returns a NaN rather than a wrong answer. olderr = np.seterr(all='ignore') try: lp = special.lpmv(-1,-1,.001) finally: np.seterr(**olderr) assert_(lp != 0 or np.isnan(lp)) def test_lqmn(self): lqmnf = special.lqmn(0,2,.5) lqf = special.lqn(2,.5) assert_array_almost_equal(lqmnf[0][0],lqf[0],4) assert_array_almost_equal(lqmnf[1][0],lqf[1],4) def test_lqmn_gt1(self): """algorithm for real arguments changes at 1.0001 test against analytical result for m=2, n=1 """ x0 = 1.0001 delta = 0.00002 for x in (x0-delta, x0+delta): lq = special.lqmn(2, 1, x)[0][-1, -1] expected = 2/(x*x-1) assert_almost_equal(lq, expected) def test_lqmn_shape(self): a, b = special.lqmn(4, 4, 1.1) assert_equal(a.shape, (5, 5)) assert_equal(b.shape, (5, 5)) a, b = special.lqmn(4, 0, 1.1) assert_equal(a.shape, (5, 1)) assert_equal(b.shape, (5, 1)) def test_lqn(self): lqf = special.lqn(2,.5) assert_array_almost_equal(lqf,(array([0.5493, -0.7253, -0.8187]), array([1.3333, 1.216, -0.8427])),4) class TestMathieu(object): def test_mathieu_a(self): pass def test_mathieu_even_coef(self): special.mathieu_even_coef(2,5) # Q not defined broken and cannot figure out proper reporting order def test_mathieu_odd_coef(self): # same problem as above pass class TestFresnelIntegral(object): def test_modfresnelp(self): pass def test_modfresnelm(self): pass class TestOblCvSeq(object): def test_obl_cv_seq(self): obl = special.obl_cv_seq(0,3,1) assert_array_almost_equal(obl,array([-0.348602, 1.393206, 5.486800, 11.492120]),5) class TestParabolicCylinder(object): def test_pbdn_seq(self): pb = special.pbdn_seq(1,.1) assert_array_almost_equal(pb,(array([0.9975, 0.0998]), array([-0.0499, 0.9925])),4) def test_pbdv(self): special.pbdv(1,.2) 1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0] def test_pbdv_seq(self): pbn = special.pbdn_seq(1,.1) pbv = special.pbdv_seq(1,.1) assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) def test_pbdv_points(self): # simple case eta = np.linspace(-10, 10, 5) z = 2**(eta/2)*np.sqrt(np.pi)/special.gamma(.5-.5*eta) assert_allclose(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14) # some points assert_allclose(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12) assert_allclose(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12) def test_pbdv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbdv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) def test_pbvv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbvv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) class TestPolygamma(object): # from Table 6.2 (pg. 271) of A&S def test_polygamma(self): poly2 = special.polygamma(2,1) poly3 = special.polygamma(3,1) assert_almost_equal(poly2,-2.4041138063,10) assert_almost_equal(poly3,6.4939394023,10) # Test polygamma(0, x) == psi(x) x = [2, 3, 1.1e14] assert_almost_equal(special.polygamma(0, x), special.psi(x)) # Test broadcasting n = [0, 1, 2] x = [0.5, 1.5, 2.5] expected = [-1.9635100260214238, 0.93480220054467933, -0.23620405164172739] assert_almost_equal(special.polygamma(n, x), expected) expected = np.row_stack([expected]*2) assert_almost_equal(special.polygamma(n, np.row_stack([x]*2)), expected) assert_almost_equal(special.polygamma(np.row_stack([n]*2), x), expected) class TestProCvSeq(object): def test_pro_cv_seq(self): prol = special.pro_cv_seq(0,3,1) assert_array_almost_equal(prol,array([0.319000, 2.593084, 6.533471, 12.514462]),5) class TestPsi(object): def test_psi(self): ps = special.psi(1) assert_almost_equal(ps,-0.57721566490153287,8) class TestRadian(object): def test_radian(self): rad = special.radian(90,0,0) assert_almost_equal(rad,pi/2.0,5) def test_radianmore(self): rad1 = special.radian(90,1,60) assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) class TestRiccati(object): def test_riccati_jn(self): N, x = 2, 0.2 S = np.empty((N, N)) for n in range(N): j = special.spherical_jn(n, x) jp = special.spherical_jn(n, x, derivative=True) S[0,n] = x*j S[1,n] = x*jp + j assert_array_almost_equal(S, special.riccati_jn(n, x), 8) def test_riccati_yn(self): N, x = 2, 0.2 C = np.empty((N, N)) for n in range(N): y = special.spherical_yn(n, x) yp = special.spherical_yn(n, x, derivative=True) C[0,n] = x*y C[1,n] = x*yp + y assert_array_almost_equal(C, special.riccati_yn(n, x), 8) class TestRound(object): def test_round(self): rnd = list(map(int,(special.round(10.1),special.round(10.4),special.round(10.5),special.round(10.6)))) # Note: According to the documentation, scipy.special.round is # supposed to round to the nearest even number if the fractional # part is exactly 0.5. On some platforms, this does not appear # to work and thus this test may fail. However, this unit test is # correctly written. rndrl = (10,10,10,11) assert_array_equal(rnd,rndrl) def test_sph_harm(): # Tests derived from tables in # https://en.wikipedia.org/wiki/Table_of_spherical_harmonics sh = special.sph_harm pi = np.pi exp = np.exp sqrt = np.sqrt sin = np.sin cos = np.cos assert_array_almost_equal(sh(0,0,0,0), 0.5/sqrt(pi)) assert_array_almost_equal(sh(-2,2,0.,pi/4), 0.25*sqrt(15./(2.*pi)) * (sin(pi/4))**2.) assert_array_almost_equal(sh(-2,2,0.,pi/2), 0.25*sqrt(15./(2.*pi))) assert_array_almost_equal(sh(2,2,pi,pi/2), 0.25*sqrt(15/(2.*pi)) * exp(0+2.*pi*1j)*sin(pi/2.)**2.) assert_array_almost_equal(sh(2,4,pi/4.,pi/3.), (3./8.)*sqrt(5./(2.*pi)) * exp(0+2.*pi/4.*1j) * sin(pi/3.)**2. * (7.*cos(pi/3.)**2.-1)) assert_array_almost_equal(sh(4,4,pi/8.,pi/6.), (3./16.)*sqrt(35./(2.*pi)) * exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.) def test_sph_harm_ufunc_loop_selection(): # see https://github.com/scipy/scipy/issues/4895 dt = np.dtype(np.complex128) assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt) assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt) assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt) assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt) assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt) assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt) class TestStruve(object): def _series(self, v, z, n=100): """Compute Struve function & error estimate from its power series.""" k = arange(0, n) r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5) err = abs(r).max() * finfo(float_).eps * n return r.sum(), err def test_vs_series(self): """Check Struve function versus its power series""" for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]: for z in [1, 10, 19, 21, 30]: value, err = self._series(v, z) assert_allclose(special.struve(v, z), value, rtol=0, atol=err), (v, z) def test_some_values(self): assert_allclose(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7) assert_allclose(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8) assert_allclose(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12) assert_allclose(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11) assert_equal(special.struve(-12, -41), -special.struve(-12, 41)) assert_equal(special.struve(+12, -41), -special.struve(+12, 41)) assert_equal(special.struve(-11, -41), +special.struve(-11, 41)) assert_equal(special.struve(+11, -41), +special.struve(+11, 41)) assert_(isnan(special.struve(-7.1, -1))) assert_(isnan(special.struve(-10.1, -1))) def test_regression_679(self): """Regression test for #679""" assert_allclose(special.struve(-1.0, 20 - 1e-8), special.struve(-1.0, 20 + 1e-8)) assert_allclose(special.struve(-2.0, 20 - 1e-8), special.struve(-2.0, 20 + 1e-8)) assert_allclose(special.struve(-4.3, 20 - 1e-8), special.struve(-4.3, 20 + 1e-8)) def test_chi2_smalldf(): assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110) def test_ch2_inf(): assert_equal(special.chdtr(0.7,np.inf), 1.0) def test_chi2c_smalldf(): assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110) def test_chi2_inv_smalldf(): assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3) def test_agm_simple(): rtol = 1e-13 # Gauss's constant assert_allclose(1/special.agm(1, np.sqrt(2)), 0.834626841674073186, rtol=rtol) # These values were computed using Wolfram Alpha, with the # function ArithmeticGeometricMean[a, b]. agm13 = 1.863616783244897 agm15 = 2.604008190530940 agm35 = 3.936235503649555 assert_allclose(special.agm([[1], [3]], [1, 3, 5]), [[1, agm13, agm15], [agm13, 3, agm35]], rtol=rtol) # Computed by the iteration formula using mpmath, # with mpmath.mp.prec = 1000: agm12 = 1.4567910310469068 assert_allclose(special.agm(1, 2), agm12, rtol=rtol) assert_allclose(special.agm(2, 1), agm12, rtol=rtol) assert_allclose(special.agm(-1, -2), -agm12, rtol=rtol) assert_allclose(special.agm(24, 6), 13.458171481725614, rtol=rtol) assert_allclose(special.agm(13, 123456789.5), 11111458.498599306, rtol=rtol) assert_allclose(special.agm(1e30, 1), 2.229223055945383e+28, rtol=rtol) assert_allclose(special.agm(1e-22, 1), 0.030182566420169886, rtol=rtol) assert_allclose(special.agm(1e150, 1e180), 2.229223055945383e+178, rtol=rtol) assert_allclose(special.agm(1e180, 1e-150), 2.0634722510162677e+177, rtol=rtol) assert_allclose(special.agm(1e-150, 1e-170), 3.3112619670463756e-152, rtol=rtol) fi = np.finfo(1.0) assert_allclose(special.agm(fi.tiny, fi.max), 1.9892072050015473e+305, rtol=rtol) assert_allclose(special.agm(0.75*fi.max, fi.max), 1.564904312298045e+308, rtol=rtol) assert_allclose(special.agm(fi.tiny, 3*fi.tiny), 4.1466849866735005e-308, rtol=rtol) # zero, nan and inf cases. assert_equal(special.agm(0, 0), 0) assert_equal(special.agm(99, 0), 0) assert_equal(special.agm(-1, 10), np.nan) assert_equal(special.agm(0, np.inf), np.nan) assert_equal(special.agm(np.inf, 0), np.nan) assert_equal(special.agm(0, -np.inf), np.nan) assert_equal(special.agm(-np.inf, 0), np.nan) assert_equal(special.agm(np.inf, -np.inf), np.nan) assert_equal(special.agm(-np.inf, np.inf), np.nan) assert_equal(special.agm(1, np.nan), np.nan) assert_equal(special.agm(np.nan, -1), np.nan) assert_equal(special.agm(1, np.inf), np.inf) assert_equal(special.agm(np.inf, 1), np.inf) assert_equal(special.agm(-1, -np.inf), -np.inf) assert_equal(special.agm(-np.inf, -1), -np.inf) def test_legacy(): # Legacy behavior: truncating arguments to integers with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3)) assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3)) assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3)) assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3)) assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3)) assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3)) assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3)) assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3)) assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3)) @with_special_errors def test_error_raising(): assert_raises(special.SpecialFunctionError, special.iv, 1, 1e99j) def test_xlogy(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x*np.log(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float) z2 = np.r_[z1, [(0, 1j), (1, 1j)]] w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13) w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1]) assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13) def test_xlog1py(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x * np.log1p(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0), (1, 1e-30)], dtype=float) w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13) def test_entr(): def xfunc(x): if x < 0: return -np.inf else: return -special.xlogy(x, x) values = (0, 0.5, 1.0, np.inf) signs = [-1, 1] arr = [] for sgn, v in itertools.product(signs, values): arr.append(sgn * v) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z) assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13) def test_kl_div(): def xfunc(x, y): if x < 0 or y < 0 or (y == 0 and x != 0): # extension of natural domain to preserve convexity return np.inf elif np.isposinf(x) or np.isposinf(y): # limits within the natural domain return np.inf elif x == 0: return y else: return special.xlogy(x, x/y) - x + y values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13) def test_rel_entr(): def xfunc(x, y): if x > 0 and y > 0: return special.xlogy(x, x/y) elif x == 0 and y >= 0: return 0 else: return np.inf values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13) def test_huber(): assert_equal(special.huber(-1, 1.5), np.inf) assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5)) assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2)) def xfunc(delta, r): if delta < 0: return np.inf elif np.abs(r) < delta: return 0.5 * np.square(r) else: return delta * (np.abs(r) - 0.5 * delta) z = np.random.randn(10, 2) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13) def test_pseudo_huber(): def xfunc(delta, r): if delta < 0: return np.inf elif (not delta) or (not r): return 0 else: return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1) z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]]) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13)
aeklant/scipy
scipy/special/tests/test_basic.py
scipy/io/matlab/tests/test_mio_funcs.py
# -*- coding: latin-1 -*- ''' Nose test generators Need function load / save / roundtrip tests ''' import os from collections import OrderedDict from os.path import join as pjoin, dirname from glob import glob from io import BytesIO from tempfile import mkdtemp import warnings import shutil import gzip from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_equal, assert_) from pytest import raises as assert_raises import numpy as np from numpy import array import scipy.sparse as SP import scipy.io.matlab.byteordercodes as boc from scipy.io.matlab.miobase import matdims, MatWriteError, MatReadError from scipy.io.matlab.mio import (mat_reader_factory, loadmat, savemat, whosmat) from scipy.io.matlab.mio5 import (MatlabObject, MatFile5Writer, MatFile5Reader, MatlabFunction, varmats_from_mat, to_writeable, EmptyStructMarker) from scipy.io.matlab import mio5_params as mio5p test_data_path = pjoin(dirname(__file__), 'data') def mlarr(*args, **kwargs): """Convenience function to return matlab-compatible 2-D array.""" arr = np.array(*args, **kwargs) arr.shape = matdims(arr) return arr # Define cases to test theta = np.pi/4*np.arange(9,dtype=float).reshape(1,9) case_table4 = [ {'name': 'double', 'classes': {'testdouble': 'double'}, 'expected': {'testdouble': theta} }] case_table4.append( {'name': 'string', 'classes': {'teststring': 'char'}, 'expected': {'teststring': array(['"Do nine men interpret?" "Nine men," I nod.'])} }) case_table4.append( {'name': 'complex', 'classes': {'testcomplex': 'double'}, 'expected': {'testcomplex': np.cos(theta) + 1j*np.sin(theta)} }) A = np.zeros((3,5)) A[0] = list(range(1,6)) A[:,0] = list(range(1,4)) case_table4.append( {'name': 'matrix', 'classes': {'testmatrix': 'double'}, 'expected': {'testmatrix': A}, }) case_table4.append( {'name': 'sparse', 'classes': {'testsparse': 'sparse'}, 'expected': {'testsparse': SP.coo_matrix(A)}, }) B = A.astype(complex) B[0,0] += 1j case_table4.append( {'name': 'sparsecomplex', 'classes': {'testsparsecomplex': 'sparse'}, 'expected': {'testsparsecomplex': SP.coo_matrix(B)}, }) case_table4.append( {'name': 'multi', 'classes': {'theta': 'double', 'a': 'double'}, 'expected': {'theta': theta, 'a': A}, }) case_table4.append( {'name': 'minus', 'classes': {'testminus': 'double'}, 'expected': {'testminus': mlarr(-1)}, }) case_table4.append( {'name': 'onechar', 'classes': {'testonechar': 'char'}, 'expected': {'testonechar': array(['r'])}, }) # Cell arrays stored as object arrays CA = mlarr(( # tuple for object array creation [], mlarr([1]), mlarr([[1,2]]), mlarr([[1,2,3]])), dtype=object).reshape(1,-1) CA[0,0] = array( ['This cell contains this string and 3 arrays of increasing length']) case_table5 = [ {'name': 'cell', 'classes': {'testcell': 'cell'}, 'expected': {'testcell': CA}}] CAE = mlarr(( # tuple for object array creation mlarr(1), mlarr(2), mlarr([]), mlarr([]), mlarr(3)), dtype=object).reshape(1,-1) objarr = np.empty((1,1),dtype=object) objarr[0,0] = mlarr(1) case_table5.append( {'name': 'scalarcell', 'classes': {'testscalarcell': 'cell'}, 'expected': {'testscalarcell': objarr} }) case_table5.append( {'name': 'emptycell', 'classes': {'testemptycell': 'cell'}, 'expected': {'testemptycell': CAE}}) case_table5.append( {'name': 'stringarray', 'classes': {'teststringarray': 'char'}, 'expected': {'teststringarray': array( ['one ', 'two ', 'three'])}, }) case_table5.append( {'name': '3dmatrix', 'classes': {'test3dmatrix': 'double'}, 'expected': { 'test3dmatrix': np.transpose(np.reshape(list(range(1,25)), (4,3,2)))} }) st_sub_arr = array([np.sqrt(2),np.exp(1),np.pi]).reshape(1,3) dtype = [(n, object) for n in ['stringfield', 'doublefield', 'complexfield']] st1 = np.zeros((1,1), dtype) st1['stringfield'][0,0] = array(['Rats live on no evil star.']) st1['doublefield'][0,0] = st_sub_arr st1['complexfield'][0,0] = st_sub_arr * (1 + 1j) case_table5.append( {'name': 'struct', 'classes': {'teststruct': 'struct'}, 'expected': {'teststruct': st1} }) CN = np.zeros((1,2), dtype=object) CN[0,0] = mlarr(1) CN[0,1] = np.zeros((1,3), dtype=object) CN[0,1][0,0] = mlarr(2, dtype=np.uint8) CN[0,1][0,1] = mlarr([[3]], dtype=np.uint8) CN[0,1][0,2] = np.zeros((1,2), dtype=object) CN[0,1][0,2][0,0] = mlarr(4, dtype=np.uint8) CN[0,1][0,2][0,1] = mlarr(5, dtype=np.uint8) case_table5.append( {'name': 'cellnest', 'classes': {'testcellnest': 'cell'}, 'expected': {'testcellnest': CN}, }) st2 = np.empty((1,1), dtype=[(n, object) for n in ['one', 'two']]) st2[0,0]['one'] = mlarr(1) st2[0,0]['two'] = np.empty((1,1), dtype=[('three', object)]) st2[0,0]['two'][0,0]['three'] = array(['number 3']) case_table5.append( {'name': 'structnest', 'classes': {'teststructnest': 'struct'}, 'expected': {'teststructnest': st2} }) a = np.empty((1,2), dtype=[(n, object) for n in ['one', 'two']]) a[0,0]['one'] = mlarr(1) a[0,0]['two'] = mlarr(2) a[0,1]['one'] = array(['number 1']) a[0,1]['two'] = array(['number 2']) case_table5.append( {'name': 'structarr', 'classes': {'teststructarr': 'struct'}, 'expected': {'teststructarr': a} }) ODT = np.dtype([(n, object) for n in ['expr', 'inputExpr', 'args', 'isEmpty', 'numArgs', 'version']]) MO = MatlabObject(np.zeros((1,1), dtype=ODT), 'inline') m0 = MO[0,0] m0['expr'] = array(['x']) m0['inputExpr'] = array([' x = INLINE_INPUTS_{1};']) m0['args'] = array(['x']) m0['isEmpty'] = mlarr(0) m0['numArgs'] = mlarr(1) m0['version'] = mlarr(1) case_table5.append( {'name': 'object', 'classes': {'testobject': 'object'}, 'expected': {'testobject': MO} }) fp_u_str = open(pjoin(test_data_path, 'japanese_utf8.txt'), 'rb') u_str = fp_u_str.read().decode('utf-8') fp_u_str.close() case_table5.append( {'name': 'unicode', 'classes': {'testunicode': 'char'}, 'expected': {'testunicode': array([u_str])} }) case_table5.append( {'name': 'sparse', 'classes': {'testsparse': 'sparse'}, 'expected': {'testsparse': SP.coo_matrix(A)}, }) case_table5.append( {'name': 'sparsecomplex', 'classes': {'testsparsecomplex': 'sparse'}, 'expected': {'testsparsecomplex': SP.coo_matrix(B)}, }) case_table5.append( {'name': 'bool', 'classes': {'testbools': 'logical'}, 'expected': {'testbools': array([[True], [False]])}, }) case_table5_rt = case_table5[:] # Inline functions can't be concatenated in matlab, so RT only case_table5_rt.append( {'name': 'objectarray', 'classes': {'testobjectarray': 'object'}, 'expected': {'testobjectarray': np.repeat(MO, 2).reshape(1,2)}}) def types_compatible(var1, var2): """Check if types are same or compatible. 0-D numpy scalars are compatible with bare python scalars. """ type1 = type(var1) type2 = type(var2) if type1 is type2: return True if type1 is np.ndarray and var1.shape == (): return type(var1.item()) is type2 if type2 is np.ndarray and var2.shape == (): return type(var2.item()) is type1 return False def _check_level(label, expected, actual): """ Check one level of a potentially nested array """ if SP.issparse(expected): # allow different types of sparse matrices assert_(SP.issparse(actual)) assert_array_almost_equal(actual.todense(), expected.todense(), err_msg=label, decimal=5) return # Check types are as expected assert_(types_compatible(expected, actual), "Expected type %s, got %s at %s" % (type(expected), type(actual), label)) # A field in a record array may not be an ndarray # A scalar from a record array will be type np.void if not isinstance(expected, (np.void, np.ndarray, MatlabObject)): assert_equal(expected, actual) return # This is an ndarray-like thing assert_(expected.shape == actual.shape, msg='Expected shape %s, got %s at %s' % (expected.shape, actual.shape, label)) ex_dtype = expected.dtype if ex_dtype.hasobject: # array of objects if isinstance(expected, MatlabObject): assert_equal(expected.classname, actual.classname) for i, ev in enumerate(expected): level_label = "%s, [%d], " % (label, i) _check_level(level_label, ev, actual[i]) return if ex_dtype.fields: # probably recarray for fn in ex_dtype.fields: level_label = "%s, field %s, " % (label, fn) _check_level(level_label, expected[fn], actual[fn]) return if ex_dtype.type in (str, # string or bool np.unicode_, np.bool_): assert_equal(actual, expected, err_msg=label) return # Something numeric assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) def _load_check_case(name, files, case): for file_name in files: matdict = loadmat(file_name, struct_as_record=True) label = "test %s; file %s" % (name, file_name) for k, expected in case.items(): k_label = "%s, variable %s" % (label, k) assert_(k in matdict, "Missing key at %s" % k_label) _check_level(k_label, expected, matdict[k]) def _whos_check_case(name, files, case, classes): for file_name in files: label = "test %s; file %s" % (name, file_name) whos = whosmat(file_name) expected_whos = [ (k, expected.shape, classes[k]) for k, expected in case.items()] whos.sort() expected_whos.sort() assert_equal(whos, expected_whos, "%s: %r != %r" % (label, whos, expected_whos) ) # Round trip tests def _rt_check_case(name, expected, format): mat_stream = BytesIO() savemat(mat_stream, expected, format=format) mat_stream.seek(0) _load_check_case(name, [mat_stream], expected) # generator for load tests def test_load(): for case in case_table4 + case_table5: name = case['name'] expected = case['expected'] filt = pjoin(test_data_path, 'test%s_*.mat' % name) files = glob(filt) assert_(len(files) > 0, "No files for test %s using filter %s" % (name, filt)) _load_check_case(name, files, expected) # generator for whos tests def test_whos(): for case in case_table4 + case_table5: name = case['name'] expected = case['expected'] classes = case['classes'] filt = pjoin(test_data_path, 'test%s_*.mat' % name) files = glob(filt) assert_(len(files) > 0, "No files for test %s using filter %s" % (name, filt)) _whos_check_case(name, files, expected, classes) # generator for round trip tests def test_round_trip(): for case in case_table4 + case_table5_rt: case_table4_names = [case['name'] for case in case_table4] name = case['name'] + '_round_trip' expected = case['expected'] for format in (['4', '5'] if case['name'] in case_table4_names else ['5']): _rt_check_case(name, expected, format) def test_gzip_simple(): xdense = np.zeros((20,20)) xdense[2,3] = 2.3 xdense[4,5] = 4.5 x = SP.csc_matrix(xdense) name = 'gzip_test' expected = {'x':x} format = '4' tmpdir = mkdtemp() try: fname = pjoin(tmpdir,name) mat_stream = gzip.open(fname, mode='wb') savemat(mat_stream, expected, format=format) mat_stream.close() mat_stream = gzip.open(fname, mode='rb') actual = loadmat(mat_stream, struct_as_record=True) mat_stream.close() finally: shutil.rmtree(tmpdir) assert_array_almost_equal(actual['x'].todense(), expected['x'].todense(), err_msg=repr(actual)) def test_multiple_open(): # Ticket #1039, on Windows: check that files are not left open tmpdir = mkdtemp() try: x = dict(x=np.zeros((2, 2))) fname = pjoin(tmpdir, "a.mat") # Check that file is not left open savemat(fname, x) os.unlink(fname) savemat(fname, x) loadmat(fname) os.unlink(fname) # Check that stream is left open f = open(fname, 'wb') savemat(f, x) f.seek(0) f.close() f = open(fname, 'rb') loadmat(f) f.seek(0) f.close() finally: shutil.rmtree(tmpdir) def test_mat73(): # Check any hdf5 files raise an error filenames = glob( pjoin(test_data_path, 'testhdf5*.mat')) assert_(len(filenames) > 0) for filename in filenames: fp = open(filename, 'rb') assert_raises(NotImplementedError, loadmat, fp, struct_as_record=True) fp.close() def test_warnings(): # This test is an echo of the previous behavior, which was to raise a # warning if the user triggered a search for mat files on the Python system # path. We can remove the test in the next version after upcoming (0.13). fname = pjoin(test_data_path, 'testdouble_7.1_GLNX86.mat') with warnings.catch_warnings(): warnings.simplefilter('error') # This should not generate a warning loadmat(fname, struct_as_record=True) # This neither loadmat(fname, struct_as_record=False) def test_regression_653(): # Saving a dictionary with only invalid keys used to raise an error. Now we # save this as an empty struct in matlab space. sio = BytesIO() savemat(sio, {'d':{1:2}}, format='5') back = loadmat(sio)['d'] # Check we got an empty struct equivalent assert_equal(back.shape, (1,1)) assert_equal(back.dtype, np.dtype(object)) assert_(back[0,0] is None) def test_structname_len(): # Test limit for length of field names in structs lim = 31 fldname = 'a' * lim st1 = np.zeros((1,1), dtype=[(fldname, object)]) savemat(BytesIO(), {'longstruct': st1}, format='5') fldname = 'a' * (lim+1) st1 = np.zeros((1,1), dtype=[(fldname, object)]) assert_raises(ValueError, savemat, BytesIO(), {'longstruct': st1}, format='5') def test_4_and_long_field_names_incompatible(): # Long field names option not supported in 4 my_struct = np.zeros((1,1),dtype=[('my_fieldname',object)]) assert_raises(ValueError, savemat, BytesIO(), {'my_struct':my_struct}, format='4', long_field_names=True) def test_long_field_names(): # Test limit for length of field names in structs lim = 63 fldname = 'a' * lim st1 = np.zeros((1,1), dtype=[(fldname, object)]) savemat(BytesIO(), {'longstruct': st1}, format='5',long_field_names=True) fldname = 'a' * (lim+1) st1 = np.zeros((1,1), dtype=[(fldname, object)]) assert_raises(ValueError, savemat, BytesIO(), {'longstruct': st1}, format='5',long_field_names=True) def test_long_field_names_in_struct(): # Regression test - long_field_names was erased if you passed a struct # within a struct lim = 63 fldname = 'a' * lim cell = np.ndarray((1,2),dtype=object) st1 = np.zeros((1,1), dtype=[(fldname, object)]) cell[0,0] = st1 cell[0,1] = st1 savemat(BytesIO(), {'longstruct': cell}, format='5',long_field_names=True) # # Check to make sure it fails with long field names off # assert_raises(ValueError, savemat, BytesIO(), {'longstruct': cell}, format='5', long_field_names=False) def test_cell_with_one_thing_in_it(): # Regression test - make a cell array that's 1 x 2 and put two # strings in it. It works. Make a cell array that's 1 x 1 and put # a string in it. It should work but, in the old days, it didn't. cells = np.ndarray((1,2),dtype=object) cells[0,0] = 'Hello' cells[0,1] = 'World' savemat(BytesIO(), {'x': cells}, format='5') cells = np.ndarray((1,1),dtype=object) cells[0,0] = 'Hello, world' savemat(BytesIO(), {'x': cells}, format='5') def test_writer_properties(): # Tests getting, setting of properties of matrix writer mfw = MatFile5Writer(BytesIO()) assert_equal(mfw.global_vars, []) mfw.global_vars = ['avar'] assert_equal(mfw.global_vars, ['avar']) assert_equal(mfw.unicode_strings, False) mfw.unicode_strings = True assert_equal(mfw.unicode_strings, True) assert_equal(mfw.long_field_names, False) mfw.long_field_names = True assert_equal(mfw.long_field_names, True) def test_use_small_element(): # Test whether we're using small data element or not sio = BytesIO() wtr = MatFile5Writer(sio) # First check size for no sde for name arr = np.zeros(10) wtr.put_variables({'aaaaa': arr}) w_sz = len(sio.getvalue()) # Check small name results in largish difference in size sio.truncate(0) sio.seek(0) wtr.put_variables({'aaaa': arr}) assert_(w_sz - len(sio.getvalue()) > 4) # Whereas increasing name size makes less difference sio.truncate(0) sio.seek(0) wtr.put_variables({'aaaaaa': arr}) assert_(len(sio.getvalue()) - w_sz < 4) def test_save_dict(): # Test that dict can be saved (as recarray), loaded as matstruct dict_types = ((dict, False), (OrderedDict, True),) ab_exp = np.array([[(1, 2)]], dtype=[('a', object), ('b', object)]) ba_exp = np.array([[(2, 1)]], dtype=[('b', object), ('a', object)]) for dict_type, is_ordered in dict_types: # Initialize with tuples to keep order for OrderedDict d = dict_type([('a', 1), ('b', 2)]) stream = BytesIO() savemat(stream, {'dict': d}) stream.seek(0) vals = loadmat(stream)['dict'] assert_equal(set(vals.dtype.names), set(['a', 'b'])) if is_ordered: # Input was ordered, output in ab order assert_array_equal(vals, ab_exp) else: # Not ordered input, either order output if vals.dtype.names[0] == 'a': assert_array_equal(vals, ab_exp) else: assert_array_equal(vals, ba_exp) def test_1d_shape(): # New 5 behavior is 1D -> row vector arr = np.arange(5) for format in ('4', '5'): # Column is the default stream = BytesIO() savemat(stream, {'oned': arr}, format=format) vals = loadmat(stream) assert_equal(vals['oned'].shape, (1, 5)) # can be explicitly 'column' for oned_as stream = BytesIO() savemat(stream, {'oned':arr}, format=format, oned_as='column') vals = loadmat(stream) assert_equal(vals['oned'].shape, (5,1)) # but different from 'row' stream = BytesIO() savemat(stream, {'oned':arr}, format=format, oned_as='row') vals = loadmat(stream) assert_equal(vals['oned'].shape, (1,5)) def test_compression(): arr = np.zeros(100).reshape((5,20)) arr[2,10] = 1 stream = BytesIO() savemat(stream, {'arr':arr}) raw_len = len(stream.getvalue()) vals = loadmat(stream) assert_array_equal(vals['arr'], arr) stream = BytesIO() savemat(stream, {'arr':arr}, do_compression=True) compressed_len = len(stream.getvalue()) vals = loadmat(stream) assert_array_equal(vals['arr'], arr) assert_(raw_len > compressed_len) # Concatenate, test later arr2 = arr.copy() arr2[0,0] = 1 stream = BytesIO() savemat(stream, {'arr':arr, 'arr2':arr2}, do_compression=False) vals = loadmat(stream) assert_array_equal(vals['arr2'], arr2) stream = BytesIO() savemat(stream, {'arr':arr, 'arr2':arr2}, do_compression=True) vals = loadmat(stream) assert_array_equal(vals['arr2'], arr2) def test_single_object(): stream = BytesIO() savemat(stream, {'A':np.array(1, dtype=object)}) def test_skip_variable(): # Test skipping over the first of two variables in a MAT file # using mat_reader_factory and put_variables to read them in. # # This is a regression test of a problem that's caused by # using the compressed file reader seek instead of the raw file # I/O seek when skipping over a compressed chunk. # # The problem arises when the chunk is large: this file has # a 256x256 array of random (uncompressible) doubles. # filename = pjoin(test_data_path,'test_skip_variable.mat') # # Prove that it loads with loadmat # d = loadmat(filename, struct_as_record=True) assert_('first' in d) assert_('second' in d) # # Make the factory # factory, file_opened = mat_reader_factory(filename, struct_as_record=True) # # This is where the factory breaks with an error in MatMatrixGetter.to_next # d = factory.get_variables('second') assert_('second' in d) factory.mat_stream.close() def test_empty_struct(): # ticket 885 filename = pjoin(test_data_path,'test_empty_struct.mat') # before ticket fix, this would crash with ValueError, empty data # type d = loadmat(filename, struct_as_record=True) a = d['a'] assert_equal(a.shape, (1,1)) assert_equal(a.dtype, np.dtype(object)) assert_(a[0,0] is None) stream = BytesIO() arr = np.array((), dtype='U') # before ticket fix, this used to give data type not understood savemat(stream, {'arr':arr}) d = loadmat(stream) a2 = d['arr'] assert_array_equal(a2, arr) def test_save_empty_dict(): # saving empty dict also gives empty struct stream = BytesIO() savemat(stream, {'arr': {}}) d = loadmat(stream) a = d['arr'] assert_equal(a.shape, (1,1)) assert_equal(a.dtype, np.dtype(object)) assert_(a[0,0] is None) def assert_any_equal(output, alternatives): """ Assert `output` is equal to at least one element in `alternatives` """ one_equal = False for expected in alternatives: if np.all(output == expected): one_equal = True break assert_(one_equal) def test_to_writeable(): # Test to_writeable function res = to_writeable(np.array([1])) # pass through ndarrays assert_equal(res.shape, (1,)) assert_array_equal(res, 1) # Dict fields can be written in any order expected1 = np.array([(1, 2)], dtype=[('a', '|O8'), ('b', '|O8')]) expected2 = np.array([(2, 1)], dtype=[('b', '|O8'), ('a', '|O8')]) alternatives = (expected1, expected2) assert_any_equal(to_writeable({'a':1,'b':2}), alternatives) # Fields with underscores discarded assert_any_equal(to_writeable({'a':1,'b':2, '_c':3}), alternatives) # Not-string fields discarded assert_any_equal(to_writeable({'a':1,'b':2, 100:3}), alternatives) # String fields that are valid Python identifiers discarded assert_any_equal(to_writeable({'a':1,'b':2, '99':3}), alternatives) # Object with field names is equivalent class klass(object): pass c = klass c.a = 1 c.b = 2 assert_any_equal(to_writeable(c), alternatives) # empty list and tuple go to empty array res = to_writeable([]) assert_equal(res.shape, (0,)) assert_equal(res.dtype.type, np.float64) res = to_writeable(()) assert_equal(res.shape, (0,)) assert_equal(res.dtype.type, np.float64) # None -> None assert_(to_writeable(None) is None) # String to strings assert_equal(to_writeable('a string').dtype.type, np.str_) # Scalars to numpy to NumPy scalars res = to_writeable(1) assert_equal(res.shape, ()) assert_equal(res.dtype.type, np.array(1).dtype.type) assert_array_equal(res, 1) # Empty dict returns EmptyStructMarker assert_(to_writeable({}) is EmptyStructMarker) # Object does not have (even empty) __dict__ assert_(to_writeable(object()) is None) # Custom object does have empty __dict__, returns EmptyStructMarker class C(object): pass assert_(to_writeable(c()) is EmptyStructMarker) # dict keys with legal characters are convertible res = to_writeable({'a': 1})['a'] assert_equal(res.shape, (1,)) assert_equal(res.dtype.type, np.object_) # Only fields with illegal characters, falls back to EmptyStruct assert_(to_writeable({'1':1}) is EmptyStructMarker) assert_(to_writeable({'_a':1}) is EmptyStructMarker) # Unless there are valid fields, in which case structured array assert_equal(to_writeable({'1':1, 'f': 2}), np.array([(2,)], dtype=[('f', '|O8')])) def test_recarray(): # check roundtrip of structured array dt = [('f1', 'f8'), ('f2', 'S10')] arr = np.zeros((2,), dtype=dt) arr[0]['f1'] = 0.5 arr[0]['f2'] = 'python' arr[1]['f1'] = 99 arr[1]['f2'] = 'not perl' stream = BytesIO() savemat(stream, {'arr': arr}) d = loadmat(stream, struct_as_record=False) a20 = d['arr'][0,0] assert_equal(a20.f1, 0.5) assert_equal(a20.f2, 'python') d = loadmat(stream, struct_as_record=True) a20 = d['arr'][0,0] assert_equal(a20['f1'], 0.5) assert_equal(a20['f2'], 'python') # structs always come back as object types assert_equal(a20.dtype, np.dtype([('f1', 'O'), ('f2', 'O')])) a21 = d['arr'].flat[1] assert_equal(a21['f1'], 99) assert_equal(a21['f2'], 'not perl') def test_save_object(): class C(object): pass c = C() c.field1 = 1 c.field2 = 'a string' stream = BytesIO() savemat(stream, {'c': c}) d = loadmat(stream, struct_as_record=False) c2 = d['c'][0,0] assert_equal(c2.field1, 1) assert_equal(c2.field2, 'a string') d = loadmat(stream, struct_as_record=True) c2 = d['c'][0,0] assert_equal(c2['field1'], 1) assert_equal(c2['field2'], 'a string') def test_read_opts(): # tests if read is seeing option sets, at initialization and after # initialization arr = np.arange(6).reshape(1,6) stream = BytesIO() savemat(stream, {'a': arr}) rdr = MatFile5Reader(stream) back_dict = rdr.get_variables() rarr = back_dict['a'] assert_array_equal(rarr, arr) rdr = MatFile5Reader(stream, squeeze_me=True) assert_array_equal(rdr.get_variables()['a'], arr.reshape((6,))) rdr.squeeze_me = False assert_array_equal(rarr, arr) rdr = MatFile5Reader(stream, byte_order=boc.native_code) assert_array_equal(rdr.get_variables()['a'], arr) # inverted byte code leads to error on read because of swapped # header etc. rdr = MatFile5Reader(stream, byte_order=boc.swapped_code) assert_raises(Exception, rdr.get_variables) rdr.byte_order = boc.native_code assert_array_equal(rdr.get_variables()['a'], arr) arr = np.array(['a string']) stream.truncate(0) stream.seek(0) savemat(stream, {'a': arr}) rdr = MatFile5Reader(stream) assert_array_equal(rdr.get_variables()['a'], arr) rdr = MatFile5Reader(stream, chars_as_strings=False) carr = np.atleast_2d(np.array(list(arr.item()), dtype='U1')) assert_array_equal(rdr.get_variables()['a'], carr) rdr.chars_as_strings = True assert_array_equal(rdr.get_variables()['a'], arr) def test_empty_string(): # make sure reading empty string does not raise error estring_fname = pjoin(test_data_path, 'single_empty_string.mat') fp = open(estring_fname, 'rb') rdr = MatFile5Reader(fp) d = rdr.get_variables() fp.close() assert_array_equal(d['a'], np.array([], dtype='U1')) # Empty string round trip. Matlab cannot distinguish # between a string array that is empty, and a string array # containing a single empty string, because it stores strings as # arrays of char. There is no way of having an array of char that # is not empty, but contains an empty string. stream = BytesIO() savemat(stream, {'a': np.array([''])}) rdr = MatFile5Reader(stream) d = rdr.get_variables() assert_array_equal(d['a'], np.array([], dtype='U1')) stream.truncate(0) stream.seek(0) savemat(stream, {'a': np.array([], dtype='U1')}) rdr = MatFile5Reader(stream) d = rdr.get_variables() assert_array_equal(d['a'], np.array([], dtype='U1')) stream.close() def test_corrupted_data(): import zlib for exc, fname in [(ValueError, 'corrupted_zlib_data.mat'), (zlib.error, 'corrupted_zlib_checksum.mat')]: with open(pjoin(test_data_path, fname), 'rb') as fp: rdr = MatFile5Reader(fp) assert_raises(exc, rdr.get_variables) def test_corrupted_data_check_can_be_disabled(): with open(pjoin(test_data_path, 'corrupted_zlib_data.mat'), 'rb') as fp: rdr = MatFile5Reader(fp, verify_compressed_data_integrity=False) rdr.get_variables() def test_read_both_endian(): # make sure big- and little- endian data is read correctly for fname in ('big_endian.mat', 'little_endian.mat'): fp = open(pjoin(test_data_path, fname), 'rb') rdr = MatFile5Reader(fp) d = rdr.get_variables() fp.close() assert_array_equal(d['strings'], np.array([['hello'], ['world']], dtype=object)) assert_array_equal(d['floats'], np.array([[2., 3.], [3., 4.]], dtype=np.float32)) def test_write_opposite_endian(): # We don't support writing opposite endian .mat files, but we need to behave # correctly if the user supplies an other-endian NumPy array to write out. float_arr = np.array([[2., 3.], [3., 4.]]) int_arr = np.arange(6).reshape((2, 3)) uni_arr = np.array(['hello', 'world'], dtype='U') stream = BytesIO() savemat(stream, {'floats': float_arr.byteswap().newbyteorder(), 'ints': int_arr.byteswap().newbyteorder(), 'uni_arr': uni_arr.byteswap().newbyteorder()}) rdr = MatFile5Reader(stream) d = rdr.get_variables() assert_array_equal(d['floats'], float_arr) assert_array_equal(d['ints'], int_arr) assert_array_equal(d['uni_arr'], uni_arr) stream.close() def test_logical_array(): # The roundtrip test doesn't verify that we load the data up with the # correct (bool) dtype with open(pjoin(test_data_path, 'testbool_8_WIN64.mat'), 'rb') as fobj: rdr = MatFile5Reader(fobj, mat_dtype=True) d = rdr.get_variables() x = np.array([[True], [False]], dtype=np.bool_) assert_array_equal(d['testbools'], x) assert_equal(d['testbools'].dtype, x.dtype) def test_logical_out_type(): # Confirm that bool type written as uint8, uint8 class # See gh-4022 stream = BytesIO() barr = np.array([False, True, False]) savemat(stream, {'barray': barr}) stream.seek(0) reader = MatFile5Reader(stream) reader.initialize_read() reader.read_file_header() hdr, _ = reader.read_var_header() assert_equal(hdr.mclass, mio5p.mxUINT8_CLASS) assert_equal(hdr.is_logical, True) var = reader.read_var_array(hdr, False) assert_equal(var.dtype.type, np.uint8) def test_mat4_3d(): # test behavior when writing 3-D arrays to matlab 4 files stream = BytesIO() arr = np.arange(24).reshape((2,3,4)) assert_raises(ValueError, savemat, stream, {'a': arr}, True, '4') def test_func_read(): func_eg = pjoin(test_data_path, 'testfunc_7.4_GLNX86.mat') fp = open(func_eg, 'rb') rdr = MatFile5Reader(fp) d = rdr.get_variables() fp.close() assert_(isinstance(d['testfunc'], MatlabFunction)) stream = BytesIO() wtr = MatFile5Writer(stream) assert_raises(MatWriteError, wtr.put_variables, d) def test_mat_dtype(): double_eg = pjoin(test_data_path, 'testmatrix_6.1_SOL2.mat') fp = open(double_eg, 'rb') rdr = MatFile5Reader(fp, mat_dtype=False) d = rdr.get_variables() fp.close() assert_equal(d['testmatrix'].dtype.kind, 'u') fp = open(double_eg, 'rb') rdr = MatFile5Reader(fp, mat_dtype=True) d = rdr.get_variables() fp.close() assert_equal(d['testmatrix'].dtype.kind, 'f') def test_sparse_in_struct(): # reproduces bug found by DC where Cython code was insisting on # ndarray return type, but getting sparse matrix st = {'sparsefield': SP.coo_matrix(np.eye(4))} stream = BytesIO() savemat(stream, {'a':st}) d = loadmat(stream, struct_as_record=True) assert_array_equal(d['a'][0,0]['sparsefield'].todense(), np.eye(4)) def test_mat_struct_squeeze(): stream = BytesIO() in_d = {'st':{'one':1, 'two':2}} savemat(stream, in_d) # no error without squeeze loadmat(stream, struct_as_record=False) # previous error was with squeeze, with mat_struct loadmat(stream, struct_as_record=False, squeeze_me=True) def test_scalar_squeeze(): stream = BytesIO() in_d = {'scalar': [[0.1]], 'string': 'my name', 'st':{'one':1, 'two':2}} savemat(stream, in_d) out_d = loadmat(stream, squeeze_me=True) assert_(isinstance(out_d['scalar'], float)) assert_(isinstance(out_d['string'], str)) assert_(isinstance(out_d['st'], np.ndarray)) def test_str_round(): # from report by Angus McMorland on mailing list 3 May 2010 stream = BytesIO() in_arr = np.array(['Hello', 'Foob']) out_arr = np.array(['Hello', 'Foob ']) savemat(stream, dict(a=in_arr)) res = loadmat(stream) # resulted in ['HloolFoa', 'elWrdobr'] assert_array_equal(res['a'], out_arr) stream.truncate(0) stream.seek(0) # Make Fortran ordered version of string in_str = in_arr.tostring(order='F') in_from_str = np.ndarray(shape=a.shape, dtype=in_arr.dtype, order='F', buffer=in_str) savemat(stream, dict(a=in_from_str)) assert_array_equal(res['a'], out_arr) # unicode save did lead to buffer too small error stream.truncate(0) stream.seek(0) in_arr_u = in_arr.astype('U') out_arr_u = out_arr.astype('U') savemat(stream, {'a': in_arr_u}) res = loadmat(stream) assert_array_equal(res['a'], out_arr_u) def test_fieldnames(): # Check that field names are as expected stream = BytesIO() savemat(stream, {'a': {'a':1, 'b':2}}) res = loadmat(stream) field_names = res['a'].dtype.names assert_equal(set(field_names), set(('a', 'b'))) def test_loadmat_varnames(): # Test that we can get just one variable from a mat file using loadmat mat5_sys_names = ['__globals__', '__header__', '__version__'] for eg_file, sys_v_names in ( (pjoin(test_data_path, 'testmulti_4.2c_SOL2.mat'), []), (pjoin( test_data_path, 'testmulti_7.4_GLNX86.mat'), mat5_sys_names)): vars = loadmat(eg_file) assert_equal(set(vars.keys()), set(['a', 'theta'] + sys_v_names)) vars = loadmat(eg_file, variable_names='a') assert_equal(set(vars.keys()), set(['a'] + sys_v_names)) vars = loadmat(eg_file, variable_names=['a']) assert_equal(set(vars.keys()), set(['a'] + sys_v_names)) vars = loadmat(eg_file, variable_names=['theta']) assert_equal(set(vars.keys()), set(['theta'] + sys_v_names)) vars = loadmat(eg_file, variable_names=('theta',)) assert_equal(set(vars.keys()), set(['theta'] + sys_v_names)) vars = loadmat(eg_file, variable_names=[]) assert_equal(set(vars.keys()), set(sys_v_names)) vnames = ['theta'] vars = loadmat(eg_file, variable_names=vnames) assert_equal(vnames, ['theta']) def test_round_types(): # Check that saving, loading preserves dtype in most cases arr = np.arange(10) stream = BytesIO() for dts in ('f8','f4','i8','i4','i2','i1', 'u8','u4','u2','u1','c16','c8'): stream.truncate(0) stream.seek(0) # needed for BytesIO in Python 3 savemat(stream, {'arr': arr.astype(dts)}) vars = loadmat(stream) assert_equal(np.dtype(dts), vars['arr'].dtype) def test_varmats_from_mat(): # Make a mat file with several variables, write it, read it back names_vars = (('arr', mlarr(np.arange(10))), ('mystr', mlarr('a string')), ('mynum', mlarr(10))) # Dict like thing to give variables in defined order class C(object): def items(self): return names_vars stream = BytesIO() savemat(stream, C()) varmats = varmats_from_mat(stream) assert_equal(len(varmats), 3) for i in range(3): name, var_stream = varmats[i] exp_name, exp_res = names_vars[i] assert_equal(name, exp_name) res = loadmat(var_stream) assert_array_equal(res[name], exp_res) def test_one_by_zero(): # Test 1x0 chars get read correctly func_eg = pjoin(test_data_path, 'one_by_zero_char.mat') fp = open(func_eg, 'rb') rdr = MatFile5Reader(fp) d = rdr.get_variables() fp.close() assert_equal(d['var'].shape, (0,)) def test_load_mat4_le(): # We were getting byte order wrong when reading little-endian floa64 dense # matrices on big-endian platforms mat4_fname = pjoin(test_data_path, 'test_mat4_le_floats.mat') vars = loadmat(mat4_fname) assert_array_equal(vars['a'], [[0.1, 1.2]]) def test_unicode_mat4(): # Mat4 should save unicode as latin1 bio = BytesIO() var = {'second_cat': 'Schrödinger'} savemat(bio, var, format='4') var_back = loadmat(bio) assert_equal(var_back['second_cat'], var['second_cat']) def test_logical_sparse(): # Test we can read logical sparse stored in mat file as bytes. # See https://github.com/scipy/scipy/issues/3539. # In some files saved by MATLAB, the sparse data elements (Real Part # Subelement in MATLAB speak) are stored with apparent type double # (miDOUBLE) but are in fact single bytes. filename = pjoin(test_data_path,'logical_sparse.mat') # Before fix, this would crash with: # ValueError: indices and data should have the same size d = loadmat(filename, struct_as_record=True) log_sp = d['sp_log_5_4'] assert_(isinstance(log_sp, SP.csc_matrix)) assert_equal(log_sp.dtype.type, np.bool_) assert_array_equal(log_sp.toarray(), [[True, True, True, False], [False, False, True, False], [False, False, True, False], [False, False, False, False], [False, False, False, False]]) def test_empty_sparse(): # Can we read empty sparse matrices? sio = BytesIO() import scipy.sparse empty_sparse = scipy.sparse.csr_matrix([[0,0],[0,0]]) savemat(sio, dict(x=empty_sparse)) sio.seek(0) res = loadmat(sio) assert_array_equal(res['x'].shape, empty_sparse.shape) assert_array_equal(res['x'].todense(), 0) # Do empty sparse matrices get written with max nnz 1? # See https://github.com/scipy/scipy/issues/4208 sio.seek(0) reader = MatFile5Reader(sio) reader.initialize_read() reader.read_file_header() hdr, _ = reader.read_var_header() assert_equal(hdr.nzmax, 1) def test_empty_mat_error(): # Test we get a specific warning for an empty mat file sio = BytesIO() assert_raises(MatReadError, loadmat, sio) def test_miuint32_compromise(): # Reader should accept miUINT32 for miINT32, but check signs # mat file with miUINT32 for miINT32, but OK values filename = pjoin(test_data_path, 'miuint32_for_miint32.mat') res = loadmat(filename) assert_equal(res['an_array'], np.arange(10)[None, :]) # mat file with miUINT32 for miINT32, with negative value filename = pjoin(test_data_path, 'bad_miuint32.mat') with assert_raises(ValueError): loadmat(filename) def test_miutf8_for_miint8_compromise(): # Check reader accepts ascii as miUTF8 for array names filename = pjoin(test_data_path, 'miutf8_array_name.mat') res = loadmat(filename) assert_equal(res['array_name'], [[1]]) # mat file with non-ascii utf8 name raises error filename = pjoin(test_data_path, 'bad_miutf8_array_name.mat') with assert_raises(ValueError): loadmat(filename) def test_bad_utf8(): # Check that reader reads bad UTF with 'replace' option filename = pjoin(test_data_path,'broken_utf8.mat') res = loadmat(filename) assert_equal(res['bad_string'], b'\x80 am broken'.decode('utf8', 'replace')) def test_save_unicode_field(tmpdir): filename = os.path.join(str(tmpdir), 'test.mat') test_dict = {u'a':{u'b':1,u'c':'test_str'}} savemat(filename, test_dict) def test_filenotfound(): # Check the correct error is thrown assert_raises(IOError, loadmat, "NotExistentFile00.mat") assert_raises(IOError, loadmat, "NotExistentFile00")
# this program corresponds to special.py ### Means test is not done yet # E Means test is giving error (E) # F Means test is failing (F) # EF Means test is giving error and Failing #! Means test is segfaulting # 8 Means test runs forever ### test_besselpoly ### test_mathieu_a ### test_mathieu_even_coef ### test_mathieu_odd_coef ### test_modfresnelp ### test_modfresnelm # test_pbdv_seq ### test_pbvv_seq ### test_sph_harm import itertools import platform import numpy as np from numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp, log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, float_) import pytest from pytest import raises as assert_raises from numpy.testing import (assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_approx_equal, assert_, assert_allclose, assert_array_almost_equal_nulp, suppress_warnings) from scipy import special import scipy.special._ufuncs as cephes from scipy.special import ellipk from scipy.special._testutils import with_special_errors, \ assert_func_equal, FuncData import math class TestCephes(object): def test_airy(self): cephes.airy(0) def test_airye(self): cephes.airye(0) def test_binom(self): n = np.array([0.264, 4, 5.2, 17]) k = np.array([2, 0.4, 7, 3.3]) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389, -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846], [10.92, 2.22993515861399, -0.00585728, 10.468891352063146], [136, 3.5252179590758828, 19448, 1024.5526916174495]]) assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13) # Test branches in implementation np.random.seed(1234) n = np.r_[np.arange(-7, 30), 1000*np.random.rand(30) - 500] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_2(self): # Test branches in implementation np.random.seed(1234) n = np.r_[np.logspace(1, 300, 20)] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_exact(self): @np.vectorize def binom_int(n, k): n = int(n) k = int(k) num = int(1) den = int(1) for i in range(1, k+1): num *= i + n - k den *= i return float(num/den) np.random.seed(1234) n = np.arange(1, 15) k = np.arange(0, 15) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T nk = nk[nk[:,0] >= nk[:,1]] assert_func_equal(cephes.binom, binom_int(nk[:,0], nk[:,1]), nk, atol=0, rtol=0) def test_binom_nooverflow_8346(self): # Test (binom(n, k) doesn't overflow prematurely */ dataset = [ (1000, 500, 2.70288240945436551e+299), (1002, 501, 1.08007396880791225e+300), (1004, 502, 4.31599279169058121e+300), (1006, 503, 1.72468101616263781e+301), (1008, 504, 6.89188009236419153e+301), (1010, 505, 2.75402257948335448e+302), (1012, 506, 1.10052048531923757e+303), (1014, 507, 4.39774063758732849e+303), (1016, 508, 1.75736486108312519e+304), (1018, 509, 7.02255427788423734e+304), (1020, 510, 2.80626776829962255e+305), (1022, 511, 1.12140876377061240e+306), (1024, 512, 4.48125455209897109e+306), (1026, 513, 1.79075474304149900e+307), (1028, 514, 7.15605105487789676e+307) ] dataset = np.asarray(dataset) FuncData(cephes.binom, dataset, (0, 1), 2, rtol=1e-12).check() def test_bdtr(self): assert_equal(cephes.bdtr(1,1,0.5),1.0) def test_bdtri(self): assert_equal(cephes.bdtri(1,3,0.5),0.5) def test_bdtrc(self): assert_equal(cephes.bdtrc(1,3,0.5),0.5) def test_bdtrin(self): assert_equal(cephes.bdtrin(1,0,1),5.0) def test_bdtrik(self): cephes.bdtrik(1,3,0.5) def test_bei(self): assert_equal(cephes.bei(0),0.0) def test_beip(self): assert_equal(cephes.beip(0),0.0) def test_ber(self): assert_equal(cephes.ber(0),1.0) def test_berp(self): assert_equal(cephes.berp(0),0.0) def test_besselpoly(self): assert_equal(cephes.besselpoly(0,0,0),1.0) def test_beta(self): assert_equal(cephes.beta(1,1),1.0) assert_allclose(cephes.beta(-100.3, 1e-200), cephes.gamma(1e-200)) assert_allclose(cephes.beta(0.0342, 171), 24.070498359873497, rtol=1e-13, atol=0) def test_betainc(self): assert_equal(cephes.betainc(1,1,1),1.0) assert_allclose(cephes.betainc(0.0342, 171, 1e-10), 0.55269916901806648) def test_betaln(self): assert_equal(cephes.betaln(1,1),0.0) assert_allclose(cephes.betaln(-100.3, 1e-200), cephes.gammaln(1e-200)) assert_allclose(cephes.betaln(0.0342, 170), 3.1811881124242447, rtol=1e-14, atol=0) def test_betaincinv(self): assert_equal(cephes.betaincinv(1,1,1),1.0) assert_allclose(cephes.betaincinv(0.0342, 171, 0.25), 8.4231316935498957e-21, rtol=3e-12, atol=0) def test_beta_inf(self): assert_(np.isinf(special.beta(-1, 2))) def test_btdtr(self): assert_equal(cephes.btdtr(1,1,1),1.0) def test_btdtri(self): assert_equal(cephes.btdtri(1,1,1),1.0) def test_btdtria(self): assert_equal(cephes.btdtria(1,1,1),5.0) def test_btdtrib(self): assert_equal(cephes.btdtrib(1,1,1),5.0) def test_cbrt(self): assert_approx_equal(cephes.cbrt(1),1.0) def test_chdtr(self): assert_equal(cephes.chdtr(1,0),0.0) def test_chdtrc(self): assert_equal(cephes.chdtrc(1,0),1.0) def test_chdtri(self): assert_equal(cephes.chdtri(1,1),0.0) def test_chdtriv(self): assert_equal(cephes.chdtriv(0,0),5.0) def test_chndtr(self): assert_equal(cephes.chndtr(0,1,0),0.0) # Each row holds (x, nu, lam, expected_value) # These values were computed using Wolfram Alpha with # CDF[NoncentralChiSquareDistribution[nu, lam], x] values = np.array([ [25.00, 20.0, 400, 4.1210655112396197139e-57], [25.00, 8.00, 250, 2.3988026526832425878e-29], [0.001, 8.00, 40., 5.3761806201366039084e-24], [0.010, 8.00, 40., 5.45396231055999457039e-20], [20.00, 2.00, 107, 1.39390743555819597802e-9], [22.50, 2.00, 107, 7.11803307138105870671e-9], [25.00, 2.00, 107, 3.11041244829864897313e-8], [3.000, 2.00, 1.0, 0.62064365321954362734], [350.0, 300., 10., 0.93880128006276407710], [100.0, 13.5, 10., 0.99999999650104210949], [700.0, 20.0, 400, 0.99999999925680650105], [150.0, 13.5, 10., 0.99999999999999983046], [160.0, 13.5, 10., 0.99999999999999999518], # 1.0 ]) cdf = cephes.chndtr(values[:, 0], values[:, 1], values[:, 2]) assert_allclose(cdf, values[:, 3], rtol=1e-12) assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0) assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0) assert_(np.isnan(cephes.chndtr(np.nan, 1, 2))) assert_(np.isnan(cephes.chndtr(5, np.nan, 2))) assert_(np.isnan(cephes.chndtr(5, 1, np.nan))) def test_chndtridf(self): assert_equal(cephes.chndtridf(0,0,1),5.0) def test_chndtrinc(self): assert_equal(cephes.chndtrinc(0,1,0),5.0) def test_chndtrix(self): assert_equal(cephes.chndtrix(0,1,0),0.0) def test_cosdg(self): assert_equal(cephes.cosdg(0),1.0) def test_cosm1(self): assert_equal(cephes.cosm1(0),0.0) def test_cotdg(self): assert_almost_equal(cephes.cotdg(45),1.0) def test_dawsn(self): assert_equal(cephes.dawsn(0),0.0) assert_allclose(cephes.dawsn(1.23), 0.50053727749081767) def test_diric(self): # Test behavior near multiples of 2pi. Regression test for issue # described in gh-4001. n_odd = [1, 5, 25] x = np.array(2*np.pi + 5e-5).astype(np.float32) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7) x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) x = np.array(2*np.pi + 1e-15).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) if hasattr(np, 'float128'): # No float128 available in 32-bit numpy x = np.array(2*np.pi + 1e-12).astype(np.float128) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19) n_even = [2, 4, 24] x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15) # Test at some values not near a multiple of pi x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi) octave_result = [0.872677996249965, 0.539344662916632, 0.127322003750035, -0.206011329583298] assert_almost_equal(special.diric(x, 3), octave_result, decimal=15) def test_diric_broadcasting(self): x = np.arange(5) n = np.array([1, 3, 7]) assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size)) def test_ellipe(self): assert_equal(cephes.ellipe(1),1.0) def test_ellipeinc(self): assert_equal(cephes.ellipeinc(0,1),0.0) def test_ellipj(self): cephes.ellipj(0,1) def test_ellipk(self): assert_allclose(ellipk(0), pi/2) def test_ellipkinc(self): assert_equal(cephes.ellipkinc(0,0),0.0) def test_erf(self): assert_equal(cephes.erf(0), 0.0) def test_erf_symmetry(self): x = 5.905732037710919 assert_equal(cephes.erf(x) + cephes.erf(-x), 0.0) def test_erfc(self): assert_equal(cephes.erfc(0), 1.0) def test_exp10(self): assert_approx_equal(cephes.exp10(2),100.0) def test_exp2(self): assert_equal(cephes.exp2(2),4.0) def test_expm1(self): assert_equal(cephes.expm1(0),0.0) assert_equal(cephes.expm1(np.inf), np.inf) assert_equal(cephes.expm1(-np.inf), -1) assert_equal(cephes.expm1(np.nan), np.nan) def test_expm1_complex(self): expm1 = cephes.expm1 assert_equal(expm1(0 + 0j), 0 + 0j) assert_equal(expm1(complex(np.inf, 0)), complex(np.inf, 0)) assert_equal(expm1(complex(np.inf, 1)), complex(np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 2)), complex(-np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 4)), complex(-np.inf, -np.inf)) assert_equal(expm1(complex(np.inf, 5)), complex(np.inf, -np.inf)) assert_equal(expm1(complex(1, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(0, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.inf, np.inf)), complex(np.inf, np.nan)) assert_equal(expm1(complex(-np.inf, np.inf)), complex(-1, 0)) assert_equal(expm1(complex(-np.inf, np.nan)), complex(-1, 0)) assert_equal(expm1(complex(np.inf, np.nan)), complex(np.inf, np.nan)) assert_equal(expm1(complex(0, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(1, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, 1)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, np.nan)), complex(np.nan, np.nan)) @pytest.mark.xfail(reason='The real part of expm1(z) bad at these points') def test_expm1_complex_hard(self): # The real part of this function is difficult to evaluate when # z.real = -log(cos(z.imag)). y = np.array([0.1, 0.2, 0.3, 5, 11, 20]) x = -np.log(np.cos(y)) z = x + 1j*y # evaluate using mpmath.expm1 with dps=1000 expected = np.array([-5.5507901846769623e-17+0.10033467208545054j, 2.4289354732893695e-18+0.20271003550867248j, 4.5235500262585768e-17+0.30933624960962319j, 7.8234305217489006e-17-3.3805150062465863j, -1.3685191953697676e-16-225.95084645419513j, 8.7175620481291045e-17+2.2371609442247422j]) found = cephes.expm1(z) # this passes. assert_array_almost_equal_nulp(found.imag, expected.imag, 3) # this fails. assert_array_almost_equal_nulp(found.real, expected.real, 20) def test_fdtr(self): assert_equal(cephes.fdtr(1, 1, 0), 0.0) # Computed using Wolfram Alpha: CDF[FRatioDistribution[1e-6, 5], 10] assert_allclose(cephes.fdtr(1e-6, 5, 10), 0.9999940790193488, rtol=1e-12) def test_fdtrc(self): assert_equal(cephes.fdtrc(1, 1, 0), 1.0) # Computed using Wolfram Alpha: # 1 - CDF[FRatioDistribution[2, 1/10], 1e10] assert_allclose(cephes.fdtrc(2, 0.1, 1e10), 0.27223784621293512, rtol=1e-12) def test_fdtri(self): assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]), array([0.9937365, 1.00630298]), rtol=1e-6) # From Wolfram Alpha: # CDF[FRatioDistribution[1/10, 1], 3] = 0.8756751669632105666874... p = 0.8756751669632105666874 assert_allclose(cephes.fdtri(0.1, 1, p), 3, rtol=1e-12) @pytest.mark.xfail(reason='Returns nan on i686.') def test_fdtri_mysterious_failure(self): assert_allclose(cephes.fdtri(1, 1, 0.5), 1) def test_fdtridfd(self): assert_equal(cephes.fdtridfd(1,0,0),5.0) def test_fresnel(self): assert_equal(cephes.fresnel(0),(0.0,0.0)) def test_gamma(self): assert_equal(cephes.gamma(5),24.0) def test_gammainccinv(self): assert_equal(cephes.gammainccinv(5,1),0.0) def test_gammaln(self): cephes.gammaln(10) def test_gammasgn(self): vals = np.array([-4, -3.5, -2.3, 1, 4.2], np.float64) assert_array_equal(cephes.gammasgn(vals), np.sign(cephes.rgamma(vals))) def test_gdtr(self): assert_equal(cephes.gdtr(1,1,0),0.0) def test_gdtr_inf(self): assert_equal(cephes.gdtr(1,1,np.inf),1.0) def test_gdtrc(self): assert_equal(cephes.gdtrc(1,1,0),1.0) def test_gdtria(self): assert_equal(cephes.gdtria(0,1,1),0.0) def test_gdtrib(self): cephes.gdtrib(1,0,1) # assert_equal(cephes.gdtrib(1,0,1),5.0) def test_gdtrix(self): cephes.gdtrix(1,1,.1) def test_hankel1(self): cephes.hankel1(1,1) def test_hankel1e(self): cephes.hankel1e(1,1) def test_hankel2(self): cephes.hankel2(1,1) def test_hankel2e(self): cephes.hankel2e(1,1) def test_hyp1f1(self): assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) cephes.hyp1f1(1,1,1) def test_hyp2f1(self): assert_equal(cephes.hyp2f1(1,1,1,0),1.0) def test_i0(self): assert_equal(cephes.i0(0),1.0) def test_i0e(self): assert_equal(cephes.i0e(0),1.0) def test_i1(self): assert_equal(cephes.i1(0),0.0) def test_i1e(self): assert_equal(cephes.i1e(0),0.0) def test_it2i0k0(self): cephes.it2i0k0(1) def test_it2j0y0(self): cephes.it2j0y0(1) def test_it2struve0(self): cephes.it2struve0(1) def test_itairy(self): cephes.itairy(1) def test_iti0k0(self): assert_equal(cephes.iti0k0(0),(0.0,0.0)) def test_itj0y0(self): assert_equal(cephes.itj0y0(0),(0.0,0.0)) def test_itmodstruve0(self): assert_equal(cephes.itmodstruve0(0),0.0) def test_itstruve0(self): assert_equal(cephes.itstruve0(0),0.0) def test_iv(self): assert_equal(cephes.iv(1,0),0.0) def _check_ive(self): assert_equal(cephes.ive(1,0),0.0) def test_j0(self): assert_equal(cephes.j0(0),1.0) def test_j1(self): assert_equal(cephes.j1(0),0.0) def test_jn(self): assert_equal(cephes.jn(0,0),1.0) def test_jv(self): assert_equal(cephes.jv(0,0),1.0) def _check_jve(self): assert_equal(cephes.jve(0,0),1.0) def test_k0(self): cephes.k0(2) def test_k0e(self): cephes.k0e(2) def test_k1(self): cephes.k1(2) def test_k1e(self): cephes.k1e(2) def test_kei(self): cephes.kei(2) def test_keip(self): assert_equal(cephes.keip(0),0.0) def test_ker(self): cephes.ker(2) def test_kerp(self): cephes.kerp(2) def _check_kelvin(self): cephes.kelvin(2) def test_kn(self): cephes.kn(1,1) def test_kolmogi(self): assert_equal(cephes.kolmogi(1),0.0) assert_(np.isnan(cephes.kolmogi(np.nan))) def test_kolmogorov(self): assert_equal(cephes.kolmogorov(0), 1.0) def test_kolmogp(self): assert_equal(cephes._kolmogp(0), -0.0) def test_kolmogc(self): assert_equal(cephes._kolmogc(0), 0.0) def test_kolmogci(self): assert_equal(cephes._kolmogci(0), 0.0) assert_(np.isnan(cephes._kolmogci(np.nan))) def _check_kv(self): cephes.kv(1,1) def _check_kve(self): cephes.kve(1,1) def test_log1p(self): log1p = cephes.log1p assert_equal(log1p(0), 0.0) assert_equal(log1p(-1), -np.inf) assert_equal(log1p(-2), np.nan) assert_equal(log1p(np.inf), np.inf) def test_log1p_complex(self): log1p = cephes.log1p c = complex assert_equal(log1p(0 + 0j), 0 + 0j) assert_equal(log1p(c(-1, 0)), c(-np.inf, 0)) with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in multiply") assert_allclose(log1p(c(1, np.inf)), c(np.inf, np.pi/2)) assert_equal(log1p(c(1, np.nan)), c(np.nan, np.nan)) assert_allclose(log1p(c(-np.inf, 1)), c(np.inf, np.pi)) assert_equal(log1p(c(np.inf, 1)), c(np.inf, 0)) assert_allclose(log1p(c(-np.inf, np.inf)), c(np.inf, 3*np.pi/4)) assert_allclose(log1p(c(np.inf, np.inf)), c(np.inf, np.pi/4)) assert_equal(log1p(c(np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(-np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, np.inf)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, 1)), c(np.nan, np.nan)) assert_equal(log1p(c(np.nan, np.nan)), c(np.nan, np.nan)) def test_lpmv(self): assert_equal(cephes.lpmv(0,0,1),1.0) def test_mathieu_a(self): assert_equal(cephes.mathieu_a(1,0),1.0) def test_mathieu_b(self): assert_equal(cephes.mathieu_b(1,0),1.0) def test_mathieu_cem(self): assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) # Test AMS 20.2.27 @np.vectorize def ce_smallq(m, q, z): z *= np.pi/180 if m == 0: return 2**(-0.5) * (1 - .5*q*cos(2*z)) # + O(q^2) elif m == 1: return cos(z) - q/8 * cos(3*z) # + O(q^2) elif m == 2: return cos(2*z) - q*(cos(4*z)/12 - 1/4) # + O(q^2) else: return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(0, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0], ce_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_sem(self): assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) # Test AMS 20.2.27 @np.vectorize def se_smallq(m, q, z): z *= np.pi/180 if m == 1: return sin(z) - q/8 * sin(3*z) # + O(q^2) elif m == 2: return sin(2*z) - q*sin(4*z)/12 # + O(q^2) else: return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(1, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0], se_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_modcem1(self): assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) def test_mathieu_modcem2(self): cephes.mathieu_modcem2(1,1,1) # Test reflection relation AMS 20.6.19 m = np.arange(0, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modcem2(m, q, -z)[0] fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0] y2 = -cephes.mathieu_modcem2(m, q, z)[0] - 2*fr*cephes.mathieu_modcem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_modsem1(self): assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) def test_mathieu_modsem2(self): cephes.mathieu_modsem2(1,1,1) # Test reflection relation AMS 20.6.20 m = np.arange(1, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modsem2(m, q, -z)[0] fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1] y2 = cephes.mathieu_modsem2(m, q, z)[0] - 2*fr*cephes.mathieu_modsem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_overflow(self): # Check that these return NaNs instead of causing a SEGV assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan)) def test_mathieu_ticket_1847(self): # Regression test --- this call had some out-of-bounds access # and could return nan occasionally for k in range(60): v = cephes.mathieu_modsem2(2, 100, -1) # Values from ACM TOMS 804 (derivate by numerical differentiation) assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10) assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4) def test_modfresnelm(self): cephes.modfresnelm(0) def test_modfresnelp(self): cephes.modfresnelp(0) def _check_modstruve(self): assert_equal(cephes.modstruve(1,0),0.0) def test_nbdtr(self): assert_equal(cephes.nbdtr(1,1,1),1.0) def test_nbdtrc(self): assert_equal(cephes.nbdtrc(1,1,1),0.0) def test_nbdtri(self): assert_equal(cephes.nbdtri(1,1,1),1.0) def __check_nbdtrik(self): cephes.nbdtrik(1,.4,.5) def test_nbdtrin(self): assert_equal(cephes.nbdtrin(1,0,0),5.0) def test_ncfdtr(self): assert_equal(cephes.ncfdtr(1,1,1,0),0.0) def test_ncfdtri(self): assert_equal(cephes.ncfdtri(1, 1, 1, 0), 0.0) f = [0.5, 1, 1.5] p = cephes.ncfdtr(2, 3, 1.5, f) assert_allclose(cephes.ncfdtri(2, 3, 1.5, p), f) def test_ncfdtridfd(self): dfd = [1, 2, 3] p = cephes.ncfdtr(2, dfd, 0.25, 15) assert_allclose(cephes.ncfdtridfd(2, p, 0.25, 15), dfd) def test_ncfdtridfn(self): dfn = [0.1, 1, 2, 3, 1e4] p = cephes.ncfdtr(dfn, 2, 0.25, 15) assert_allclose(cephes.ncfdtridfn(p, 2, 0.25, 15), dfn, rtol=1e-5) def test_ncfdtrinc(self): nc = [0.5, 1.5, 2.0] p = cephes.ncfdtr(2, 3, nc, 15) assert_allclose(cephes.ncfdtrinc(2, 3, p, 15), nc) def test_nctdtr(self): assert_equal(cephes.nctdtr(1,0,0),0.5) assert_equal(cephes.nctdtr(9, 65536, 45), 0.0) assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5) assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.))) assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.) assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.))) assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.))) assert_(np.isnan(cephes.nctdtr(2., 1., np.nan))) def __check_nctdtridf(self): cephes.nctdtridf(1,0.5,0) def test_nctdtrinc(self): cephes.nctdtrinc(1,0,0) def test_nctdtrit(self): cephes.nctdtrit(.1,0.2,.5) def test_nrdtrimn(self): assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) def test_nrdtrisd(self): assert_allclose(cephes.nrdtrisd(0.5,0.5,0.5), 0.0, atol=0, rtol=0) def test_obl_ang1(self): cephes.obl_ang1(1,1,1,0) def test_obl_ang1_cv(self): result = cephes.obl_ang1_cv(1,1,1,1,0) assert_almost_equal(result[0],1.0) assert_almost_equal(result[1],0.0) def _check_obl_cv(self): assert_equal(cephes.obl_cv(1,1,0),2.0) def test_obl_rad1(self): cephes.obl_rad1(1,1,1,0) def test_obl_rad1_cv(self): cephes.obl_rad1_cv(1,1,1,1,0) def test_obl_rad2(self): cephes.obl_rad2(1,1,1,0) def test_obl_rad2_cv(self): cephes.obl_rad2_cv(1,1,1,1,0) def test_pbdv(self): assert_equal(cephes.pbdv(1,0),(0.0,1.0)) def test_pbvv(self): cephes.pbvv(1,0) def test_pbwa(self): cephes.pbwa(1,0) def test_pdtr(self): val = cephes.pdtr(0, 1) assert_almost_equal(val, np.exp(-1)) # Edge case: m = 0. val = cephes.pdtr([0, 1, 2], 0) assert_array_equal(val, [1, 1, 1]) def test_pdtrc(self): val = cephes.pdtrc(0, 1) assert_almost_equal(val, 1 - np.exp(-1)) # Edge case: m = 0. val = cephes.pdtrc([0, 1, 2], 0.0) assert_array_equal(val, [0, 0, 0]) def test_pdtri(self): with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") cephes.pdtri(0.5,0.5) def test_pdtrik(self): k = cephes.pdtrik(0.5, 1) assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5) # Edge case: m = 0 or very small. k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6]) assert_array_equal(k, np.zeros((3, 3))) def test_pro_ang1(self): cephes.pro_ang1(1,1,1,0) def test_pro_ang1_cv(self): assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), array((1.0,0.0))) def _check_pro_cv(self): assert_equal(cephes.pro_cv(1,1,0),2.0) def test_pro_rad1(self): cephes.pro_rad1(1,1,1,0.1) def test_pro_rad1_cv(self): cephes.pro_rad1_cv(1,1,1,1,0) def test_pro_rad2(self): cephes.pro_rad2(1,1,1,0) def test_pro_rad2_cv(self): cephes.pro_rad2_cv(1,1,1,1,0) def test_psi(self): cephes.psi(1) def test_radian(self): assert_equal(cephes.radian(0,0,0),0) def test_rgamma(self): assert_equal(cephes.rgamma(1),1.0) def test_round(self): assert_equal(cephes.round(3.4),3.0) assert_equal(cephes.round(-3.4),-3.0) assert_equal(cephes.round(3.6),4.0) assert_equal(cephes.round(-3.6),-4.0) assert_equal(cephes.round(3.5),4.0) assert_equal(cephes.round(-3.5),-4.0) def test_shichi(self): cephes.shichi(1) def test_sici(self): cephes.sici(1) s, c = cephes.sici(np.inf) assert_almost_equal(s, np.pi * 0.5) assert_almost_equal(c, 0) s, c = cephes.sici(-np.inf) assert_almost_equal(s, -np.pi * 0.5) assert_(np.isnan(c), "cosine integral(-inf) is not nan") def test_sindg(self): assert_equal(cephes.sindg(90),1.0) def test_smirnov(self): assert_equal(cephes.smirnov(1,.1),0.9) assert_(np.isnan(cephes.smirnov(1,np.nan))) def test_smirnovp(self): assert_equal(cephes._smirnovp(1, .1), -1) assert_equal(cephes._smirnovp(2, 0.75), -2*(0.25)**(2-1)) assert_equal(cephes._smirnovp(3, 0.75), -3*(0.25)**(3-1)) assert_(np.isnan(cephes._smirnovp(1, np.nan))) def test_smirnovc(self): assert_equal(cephes._smirnovc(1,.1),0.1) assert_(np.isnan(cephes._smirnovc(1,np.nan))) x10 = np.linspace(0, 1, 11, endpoint=True) assert_almost_equal(cephes._smirnovc(3, x10), 1-cephes.smirnov(3, x10)) x4 = np.linspace(0, 1, 5, endpoint=True) assert_almost_equal(cephes._smirnovc(4, x4), 1-cephes.smirnov(4, x4)) def test_smirnovi(self): assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) assert_(np.isnan(cephes.smirnovi(1,np.nan))) def test_smirnovci(self): assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.4)),0.4) assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.6)),0.6) assert_(np.isnan(cephes._smirnovci(1,np.nan))) def test_spence(self): assert_equal(cephes.spence(1),0.0) def test_stdtr(self): assert_equal(cephes.stdtr(1,0),0.5) assert_almost_equal(cephes.stdtr(1,1), 0.75) assert_almost_equal(cephes.stdtr(1,2), 0.852416382349) def test_stdtridf(self): cephes.stdtridf(0.7,1) def test_stdtrit(self): cephes.stdtrit(1,0.7) def test_struve(self): assert_equal(cephes.struve(0,0),0.0) def test_tandg(self): assert_equal(cephes.tandg(45),1.0) def test_tklmbda(self): assert_almost_equal(cephes.tklmbda(1,1),1.0) def test_y0(self): cephes.y0(1) def test_y1(self): cephes.y1(1) def test_yn(self): cephes.yn(1,1) def test_yv(self): cephes.yv(1,1) def _check_yve(self): cephes.yve(1,1) def test_wofz(self): z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.), complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.), complex(-0.0000000234545,1.1234), complex(-3.,5.1), complex(-53,30.1), complex(0.0,0.12345), complex(11,1), complex(-22,-2), complex(9,-28), complex(21,-33), complex(1e5,1e5), complex(1e14,1e14) ] w = [ complex(-3.78270245518980507452677445620103199303131110e-7, 0.000903861276433172057331093754199933411710053155), complex(0.1764906227004816847297495349730234591778719532788, -0.02146550539468457616788719893991501311573031095617), complex(0.2410250715772692146133539023007113781272362309451, 0.06087579663428089745895459735240964093522265589350), complex(0.30474420525691259245713884106959496013413834051768, -0.20821893820283162728743734725471561394145872072738), complex(7.317131068972378096865595229600561710140617977e34, 8.321873499714402777186848353320412813066170427e34), complex(0.0615698507236323685519612934241429530190806818395, -0.00676005783716575013073036218018565206070072304635), complex(0.3960793007699874918961319170187598400134746631, -5.593152259116644920546186222529802777409274656e-9), complex(0.08217199226739447943295069917990417630675021771804, -0.04701291087643609891018366143118110965272615832184), complex(0.00457246000350281640952328010227885008541748668738, -0.00804900791411691821818731763401840373998654987934), complex(0.8746342859608052666092782112565360755791467973338452, 0.), complex(0.00468190164965444174367477874864366058339647648741, 0.0510735563901306197993676329845149741675029197050), complex(-0.0023193175200187620902125853834909543869428763219, -0.025460054739731556004902057663500272721780776336), complex(9.11463368405637174660562096516414499772662584e304, 3.97101807145263333769664875189354358563218932e305), complex(-4.4927207857715598976165541011143706155432296e281, -2.8019591213423077494444700357168707775769028e281), complex(2.820947917809305132678577516325951485807107151e-6, 2.820947917668257736791638444590253942253354058e-6), complex(2.82094791773878143474039725787438662716372268e-15, 2.82094791773878143474039725773333923127678361e-15) ] assert_func_equal(cephes.wofz, w, z, rtol=1e-13) class TestAiry(object): def test_airy(self): # This tests the airy function to ensure 8 place accuracy in computation x = special.airy(.99) assert_array_almost_equal(x,array([0.13689066,-0.16050153,1.19815925,0.92046818]),8) x = special.airy(.41) assert_array_almost_equal(x,array([0.25238916,-.23480512,0.80686202,0.51053919]),8) x = special.airy(-.36) assert_array_almost_equal(x,array([0.44508477,-0.23186773,0.44939534,0.48105354]),8) def test_airye(self): a = special.airye(0.01) b = special.airy(0.01) b1 = [None]*4 for n in range(2): b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01)) for n in range(2,4): b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) assert_array_almost_equal(a,b1,6) def test_bi_zeros(self): bi = special.bi_zeros(2) bia = (array([-1.17371322, -3.2710930]), array([-2.29443968, -4.07315509]), array([-0.45494438, 0.39652284]), array([0.60195789, -0.76031014])) assert_array_almost_equal(bi,bia,4) bi = special.bi_zeros(5) assert_array_almost_equal(bi[0],array([-1.173713222709127, -3.271093302836352, -4.830737841662016, -6.169852128310251, -7.376762079367764]),11) assert_array_almost_equal(bi[1],array([-2.294439682614122, -4.073155089071828, -5.512395729663599, -6.781294445990305, -7.940178689168587]),10) assert_array_almost_equal(bi[2],array([-0.454944383639657, 0.396522836094465, -0.367969161486959, 0.349499116831805, -0.336026240133662]),11) assert_array_almost_equal(bi[3],array([0.601957887976239, -0.760310141492801, 0.836991012619261, -0.88947990142654, 0.929983638568022]),10) def test_ai_zeros(self): ai = special.ai_zeros(1) assert_array_almost_equal(ai,(array([-2.33810741]), array([-1.01879297]), array([0.5357]), array([0.7012])),4) def test_ai_zeros_big(self): z, zp, ai_zpx, aip_zx = special.ai_zeros(50000) ai_z, aip_z, _, _ = special.airy(z) ai_zp, aip_zp, _, _ = special.airy(zp) ai_envelope = 1/abs(z)**(1./4) aip_envelope = abs(zp)**(1./4) # Check values assert_allclose(ai_zpx, ai_zp, rtol=1e-10) assert_allclose(aip_zx, aip_z, rtol=1e-10) # Check they are zeros assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0) assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.1 assert_allclose(z[:6], [-2.3381074105, -4.0879494441, -5.5205598281, -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10) assert_allclose(zp[:6], [-1.0187929716, -3.2481975822, -4.8200992112, -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10) def test_bi_zeros_big(self): z, zp, bi_zpx, bip_zx = special.bi_zeros(50000) _, _, bi_z, bip_z = special.airy(z) _, _, bi_zp, bip_zp = special.airy(zp) bi_envelope = 1/abs(z)**(1./4) bip_envelope = abs(zp)**(1./4) # Check values assert_allclose(bi_zpx, bi_zp, rtol=1e-10) assert_allclose(bip_zx, bip_z, rtol=1e-10) # Check they are zeros assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0) assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.2 assert_allclose(z[:6], [-1.1737132227, -3.2710933028, -4.8307378417, -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10) assert_allclose(zp[:6], [-2.2944396826, -4.0731550891, -5.5123957297, -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10) class TestAssocLaguerre(object): def test_assoc_laguerre(self): a1 = special.genlaguerre(11,1) a2 = special.assoc_laguerre(.2,11,1) assert_array_almost_equal(a2,a1(.2),8) a2 = special.assoc_laguerre(1,11,1) assert_array_almost_equal(a2,a1(1),8) class TestBesselpoly(object): def test_besselpoly(self): pass class TestKelvin(object): def test_bei(self): mbei = special.bei(2) assert_almost_equal(mbei, 0.9722916273066613,5) # this may not be exact def test_beip(self): mbeip = special.beip(2) assert_almost_equal(mbeip,0.91701361338403631,5) # this may not be exact def test_ber(self): mber = special.ber(2) assert_almost_equal(mber,0.75173418271380821,5) # this may not be exact def test_berp(self): mberp = special.berp(2) assert_almost_equal(mberp,-0.49306712470943909,5) # this may not be exact def test_bei_zeros(self): # Abramowitz & Stegun, Table 9.12 bi = special.bei_zeros(5) assert_array_almost_equal(bi,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) def test_beip_zeros(self): bip = special.beip_zeros(5) assert_array_almost_equal(bip,array([3.772673304934953, 8.280987849760042, 12.742147523633703, 17.193431752512542, 21.641143941167325]),8) def test_ber_zeros(self): ber = special.ber_zeros(5) assert_array_almost_equal(ber,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) def test_berp_zeros(self): brp = special.berp_zeros(5) assert_array_almost_equal(brp,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) def test_kelvin(self): mkelv = special.kelvin(2) assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j, special.ker(2) + special.kei(2)*1j, special.berp(2) + special.beip(2)*1j, special.kerp(2) + special.keip(2)*1j),8) def test_kei(self): mkei = special.kei(2) assert_almost_equal(mkei,-0.20240006776470432,5) def test_keip(self): mkeip = special.keip(2) assert_almost_equal(mkeip,0.21980790991960536,5) def test_ker(self): mker = special.ker(2) assert_almost_equal(mker,-0.041664513991509472,5) def test_kerp(self): mkerp = special.kerp(2) assert_almost_equal(mkerp,-0.10660096588105264,5) def test_kei_zeros(self): kei = special.kei_zeros(5) assert_array_almost_equal(kei,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) def test_keip_zeros(self): keip = special.keip_zeros(5) assert_array_almost_equal(keip,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) # numbers come from 9.9 of A&S pg. 381 def test_kelvin_zeros(self): tmp = special.kelvin_zeros(5) berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp assert_array_almost_equal(berz,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) assert_array_almost_equal(beiz,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) assert_array_almost_equal(kerz,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44382]),4) assert_array_almost_equal(keiz,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) assert_array_almost_equal(berpz,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) assert_array_almost_equal(beipz,array([3.77267, # table from 1927 had 3.77320 # but this is more accurate 8.28099, 12.74215, 17.19343, 21.64114]),4) assert_array_almost_equal(kerpz,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) assert_array_almost_equal(keipz,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) def test_ker_zeros(self): ker = special.ker_zeros(5) assert_array_almost_equal(ker,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44381]),4) def test_kerp_zeros(self): kerp = special.kerp_zeros(5) assert_array_almost_equal(kerp,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) class TestBernoulli(object): def test_bernoulli(self): brn = special.bernoulli(5) assert_array_almost_equal(brn,array([1.0000, -0.5000, 0.1667, 0.0000, -0.0333, 0.0000]),4) class TestBeta(object): def test_beta(self): bet = special.beta(2,4) betg = (special.gamma(2)*special.gamma(4))/special.gamma(6) assert_almost_equal(bet,betg,8) def test_betaln(self): betln = special.betaln(2,4) bet = log(abs(special.beta(2,4))) assert_almost_equal(betln,bet,8) def test_betainc(self): btinc = special.betainc(1,1,.2) assert_almost_equal(btinc,0.2,8) def test_betaincinv(self): y = special.betaincinv(2,4,.5) comp = special.betainc(2,4,y) assert_almost_equal(comp,.5,5) class TestCombinatorics(object): def test_comb(self): assert_array_almost_equal(special.comb([10, 10], [3, 4]), [120., 210.]) assert_almost_equal(special.comb(10, 3), 120.) assert_equal(special.comb(10, 3, exact=True), 120) assert_equal(special.comb(10, 3, exact=True, repetition=True), 220) assert_allclose([special.comb(20, k, exact=True) for k in range(21)], special.comb(20, list(range(21))), atol=1e-15) ii = np.iinfo(int).max + 1 assert_equal(special.comb(ii, ii-1, exact=True), ii) expected = 100891344545564193334812497256 assert_equal(special.comb(100, 50, exact=True), expected) def test_comb_with_np_int64(self): n = 70 k = 30 np_n = np.int64(n) np_k = np.int64(k) assert_equal(special.comb(np_n, np_k, exact=True), special.comb(n, k, exact=True)) def test_comb_zeros(self): assert_equal(special.comb(2, 3, exact=True), 0) assert_equal(special.comb(-1, 3, exact=True), 0) assert_equal(special.comb(2, -1, exact=True), 0) assert_equal(special.comb(2, -1, exact=False), 0) assert_array_almost_equal(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 120.]) def test_perm(self): assert_array_almost_equal(special.perm([10, 10], [3, 4]), [720., 5040.]) assert_almost_equal(special.perm(10, 3), 720.) assert_equal(special.perm(10, 3, exact=True), 720) def test_perm_zeros(self): assert_equal(special.perm(2, 3, exact=True), 0) assert_equal(special.perm(-1, 3, exact=True), 0) assert_equal(special.perm(2, -1, exact=True), 0) assert_equal(special.perm(2, -1, exact=False), 0) assert_array_almost_equal(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 720.]) class TestTrigonometric(object): def test_cbrt(self): cb = special.cbrt(27) cbrl = 27**(1.0/3.0) assert_approx_equal(cb,cbrl) def test_cbrtmore(self): cb1 = special.cbrt(27.9) cbrl1 = 27.9**(1.0/3.0) assert_almost_equal(cb1,cbrl1,8) def test_cosdg(self): cdg = special.cosdg(90) cdgrl = cos(pi/2.0) assert_almost_equal(cdg,cdgrl,8) def test_cosdgmore(self): cdgm = special.cosdg(30) cdgmrl = cos(pi/6.0) assert_almost_equal(cdgm,cdgmrl,8) def test_cosm1(self): cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10)) csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) assert_array_almost_equal(cs,csrl,8) def test_cotdg(self): ct = special.cotdg(30) ctrl = tan(pi/6.0)**(-1) assert_almost_equal(ct,ctrl,8) def test_cotdgmore(self): ct1 = special.cotdg(45) ctrl1 = tan(pi/4.0)**(-1) assert_almost_equal(ct1,ctrl1,8) def test_specialpoints(self): assert_almost_equal(special.cotdg(45), 1.0, 14) assert_almost_equal(special.cotdg(-45), -1.0, 14) assert_almost_equal(special.cotdg(90), 0.0, 14) assert_almost_equal(special.cotdg(-90), 0.0, 14) assert_almost_equal(special.cotdg(135), -1.0, 14) assert_almost_equal(special.cotdg(-135), 1.0, 14) assert_almost_equal(special.cotdg(225), 1.0, 14) assert_almost_equal(special.cotdg(-225), -1.0, 14) assert_almost_equal(special.cotdg(270), 0.0, 14) assert_almost_equal(special.cotdg(-270), 0.0, 14) assert_almost_equal(special.cotdg(315), -1.0, 14) assert_almost_equal(special.cotdg(-315), 1.0, 14) assert_almost_equal(special.cotdg(765), 1.0, 14) def test_sinc(self): # the sinc implementation and more extensive sinc tests are in numpy assert_array_equal(special.sinc([0]), 1) assert_equal(special.sinc(0.0), 1.0) def test_sindg(self): sn = special.sindg(90) assert_equal(sn,1.0) def test_sindgmore(self): snm = special.sindg(30) snmrl = sin(pi/6.0) assert_almost_equal(snm,snmrl,8) snm1 = special.sindg(45) snmrl1 = sin(pi/4.0) assert_almost_equal(snm1,snmrl1,8) class TestTandg(object): def test_tandg(self): tn = special.tandg(30) tnrl = tan(pi/6.0) assert_almost_equal(tn,tnrl,8) def test_tandgmore(self): tnm = special.tandg(45) tnmrl = tan(pi/4.0) assert_almost_equal(tnm,tnmrl,8) tnm1 = special.tandg(60) tnmrl1 = tan(pi/3.0) assert_almost_equal(tnm1,tnmrl1,8) def test_specialpoints(self): assert_almost_equal(special.tandg(0), 0.0, 14) assert_almost_equal(special.tandg(45), 1.0, 14) assert_almost_equal(special.tandg(-45), -1.0, 14) assert_almost_equal(special.tandg(135), -1.0, 14) assert_almost_equal(special.tandg(-135), 1.0, 14) assert_almost_equal(special.tandg(180), 0.0, 14) assert_almost_equal(special.tandg(-180), 0.0, 14) assert_almost_equal(special.tandg(225), 1.0, 14) assert_almost_equal(special.tandg(-225), -1.0, 14) assert_almost_equal(special.tandg(315), -1.0, 14) assert_almost_equal(special.tandg(-315), 1.0, 14) class TestEllip(object): def test_ellipj_nan(self): """Regression test for #912.""" special.ellipj(0.5, np.nan) def test_ellipj(self): el = special.ellipj(0.2,0) rel = [sin(0.2),cos(0.2),1.0,0.20] assert_array_almost_equal(el,rel,13) def test_ellipk(self): elk = special.ellipk(.2) assert_almost_equal(elk,1.659623598610528,11) assert_equal(special.ellipkm1(0.0), np.inf) assert_equal(special.ellipkm1(1.0), pi/2) assert_equal(special.ellipkm1(np.inf), 0.0) assert_equal(special.ellipkm1(np.nan), np.nan) assert_equal(special.ellipkm1(-1), np.nan) assert_allclose(special.ellipk(-10), 0.7908718902387385) def test_ellipkinc(self): elkinc = special.ellipkinc(pi/2,.2) elk = special.ellipk(0.2) assert_almost_equal(elkinc,elk,15) alpha = 20*pi/180 phi = 45*pi/180 m = sin(alpha)**2 elkinc = special.ellipkinc(phi,m) assert_almost_equal(elkinc,0.79398143,8) # From pg. 614 of A & S assert_equal(special.ellipkinc(pi/2, 0.0), pi/2) assert_equal(special.ellipkinc(pi/2, 1.0), np.inf) assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0) assert_equal(special.ellipkinc(pi/2, np.nan), np.nan) assert_equal(special.ellipkinc(pi/2, 2), np.nan) assert_equal(special.ellipkinc(0, 0.5), 0.0) assert_equal(special.ellipkinc(np.inf, 0.5), np.inf) assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipkinc(np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.nan, 0.5), np.nan) assert_equal(special.ellipkinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14) assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946) def test_ellipkinc_2(self): # Regression test for gh-3550 # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipkinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 1.0259330100195334), 1) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipkinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 5.1296650500976675), 2) def test_ellipkinc_singular(self): # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2) xlog = np.logspace(-300, -17, 25) xlin = np.linspace(1e-17, 0.1, 25) xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False) assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)), rtol=1e14) assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)), rtol=1e14) assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)), rtol=1e14) assert_equal(special.ellipkinc(np.pi/2, 1), np.inf) assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)), rtol=1e14) assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf) def test_ellipe(self): ele = special.ellipe(.2) assert_almost_equal(ele,1.4890350580958529,8) assert_equal(special.ellipe(0.0), pi/2) assert_equal(special.ellipe(1.0), 1.0) assert_equal(special.ellipe(-np.inf), np.inf) assert_equal(special.ellipe(np.nan), np.nan) assert_equal(special.ellipe(2), np.nan) assert_allclose(special.ellipe(-10), 3.6391380384177689) def test_ellipeinc(self): eleinc = special.ellipeinc(pi/2,.2) ele = special.ellipe(0.2) assert_almost_equal(eleinc,ele,14) # pg 617 of A & S alpha, phi = 52*pi/180,35*pi/180 m = sin(alpha)**2 eleinc = special.ellipeinc(phi,m) assert_almost_equal(eleinc, 0.58823065, 8) assert_equal(special.ellipeinc(pi/2, 0.0), pi/2) assert_equal(special.ellipeinc(pi/2, 1.0), 1.0) assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf) assert_equal(special.ellipeinc(pi/2, np.nan), np.nan) assert_equal(special.ellipeinc(pi/2, 2), np.nan) assert_equal(special.ellipeinc(0, 0.5), 0.0) assert_equal(special.ellipeinc(np.inf, 0.5), np.inf) assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf) assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf) assert_equal(special.ellipeinc(np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(np.nan, 0.5), np.nan) assert_equal(special.ellipeinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876) def test_ellipeinc_2(self): # Regression test for gh-3550 # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipeinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 0.84442884574781019), 2) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipeinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 3.3471442287390509), 4) class TestErf(object): def test_erf(self): er = special.erf(.25) assert_almost_equal(er,0.2763263902,8) def test_erf_zeros(self): erz = special.erf_zeros(5) erzr = array([1.45061616+1.88094300j, 2.24465928+2.61657514j, 2.83974105+3.17562810j, 3.33546074+3.64617438j, 3.76900557+4.06069723j]) assert_array_almost_equal(erz,erzr,4) def _check_variant_func(self, func, other_func, rtol, atol=0): np.random.seed(1234) n = 10000 x = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) y = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) z = x + 1j*y old_errors = np.seterr(all='ignore') try: w = other_func(z) w_real = other_func(x).real mask = np.isfinite(w) w = w[mask] z = z[mask] mask = np.isfinite(w_real) w_real = w_real[mask] x = x[mask] # test both real and complex variants assert_func_equal(func, w, z, rtol=rtol, atol=atol) assert_func_equal(func, w_real, x, rtol=rtol, atol=atol) finally: np.seterr(**old_errors) def test_erfc_consistent(self): self._check_variant_func( cephes.erfc, lambda z: 1 - cephes.erf(z), rtol=1e-12, atol=1e-14 # <- the test function loses precision ) def test_erfcx_consistent(self): self._check_variant_func( cephes.erfcx, lambda z: np.exp(z*z) * cephes.erfc(z), rtol=1e-12 ) def test_erfi_consistent(self): self._check_variant_func( cephes.erfi, lambda z: -1j * cephes.erf(1j*z), rtol=1e-12 ) def test_dawsn_consistent(self): self._check_variant_func( cephes.dawsn, lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z), rtol=1e-12 ) def test_erf_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -1, 1] assert_allclose(special.erf(vals), expected, rtol=1e-15) def test_erfc_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, 2, 0] assert_allclose(special.erfc(vals), expected, rtol=1e-15) def test_erfcx_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, np.inf, 0] assert_allclose(special.erfcx(vals), expected, rtol=1e-15) def test_erfi_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -np.inf, np.inf] assert_allclose(special.erfi(vals), expected, rtol=1e-15) def test_dawsn_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -0.0, 0.0] assert_allclose(special.dawsn(vals), expected, rtol=1e-15) def test_wofz_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan + np.nan * 1.j, 0.-0.j, 0.+0.j] assert_allclose(special.wofz(vals), expected, rtol=1e-15) class TestEuler(object): def test_euler(self): eu0 = special.euler(0) eu1 = special.euler(1) eu2 = special.euler(2) # just checking segfaults assert_allclose(eu0, [1], rtol=1e-15) assert_allclose(eu1, [1, 0], rtol=1e-15) assert_allclose(eu2, [1, 0, -1], rtol=1e-15) eu24 = special.euler(24) mathworld = [1,1,5,61,1385,50521,2702765,199360981, 19391512145,2404879675441, 370371188237525,69348874393137901, 15514534163557086905] correct = zeros((25,),'d') for k in range(0,13): if (k % 2): correct[2*k] = -float(mathworld[k]) else: correct[2*k] = float(mathworld[k]) olderr = np.seterr(all='ignore') try: err = nan_to_num((eu24-correct)/correct) errmax = max(err) finally: np.seterr(**olderr) assert_almost_equal(errmax, 0.0, 14) class TestExp(object): def test_exp2(self): ex = special.exp2(2) exrl = 2**2 assert_equal(ex,exrl) def test_exp2more(self): exm = special.exp2(2.5) exmrl = 2**(2.5) assert_almost_equal(exm,exmrl,8) def test_exp10(self): ex = special.exp10(2) exrl = 10**2 assert_approx_equal(ex,exrl) def test_exp10more(self): exm = special.exp10(2.5) exmrl = 10**(2.5) assert_almost_equal(exm,exmrl,8) def test_expm1(self): ex = (special.expm1(2),special.expm1(3),special.expm1(4)) exrl = (exp(2)-1,exp(3)-1,exp(4)-1) assert_array_almost_equal(ex,exrl,8) def test_expm1more(self): ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2)) exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) assert_array_almost_equal(ex1,exrl1,8) class TestFactorialFunctions(object): def test_factorial(self): # Some known values, float math assert_array_almost_equal(special.factorial(0), 1) assert_array_almost_equal(special.factorial(1), 1) assert_array_almost_equal(special.factorial(2), 2) assert_array_almost_equal([6., 24., 120.], special.factorial([3, 4, 5], exact=False)) assert_array_almost_equal(special.factorial([[5, 3], [4, 3]]), [[120, 6], [24, 6]]) # Some known values, integer math assert_equal(special.factorial(0, exact=True), 1) assert_equal(special.factorial(1, exact=True), 1) assert_equal(special.factorial(2, exact=True), 2) assert_equal(special.factorial(5, exact=True), 120) assert_equal(special.factorial(15, exact=True), 1307674368000) # ndarray shape is maintained assert_equal(special.factorial([7, 4, 15, 10], exact=True), [5040, 24, 1307674368000, 3628800]) assert_equal(special.factorial([[5, 3], [4, 3]], True), [[120, 6], [24, 6]]) # object arrays assert_equal(special.factorial(np.arange(-3, 22), True), special.factorial(np.arange(-3, 22), False)) # int64 array assert_equal(special.factorial(np.arange(-3, 15), True), special.factorial(np.arange(-3, 15), False)) # int32 array assert_equal(special.factorial(np.arange(-3, 5), True), special.factorial(np.arange(-3, 5), False)) # Consistent output for n < 0 for exact in (True, False): assert_array_equal(0, special.factorial(-3, exact)) assert_array_equal([1, 2, 0, 0], special.factorial([1, 2, -5, -4], exact)) for n in range(0, 22): # Compare all with math.factorial correct = math.factorial(n) assert_array_equal(correct, special.factorial(n, True)) assert_array_equal(correct, special.factorial([n], True)[0]) assert_allclose(float(correct), special.factorial(n, False)) assert_allclose(float(correct), special.factorial([n], False)[0]) # Compare exact=True vs False, scalar vs array assert_array_equal(special.factorial(n, True), special.factorial(n, False)) assert_array_equal(special.factorial([n], True), special.factorial([n], False)) @pytest.mark.parametrize('x, exact', [ (1, True), (1, False), (np.array(1), True), (np.array(1), False), ]) def test_factorial_0d_return_type(self, x, exact): assert np.isscalar(special.factorial(x, exact=exact)) def test_factorial2(self): assert_array_almost_equal([105., 384., 945.], special.factorial2([7, 8, 9], exact=False)) assert_equal(special.factorial2(7, exact=True), 105) def test_factorialk(self): assert_equal(special.factorialk(5, 1, exact=True), 120) assert_equal(special.factorialk(5, 3, exact=True), 10) @pytest.mark.parametrize('x, exact', [ (np.nan, True), (np.nan, False), (np.array([np.nan]), True), (np.array([np.nan]), False), ]) def test_nan_inputs(self, x, exact): result = special.factorial(x, exact=exact) assert_(np.isnan(result)) def test_mixed_nan_inputs(self): x = np.array([np.nan, 1, 2, 3, np.nan]) result = special.factorial(x, exact=True) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) result = special.factorial(x, exact=False) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) class TestFresnel(object): def test_fresnel(self): frs = array(special.fresnel(.5)) assert_array_almost_equal(frs,array([0.064732432859999287, 0.49234422587144644]),8) def test_fresnel_inf1(self): frs = special.fresnel(np.inf) assert_equal(frs, (0.5, 0.5)) def test_fresnel_inf2(self): frs = special.fresnel(-np.inf) assert_equal(frs, (-0.5, -0.5)) # values from pg 329 Table 7.11 of A & S # slightly corrected in 4th decimal place def test_fresnel_zeros(self): szo, czo = special.fresnel_zeros(5) assert_array_almost_equal(szo, array([2.0093+0.2885j, 2.8335+0.2443j, 3.4675+0.2185j, 4.0026+0.2009j, 4.4742+0.1877j]),3) assert_array_almost_equal(czo, array([1.7437+0.3057j, 2.6515+0.2529j, 3.3204+0.2240j, 3.8757+0.2047j, 4.3611+0.1907j]),3) vals1 = special.fresnel(szo)[0] vals2 = special.fresnel(czo)[1] assert_array_almost_equal(vals1,0,14) assert_array_almost_equal(vals2,0,14) def test_fresnelc_zeros(self): szo, czo = special.fresnel_zeros(6) frc = special.fresnelc_zeros(6) assert_array_almost_equal(frc,czo,12) def test_fresnels_zeros(self): szo, czo = special.fresnel_zeros(5) frs = special.fresnels_zeros(5) assert_array_almost_equal(frs,szo,12) class TestGamma(object): def test_gamma(self): gam = special.gamma(5) assert_equal(gam,24.0) def test_gammaln(self): gamln = special.gammaln(3) lngam = log(special.gamma(3)) assert_almost_equal(gamln,lngam,8) def test_gammainccinv(self): gccinv = special.gammainccinv(.5,.5) gcinv = special.gammaincinv(.5,.5) assert_almost_equal(gccinv,gcinv,8) @with_special_errors def test_gammaincinv(self): y = special.gammaincinv(.4,.4) x = special.gammainc(.4,y) assert_almost_equal(x,0.4,1) y = special.gammainc(10, 0.05) x = special.gammaincinv(10, 2.5715803516000736e-20) assert_almost_equal(0.05, x, decimal=10) assert_almost_equal(y, 2.5715803516000736e-20, decimal=10) x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18) assert_almost_equal(11.0, x, decimal=10) @with_special_errors def test_975(self): # Regression test for ticket #975 -- switch point in algorithm # check that things work OK at the point, immediately next floats # around it, and a bit further away pts = [0.25, np.nextafter(0.25, 0), 0.25 - 1e-12, np.nextafter(0.25, 1), 0.25 + 1e-12] for xp in pts: y = special.gammaincinv(.4, xp) x = special.gammainc(0.4, y) assert_allclose(x, xp, rtol=1e-12) def test_rgamma(self): rgam = special.rgamma(8) rlgam = 1/special.gamma(8) assert_almost_equal(rgam,rlgam,8) def test_infinity(self): assert_(np.isinf(special.gamma(-1))) assert_equal(special.rgamma(-1), 0) class TestHankel(object): def test_negv1(self): assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14) def test_hankel1(self): hank1 = special.hankel1(1,.1) hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j) assert_almost_equal(hank1,hankrl,8) def test_negv1e(self): assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14) def test_hankel1e(self): hank1e = special.hankel1e(1,.1) hankrle = special.hankel1(1,.1)*exp(-.1j) assert_almost_equal(hank1e,hankrle,8) def test_negv2(self): assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14) def test_hankel2(self): hank2 = special.hankel2(1,.1) hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j) assert_almost_equal(hank2,hankrl2,8) def test_neg2e(self): assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14) def test_hankl2e(self): hank2e = special.hankel2e(1,.1) hankrl2e = special.hankel2e(1,.1) assert_almost_equal(hank2e,hankrl2e,8) class TestHyper(object): def test_h1vp(self): h1 = special.h1vp(1,.1) h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j) assert_almost_equal(h1,h1real,8) def test_h2vp(self): h2 = special.h2vp(1,.1) h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j) assert_almost_equal(h2,h2real,8) def test_hyp0f1(self): # scalar input assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12) assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15) # float input, expected values match mpmath x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5]) expected = np.array([0.58493659229143, 0.70566805723127, 1.0, 1.37789689539747, 1.60373685288480]) assert_allclose(x, expected, rtol=1e-12) # complex input x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j) assert_allclose(x, expected.astype(complex), rtol=1e-12) # test broadcasting x1 = [0.5, 1.5, 2.5] x2 = [0, 1, 0.5] x = special.hyp0f1(x1, x2) expected = [1.0, 1.8134302039235093, 1.21482702689997] assert_allclose(x, expected, rtol=1e-12) x = special.hyp0f1(np.row_stack([x1] * 2), x2) assert_allclose(x, np.row_stack([expected] * 2), rtol=1e-12) assert_raises(ValueError, special.hyp0f1, np.row_stack([x1] * 3), [0, 1]) def test_hyp0f1_gh5764(self): # Just checks the point that failed; there's a more systematic # test in test_mpmath res = special.hyp0f1(0.8, 0.5 + 0.5*1J) # The expected value was generated using mpmath assert_almost_equal(res, 1.6139719776441115 + 1J*0.80893054061790665) def test_hyp1f1(self): hyp1 = special.hyp1f1(.1,.1,.3) assert_almost_equal(hyp1, 1.3498588075760032,7) # test contributed by Moritz Deger (2008-05-29) # https://github.com/scipy/scipy/issues/1186 (Trac #659) # reference data obtained from mathematica [ a, b, x, m(a,b,x)]: # produced with test_hyp1f1.nb ref_data = array([[-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04], [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00], [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05], [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08], [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24], [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21], [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13], [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13], [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02], [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10], [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01], [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21], [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20], [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07], [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03], [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02], [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11], [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03], [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17], [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01], [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00], [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00], [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23], [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01], [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04], [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08], [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01], [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07], [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03], [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09], [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06], [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00], [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01], [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02], [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02], [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02], [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00], [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09], [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01], [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00], [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02], [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05], [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05], [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02], [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02], [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13], [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05], [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12], [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01], [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16], [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37], [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06], [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02], [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12], [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27], [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04], [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06], [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07], [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03], [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07], [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27], [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12], [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32], [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04], [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01], [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02], [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19], [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09], [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31], [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01], [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02], [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08], [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09], [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33], [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01], [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29], [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01], [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29], [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02], [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00], [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08], [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01], [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01], [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01], [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13], [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11], [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02], [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02], [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01], [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31], [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04], [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25], [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01], [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00], [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02], [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05], [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02], [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01], [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01], [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00]]) for a,b,c,expected in ref_data: result = special.hyp1f1(a,b,c) assert_(abs(expected - result)/expected < 1e-4) def test_hyp1f1_gh2957(self): hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933) hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934) assert_almost_equal(hyp1, hyp2, 12) def test_hyp1f1_gh2282(self): hyp = special.hyp1f1(0.5, 1.5, -1000) assert_almost_equal(hyp, 0.028024956081989643, 12) def test_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], [3, 4, 8, 1, special.gamma(8)*special.gamma(8-4-3)/special.gamma(8-3)/special.gamma(8-4)], [3, 2, 3-2+1, -1, 1./2**3*sqrt(pi) * special.gamma(1+3-2)/special.gamma(1+0.5*3-2)/special.gamma(0.5+0.5*3)], [5, 2, 5-2+1, -1, 1./2**5*sqrt(pi) * special.gamma(1+5-2)/special.gamma(1+0.5*5-2)/special.gamma(0.5+0.5*5)], [4, 0.5+4, 1.5-2*4, -1./3, (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4)/special.gamma(3./2)/special.gamma(4./3-2*4)], # and some others # ticket #424 [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484], # negative integer a or b, with c-a-b integer and x > 0.9 [-2,3,1,0.95,0.715], [2,-3,1,0.95,-0.007], [-6,3,1,0.95,0.0000810625], [2,-5,1,0.95,-0.000029375], # huge negative integers (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24), (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18), ] for i, (a, b, c, x, v) in enumerate(values): cv = special.hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_hyperu(self): val1 = special.hyperu(1,0.1,100) assert_almost_equal(val1,0.0098153,7) a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] a,b = asarray(a), asarray(b) z = 0.5 hypu = special.hyperu(a,b,z) hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) / (special.gamma(1+a-b)*special.gamma(b)) - z**(1-b)*special.hyp1f1(1+a-b,2-b,z) / (special.gamma(a)*special.gamma(2-b))) assert_array_almost_equal(hypu,hprl,12) def test_hyperu_gh2287(self): assert_almost_equal(special.hyperu(1, 1.5, 20.2), 0.048360918656699191, 12) class TestBessel(object): def test_itj0y0(self): it0 = array(special.itj0y0(.2)) assert_array_almost_equal(it0,array([0.19933433254006822, -0.34570883800412566]),8) def test_it2j0y0(self): it2 = array(special.it2j0y0(.2)) assert_array_almost_equal(it2,array([0.0049937546274601858, -0.43423067011231614]),8) def test_negv_iv(self): assert_equal(special.iv(3,2), special.iv(-3,2)) def test_j0(self): oz = special.j0(.1) ozr = special.jn(0,.1) assert_almost_equal(oz,ozr,8) def test_j1(self): o1 = special.j1(.1) o1r = special.jn(1,.1) assert_almost_equal(o1,o1r,8) def test_jn(self): jnnr = special.jn(1,.2) assert_almost_equal(jnnr,0.099500832639235995,8) def test_negv_jv(self): assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14) def test_jv(self): values = [[0, 0.1, 0.99750156206604002], [2./3, 1e-8, 0.3239028506761532e-5], [2./3, 1e-10, 0.1503423854873779e-6], [3.1, 1e-10, 0.1711956265409013e-32], [2./3, 4.0, -0.2325440850267039], ] for i, (v, x, y) in enumerate(values): yc = special.jv(v, x) assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) def test_negv_jve(self): assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14) def test_jve(self): jvexp = special.jve(1,.2) assert_almost_equal(jvexp,0.099500832639235995,8) jvexp1 = special.jve(1,.2+1j) z = .2+1j jvexpr = special.jv(1,z)*exp(-abs(z.imag)) assert_almost_equal(jvexp1,jvexpr,8) def test_jn_zeros(self): jn0 = special.jn_zeros(0,5) jn1 = special.jn_zeros(1,5) assert_array_almost_equal(jn0,array([2.4048255577, 5.5200781103, 8.6537279129, 11.7915344391, 14.9309177086]),4) assert_array_almost_equal(jn1,array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]),4) jn102 = special.jn_zeros(102,5) assert_allclose(jn102, array([110.89174935992040343, 117.83464175788308398, 123.70194191713507279, 129.02417238949092824, 134.00114761868422559]), rtol=1e-13) jn301 = special.jn_zeros(301,5) assert_allclose(jn301, array([313.59097866698830153, 323.21549776096288280, 331.22338738656748796, 338.39676338872084500, 345.03284233056064157]), rtol=1e-13) def test_jn_zeros_slow(self): jn0 = special.jn_zeros(0, 300) assert_allclose(jn0[260-1], 816.02884495068867280, rtol=1e-13) assert_allclose(jn0[280-1], 878.86068707124422606, rtol=1e-13) assert_allclose(jn0[300-1], 941.69253065317954064, rtol=1e-13) jn10 = special.jn_zeros(10, 300) assert_allclose(jn10[260-1], 831.67668514305631151, rtol=1e-13) assert_allclose(jn10[280-1], 894.51275095371316931, rtol=1e-13) assert_allclose(jn10[300-1], 957.34826370866539775, rtol=1e-13) jn3010 = special.jn_zeros(3010,5) assert_allclose(jn3010, array([3036.86590780927, 3057.06598526482, 3073.66360690272, 3088.37736494778, 3101.86438139042]), rtol=1e-8) def test_jnjnp_zeros(self): jn = special.jn def jnp(n, x): return (jn(n-1,x) - jn(n+1,x))/2 for nt in range(1, 30): z, n, m, t = special.jnjnp_zeros(nt) for zz, nn, tt in zip(z, n, t): if tt == 0: assert_allclose(jn(nn, zz), 0, atol=1e-6) elif tt == 1: assert_allclose(jnp(nn, zz), 0, atol=1e-6) else: raise AssertionError("Invalid t return for nt=%d" % nt) def test_jnp_zeros(self): jnp = special.jnp_zeros(1,5) assert_array_almost_equal(jnp, array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]),4) jnp = special.jnp_zeros(443,5) assert_allclose(special.jvp(443, jnp), 0, atol=1e-15) def test_jnyn_zeros(self): jnz = special.jnyn_zeros(1,5) assert_array_almost_equal(jnz,(array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]), array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]), array([2.19714, 5.42968, 8.59601, 11.74915, 14.89744]), array([3.68302, 6.94150, 10.12340, 13.28576, 16.44006])),5) def test_jvp(self): jvprim = special.jvp(2,2) jv0 = (special.jv(1,2)-special.jv(3,2))/2 assert_almost_equal(jvprim,jv0,10) def test_k0(self): ozk = special.k0(.1) ozkr = special.kv(0,.1) assert_almost_equal(ozk,ozkr,8) def test_k0e(self): ozke = special.k0e(.1) ozker = special.kve(0,.1) assert_almost_equal(ozke,ozker,8) def test_k1(self): o1k = special.k1(.1) o1kr = special.kv(1,.1) assert_almost_equal(o1k,o1kr,8) def test_k1e(self): o1ke = special.k1e(.1) o1ker = special.kve(1,.1) assert_almost_equal(o1ke,o1ker,8) def test_jacobi(self): a = 5*np.random.random() - 1 b = 5*np.random.random() - 1 P0 = special.jacobi(0,a,b) P1 = special.jacobi(1,a,b) P2 = special.jacobi(2,a,b) P3 = special.jacobi(3,a,b) assert_array_almost_equal(P0.c,[1],13) assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13) cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)] p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]] assert_array_almost_equal(P2.c,array(p2c)/8.0,13) cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3), 12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)] p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] assert_array_almost_equal(P3.c,array(p3c)/48.0,13) def test_kn(self): kn1 = special.kn(0,.2) assert_almost_equal(kn1,1.7527038555281462,8) def test_negv_kv(self): assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2)) def test_kv0(self): kv0 = special.kv(0,.2) assert_almost_equal(kv0, 1.7527038555281462, 10) def test_kv1(self): kv1 = special.kv(1,0.2) assert_almost_equal(kv1, 4.775972543220472, 10) def test_kv2(self): kv2 = special.kv(2,0.2) assert_almost_equal(kv2, 49.51242928773287, 10) def test_kn_largeorder(self): assert_allclose(special.kn(32, 1), 1.7516596664574289e+43) def test_kv_largearg(self): assert_equal(special.kv(0, 1e19), 0) def test_negv_kve(self): assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2)) def test_kve(self): kve1 = special.kve(0,.2) kv1 = special.kv(0,.2)*exp(.2) assert_almost_equal(kve1,kv1,8) z = .2+1j kve2 = special.kve(0,z) kv2 = special.kv(0,z)*exp(z) assert_almost_equal(kve2,kv2,8) def test_kvp_v0n1(self): z = 2.2 assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10) def test_kvp_n1(self): v = 3. z = 2.2 xc = -special.kv(v+1,z) + v/z*special.kv(v,z) x = special.kvp(v,z, n=1) assert_almost_equal(xc, x, 10) # this function (kvp) is broken def test_kvp_n2(self): v = 3. z = 2.2 xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z x = special.kvp(v, z, n=2) assert_almost_equal(xc, x, 10) def test_y0(self): oz = special.y0(.1) ozr = special.yn(0,.1) assert_almost_equal(oz,ozr,8) def test_y1(self): o1 = special.y1(.1) o1r = special.yn(1,.1) assert_almost_equal(o1,o1r,8) def test_y0_zeros(self): yo,ypo = special.y0_zeros(2) zo,zpo = special.y0_zeros(2,complex=1) all = r_[yo,zo] allval = r_[ypo,zpo] assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11) assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11) def test_y1_zeros(self): y1 = special.y1_zeros(1) assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) def test_y1p_zeros(self): y1p = special.y1p_zeros(1,complex=1) assert_array_almost_equal(y1p,(array([0.5768+0.904j]), array([-0.7635+0.5892j])),3) def test_yn_zeros(self): an = special.yn_zeros(4,2) assert_array_almost_equal(an,array([5.64515, 9.36162]),5) an = special.yn_zeros(443,5) assert_allclose(an, [450.13573091578090314, 463.05692376675001542, 472.80651546418663566, 481.27353184725625838, 488.98055964441374646], rtol=1e-15) def test_ynp_zeros(self): ao = special.ynp_zeros(0,2) assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6) ao = special.ynp_zeros(43,5) assert_allclose(special.yvp(43, ao), 0, atol=1e-15) ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-9) def test_ynp_zeros_large_order(self): ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-14) def test_yn(self): yn2n = special.yn(1,.2) assert_almost_equal(yn2n,-3.3238249881118471,8) def test_negv_yv(self): assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14) def test_yv(self): yv2 = special.yv(1,.2) assert_almost_equal(yv2,-3.3238249881118471,8) def test_negv_yve(self): assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14) def test_yve(self): yve2 = special.yve(1,.2) assert_almost_equal(yve2,-3.3238249881118471,8) yve2r = special.yv(1,.2+1j)*exp(-1) yve22 = special.yve(1,.2+1j) assert_almost_equal(yve22,yve2r,8) def test_yvp(self): yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0 yvp1 = special.yvp(2,.2) assert_array_almost_equal(yvp1,yvpr,10) def _cephes_vs_amos_points(self): """Yield points at which to compare Cephes implementation to AMOS""" # check several points, including large-amplitude ones for v in [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301]: for z in [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300, 10003]: yield v, z # check half-integers; these are problematic points at least # for cephes/iv for v in 0.5 + arange(-60, 60): yield v, 3.5 def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None): for v, z in self._cephes_vs_amos_points(): if skip is not None and skip(v, z): continue c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z) if np.isinf(c1): assert_(np.abs(c2) >= 1e300, (v, z)) elif np.isnan(c1): assert_(c2.imag != 0, (v, z)) else: assert_allclose(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol) if v == int(v): assert_allclose(c3, c2, err_msg=(v, z), rtol=rtol, atol=atol) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_jv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_yv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305) def test_yv_cephes_vs_amos_only_small_orders(self): skipper = lambda v, z: (abs(v) > 50) self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305, skip=skipper) def test_iv_cephes_vs_amos(self): olderr = np.seterr(all='ignore') try: self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305) finally: np.seterr(**olderr) @pytest.mark.slow def test_iv_cephes_vs_amos_mass_test(self): N = 1000000 np.random.seed(1) v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N) x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N) imsk = (np.random.randint(8, size=N) == 0) v[imsk] = v[imsk].astype(int) old_err = np.seterr(all='ignore') try: c1 = special.iv(v, x) c2 = special.iv(v, x+0j) # deal with differences in the inf and zero cutoffs c1[abs(c1) > 1e300] = np.inf c2[abs(c2) > 1e300] = np.inf c1[abs(c1) < 1e-300] = 0 c2[abs(c2) < 1e-300] = 0 dc = abs(c1/c2 - 1) dc[np.isnan(dc)] = 0 finally: np.seterr(**old_err) k = np.argmax(dc) # Most error apparently comes from AMOS and not our implementation; # there are some problems near integer orders there assert_(dc[k] < 2e-7, (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j))) def test_kv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305) self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305) def test_ticket_623(self): assert_allclose(special.jv(3, 4), 0.43017147387562193) assert_allclose(special.jv(301, 1300), 0.0183487151115275) assert_allclose(special.jv(301, 1296.0682), -0.0224174325312048) def test_ticket_853(self): """Negative-order Bessels""" # cephes assert_allclose(special.jv(-1, 1), -0.4400505857449335) assert_allclose(special.jv(-2, 1), 0.1149034849319005) assert_allclose(special.yv(-1, 1), 0.7812128213002887) assert_allclose(special.yv(-2, 1), -1.650682606816255) assert_allclose(special.iv(-1, 1), 0.5651591039924851) assert_allclose(special.iv(-2, 1), 0.1357476697670383) assert_allclose(special.kv(-1, 1), 0.6019072301972347) assert_allclose(special.kv(-2, 1), 1.624838898635178) assert_allclose(special.jv(-0.5, 1), 0.43109886801837607952) assert_allclose(special.yv(-0.5, 1), 0.6713967071418031) assert_allclose(special.iv(-0.5, 1), 1.231200214592967) assert_allclose(special.kv(-0.5, 1), 0.4610685044478945) # amos assert_allclose(special.jv(-1, 1+0j), -0.4400505857449335) assert_allclose(special.jv(-2, 1+0j), 0.1149034849319005) assert_allclose(special.yv(-1, 1+0j), 0.7812128213002887) assert_allclose(special.yv(-2, 1+0j), -1.650682606816255) assert_allclose(special.iv(-1, 1+0j), 0.5651591039924851) assert_allclose(special.iv(-2, 1+0j), 0.1357476697670383) assert_allclose(special.kv(-1, 1+0j), 0.6019072301972347) assert_allclose(special.kv(-2, 1+0j), 1.624838898635178) assert_allclose(special.jv(-0.5, 1+0j), 0.43109886801837607952) assert_allclose(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j) assert_allclose(special.yv(-0.5, 1+0j), 0.6713967071418031) assert_allclose(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j) assert_allclose(special.iv(-0.5, 1+0j), 1.231200214592967) assert_allclose(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j) assert_allclose(special.kv(-0.5, 1+0j), 0.4610685044478945) assert_allclose(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j) assert_allclose(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3)) assert_allclose(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j)) assert_allclose(special.hankel1(-0.5, 1+1j), special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j)) assert_allclose(special.hankel2(-0.5, 1+1j), special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j)) def test_ticket_854(self): """Real-valued Bessel domains""" assert_(isnan(special.jv(0.5, -1))) assert_(isnan(special.iv(0.5, -1))) assert_(isnan(special.yv(0.5, -1))) assert_(isnan(special.yv(1, -1))) assert_(isnan(special.kv(0.5, -1))) assert_(isnan(special.kv(1, -1))) assert_(isnan(special.jve(0.5, -1))) assert_(isnan(special.ive(0.5, -1))) assert_(isnan(special.yve(0.5, -1))) assert_(isnan(special.yve(1, -1))) assert_(isnan(special.kve(0.5, -1))) assert_(isnan(special.kve(1, -1))) assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1)) assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1)) def test_gh_7909(self): assert_(special.kv(1.5, 0) == np.inf) assert_(special.kve(1.5, 0) == np.inf) def test_ticket_503(self): """Real-valued Bessel I overflow""" assert_allclose(special.iv(1, 700), 1.528500390233901e302) assert_allclose(special.iv(1000, 1120), 1.301564549405821e301) def test_iv_hyperg_poles(self): assert_allclose(special.iv(-0.5, 1), 1.231200214592967) def iv_series(self, v, z, n=200): k = arange(0, n).astype(float_) r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1) r[isnan(r)] = inf r = exp(r) err = abs(r).max() * finfo(float_).eps * n + abs(r[-1])*10 return r.sum(), err def test_i0_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(0, z) assert_allclose(special.i0(z), value, atol=err, err_msg=z) def test_i1_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(1, z) assert_allclose(special.i1(z), value, atol=err, err_msg=z) def test_iv_series(self): for v in [-20., -10., -1., 0., 1., 12.49, 120.]: for z in [1., 10., 200.5, -1+2j]: value, err = self.iv_series(v, z) assert_allclose(special.iv(v, z), value, atol=err, err_msg=(v, z)) def test_i0(self): values = [[0.0, 1.0], [1e-10, 1.0], [0.1, 0.9071009258], [0.5, 0.6450352706], [1.0, 0.4657596077], [2.5, 0.2700464416], [5.0, 0.1835408126], [20.0, 0.0897803119], ] for i, (x, v) in enumerate(values): cv = special.i0(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i0e(self): oize = special.i0e(.1) oizer = special.ive(0,.1) assert_almost_equal(oize,oizer,8) def test_i1(self): values = [[0.0, 0.0], [1e-10, 0.4999999999500000e-10], [0.1, 0.0452984468], [0.5, 0.1564208032], [1.0, 0.2079104154], [5.0, 0.1639722669], [20.0, 0.0875062222], ] for i, (x, v) in enumerate(values): cv = special.i1(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i1e(self): oi1e = special.i1e(.1) oi1er = special.ive(1,.1) assert_almost_equal(oi1e,oi1er,8) def test_iti0k0(self): iti0 = array(special.iti0k0(5)) assert_array_almost_equal(iti0,array([31.848667776169801, 1.5673873907283657]),5) def test_it2i0k0(self): it2k = special.it2i0k0(.1) assert_array_almost_equal(it2k,array([0.0012503906973464409, 3.3309450354686687]),6) def test_iv(self): iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(iv1,0.90710092578230106,10) def test_negv_ive(self): assert_equal(special.ive(3,2), special.ive(-3,2)) def test_ive(self): ive1 = special.ive(0,.1) iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(ive1,iv1,10) def test_ivp0(self): assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10) def test_ivp(self): y = (special.iv(0,2) + special.iv(2,2))/2 x = special.ivp(1,2) assert_almost_equal(x,y,10) class TestLaguerre(object): def test_laguerre(self): lag0 = special.laguerre(0) lag1 = special.laguerre(1) lag2 = special.laguerre(2) lag3 = special.laguerre(3) lag4 = special.laguerre(4) lag5 = special.laguerre(5) assert_array_almost_equal(lag0.c,[1],13) assert_array_almost_equal(lag1.c,[-1,1],13) assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13) assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13) assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) def test_genlaguerre(self): k = 5*np.random.random() - 0.9 lag0 = special.genlaguerre(0,k) lag1 = special.genlaguerre(1,k) lag2 = special.genlaguerre(2,k) lag3 = special.genlaguerre(3,k) assert_equal(lag0.c,[1]) assert_equal(lag1.c,[-1,k+1]) assert_almost_equal(lag2.c,array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0) assert_almost_equal(lag3.c,array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0) # Base polynomials come from Abrahmowitz and Stegan class TestLegendre(object): def test_legendre(self): leg0 = special.legendre(0) leg1 = special.legendre(1) leg2 = special.legendre(2) leg3 = special.legendre(3) leg4 = special.legendre(4) leg5 = special.legendre(5) assert_equal(leg0.c, [1]) assert_equal(leg1.c, [1,0]) assert_almost_equal(leg2.c, array([3,0,-1])/2.0, decimal=13) assert_almost_equal(leg3.c, array([5,0,-3,0])/2.0) assert_almost_equal(leg4.c, array([35,0,-30,0,3])/8.0) assert_almost_equal(leg5.c, array([63,0,-70,0,15,0])/8.0) class TestLambda(object): def test_lmbda(self): lam = special.lmbda(1,.1) lamr = (array([special.jn(0,.1), 2*special.jn(1,.1)/.1]), array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])) assert_array_almost_equal(lam,lamr,8) class TestLog1p(object): def test_log1p(self): l1p = (special.log1p(10), special.log1p(11), special.log1p(12)) l1prl = (log(11), log(12), log(13)) assert_array_almost_equal(l1p,l1prl,8) def test_log1pmore(self): l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2)) l1pmrl = (log(2),log(2.1),log(2.2)) assert_array_almost_equal(l1pm,l1pmrl,8) class TestLegendreFunctions(object): def test_clpmn(self): z = 0.5+0.3j clp = special.clpmn(2, 2, z, 3) assert_array_almost_equal(clp, (array([[1.0000, z, 0.5*(3*z*z-1)], [0.0000, sqrt(z*z-1), 3*z*sqrt(z*z-1)], [0.0000, 0.0000, 3*(z*z-1)]]), array([[0.0000, 1.0000, 3*z], [0.0000, z/sqrt(z*z-1), 3*(2*z*z-1)/sqrt(z*z-1)], [0.0000, 0.0000, 6*z]])), 7) def test_clpmn_close_to_real_2(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x), special.lpmv(m, n, x)]), 7) def test_clpmn_close_to_real_3(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi), special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]), 7) def test_clpmn_across_unit_circle(self): eps = 1e-7 m = 1 n = 1 x = 1j for type in [2, 3]: assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n], special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6) def test_inf(self): for z in (1, -1): for n in range(4): for m in range(1, n): lp = special.clpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) lp = special.lpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) def test_deriv_clpmn(self): # data inside and outside of the unit circle zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j, 1+1j, -1+1j, -1-1j, 1-1j] m = 2 n = 3 for type in [2, 3]: for z in zvals: for h in [1e-3, 1e-3j]: approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0] - special.clpmn(m, n, z-0.5*h, type)[0])/h assert_allclose(special.clpmn(m, n, z, type)[1], approx_derivative, rtol=1e-4) def test_lpmn(self): lp = special.lpmn(0,2,.5) assert_array_almost_equal(lp,(array([[1.00000, 0.50000, -0.12500]]), array([[0.00000, 1.00000, 1.50000]])),4) def test_lpn(self): lpnf = special.lpn(2,.5) assert_array_almost_equal(lpnf,(array([1.00000, 0.50000, -0.12500]), array([0.00000, 1.00000, 1.50000])),4) def test_lpmv(self): lp = special.lpmv(0,2,.5) assert_almost_equal(lp,-0.125,7) lp = special.lpmv(0,40,.001) assert_almost_equal(lp,0.1252678976534484,7) # XXX: this is outside the domain of the current implementation, # so ensure it returns a NaN rather than a wrong answer. olderr = np.seterr(all='ignore') try: lp = special.lpmv(-1,-1,.001) finally: np.seterr(**olderr) assert_(lp != 0 or np.isnan(lp)) def test_lqmn(self): lqmnf = special.lqmn(0,2,.5) lqf = special.lqn(2,.5) assert_array_almost_equal(lqmnf[0][0],lqf[0],4) assert_array_almost_equal(lqmnf[1][0],lqf[1],4) def test_lqmn_gt1(self): """algorithm for real arguments changes at 1.0001 test against analytical result for m=2, n=1 """ x0 = 1.0001 delta = 0.00002 for x in (x0-delta, x0+delta): lq = special.lqmn(2, 1, x)[0][-1, -1] expected = 2/(x*x-1) assert_almost_equal(lq, expected) def test_lqmn_shape(self): a, b = special.lqmn(4, 4, 1.1) assert_equal(a.shape, (5, 5)) assert_equal(b.shape, (5, 5)) a, b = special.lqmn(4, 0, 1.1) assert_equal(a.shape, (5, 1)) assert_equal(b.shape, (5, 1)) def test_lqn(self): lqf = special.lqn(2,.5) assert_array_almost_equal(lqf,(array([0.5493, -0.7253, -0.8187]), array([1.3333, 1.216, -0.8427])),4) class TestMathieu(object): def test_mathieu_a(self): pass def test_mathieu_even_coef(self): special.mathieu_even_coef(2,5) # Q not defined broken and cannot figure out proper reporting order def test_mathieu_odd_coef(self): # same problem as above pass class TestFresnelIntegral(object): def test_modfresnelp(self): pass def test_modfresnelm(self): pass class TestOblCvSeq(object): def test_obl_cv_seq(self): obl = special.obl_cv_seq(0,3,1) assert_array_almost_equal(obl,array([-0.348602, 1.393206, 5.486800, 11.492120]),5) class TestParabolicCylinder(object): def test_pbdn_seq(self): pb = special.pbdn_seq(1,.1) assert_array_almost_equal(pb,(array([0.9975, 0.0998]), array([-0.0499, 0.9925])),4) def test_pbdv(self): special.pbdv(1,.2) 1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0] def test_pbdv_seq(self): pbn = special.pbdn_seq(1,.1) pbv = special.pbdv_seq(1,.1) assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) def test_pbdv_points(self): # simple case eta = np.linspace(-10, 10, 5) z = 2**(eta/2)*np.sqrt(np.pi)/special.gamma(.5-.5*eta) assert_allclose(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14) # some points assert_allclose(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12) assert_allclose(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12) def test_pbdv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbdv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) def test_pbvv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbvv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) class TestPolygamma(object): # from Table 6.2 (pg. 271) of A&S def test_polygamma(self): poly2 = special.polygamma(2,1) poly3 = special.polygamma(3,1) assert_almost_equal(poly2,-2.4041138063,10) assert_almost_equal(poly3,6.4939394023,10) # Test polygamma(0, x) == psi(x) x = [2, 3, 1.1e14] assert_almost_equal(special.polygamma(0, x), special.psi(x)) # Test broadcasting n = [0, 1, 2] x = [0.5, 1.5, 2.5] expected = [-1.9635100260214238, 0.93480220054467933, -0.23620405164172739] assert_almost_equal(special.polygamma(n, x), expected) expected = np.row_stack([expected]*2) assert_almost_equal(special.polygamma(n, np.row_stack([x]*2)), expected) assert_almost_equal(special.polygamma(np.row_stack([n]*2), x), expected) class TestProCvSeq(object): def test_pro_cv_seq(self): prol = special.pro_cv_seq(0,3,1) assert_array_almost_equal(prol,array([0.319000, 2.593084, 6.533471, 12.514462]),5) class TestPsi(object): def test_psi(self): ps = special.psi(1) assert_almost_equal(ps,-0.57721566490153287,8) class TestRadian(object): def test_radian(self): rad = special.radian(90,0,0) assert_almost_equal(rad,pi/2.0,5) def test_radianmore(self): rad1 = special.radian(90,1,60) assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) class TestRiccati(object): def test_riccati_jn(self): N, x = 2, 0.2 S = np.empty((N, N)) for n in range(N): j = special.spherical_jn(n, x) jp = special.spherical_jn(n, x, derivative=True) S[0,n] = x*j S[1,n] = x*jp + j assert_array_almost_equal(S, special.riccati_jn(n, x), 8) def test_riccati_yn(self): N, x = 2, 0.2 C = np.empty((N, N)) for n in range(N): y = special.spherical_yn(n, x) yp = special.spherical_yn(n, x, derivative=True) C[0,n] = x*y C[1,n] = x*yp + y assert_array_almost_equal(C, special.riccati_yn(n, x), 8) class TestRound(object): def test_round(self): rnd = list(map(int,(special.round(10.1),special.round(10.4),special.round(10.5),special.round(10.6)))) # Note: According to the documentation, scipy.special.round is # supposed to round to the nearest even number if the fractional # part is exactly 0.5. On some platforms, this does not appear # to work and thus this test may fail. However, this unit test is # correctly written. rndrl = (10,10,10,11) assert_array_equal(rnd,rndrl) def test_sph_harm(): # Tests derived from tables in # https://en.wikipedia.org/wiki/Table_of_spherical_harmonics sh = special.sph_harm pi = np.pi exp = np.exp sqrt = np.sqrt sin = np.sin cos = np.cos assert_array_almost_equal(sh(0,0,0,0), 0.5/sqrt(pi)) assert_array_almost_equal(sh(-2,2,0.,pi/4), 0.25*sqrt(15./(2.*pi)) * (sin(pi/4))**2.) assert_array_almost_equal(sh(-2,2,0.,pi/2), 0.25*sqrt(15./(2.*pi))) assert_array_almost_equal(sh(2,2,pi,pi/2), 0.25*sqrt(15/(2.*pi)) * exp(0+2.*pi*1j)*sin(pi/2.)**2.) assert_array_almost_equal(sh(2,4,pi/4.,pi/3.), (3./8.)*sqrt(5./(2.*pi)) * exp(0+2.*pi/4.*1j) * sin(pi/3.)**2. * (7.*cos(pi/3.)**2.-1)) assert_array_almost_equal(sh(4,4,pi/8.,pi/6.), (3./16.)*sqrt(35./(2.*pi)) * exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.) def test_sph_harm_ufunc_loop_selection(): # see https://github.com/scipy/scipy/issues/4895 dt = np.dtype(np.complex128) assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt) assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt) assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt) assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt) assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt) assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt) class TestStruve(object): def _series(self, v, z, n=100): """Compute Struve function & error estimate from its power series.""" k = arange(0, n) r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5) err = abs(r).max() * finfo(float_).eps * n return r.sum(), err def test_vs_series(self): """Check Struve function versus its power series""" for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]: for z in [1, 10, 19, 21, 30]: value, err = self._series(v, z) assert_allclose(special.struve(v, z), value, rtol=0, atol=err), (v, z) def test_some_values(self): assert_allclose(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7) assert_allclose(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8) assert_allclose(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12) assert_allclose(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11) assert_equal(special.struve(-12, -41), -special.struve(-12, 41)) assert_equal(special.struve(+12, -41), -special.struve(+12, 41)) assert_equal(special.struve(-11, -41), +special.struve(-11, 41)) assert_equal(special.struve(+11, -41), +special.struve(+11, 41)) assert_(isnan(special.struve(-7.1, -1))) assert_(isnan(special.struve(-10.1, -1))) def test_regression_679(self): """Regression test for #679""" assert_allclose(special.struve(-1.0, 20 - 1e-8), special.struve(-1.0, 20 + 1e-8)) assert_allclose(special.struve(-2.0, 20 - 1e-8), special.struve(-2.0, 20 + 1e-8)) assert_allclose(special.struve(-4.3, 20 - 1e-8), special.struve(-4.3, 20 + 1e-8)) def test_chi2_smalldf(): assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110) def test_ch2_inf(): assert_equal(special.chdtr(0.7,np.inf), 1.0) def test_chi2c_smalldf(): assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110) def test_chi2_inv_smalldf(): assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3) def test_agm_simple(): rtol = 1e-13 # Gauss's constant assert_allclose(1/special.agm(1, np.sqrt(2)), 0.834626841674073186, rtol=rtol) # These values were computed using Wolfram Alpha, with the # function ArithmeticGeometricMean[a, b]. agm13 = 1.863616783244897 agm15 = 2.604008190530940 agm35 = 3.936235503649555 assert_allclose(special.agm([[1], [3]], [1, 3, 5]), [[1, agm13, agm15], [agm13, 3, agm35]], rtol=rtol) # Computed by the iteration formula using mpmath, # with mpmath.mp.prec = 1000: agm12 = 1.4567910310469068 assert_allclose(special.agm(1, 2), agm12, rtol=rtol) assert_allclose(special.agm(2, 1), agm12, rtol=rtol) assert_allclose(special.agm(-1, -2), -agm12, rtol=rtol) assert_allclose(special.agm(24, 6), 13.458171481725614, rtol=rtol) assert_allclose(special.agm(13, 123456789.5), 11111458.498599306, rtol=rtol) assert_allclose(special.agm(1e30, 1), 2.229223055945383e+28, rtol=rtol) assert_allclose(special.agm(1e-22, 1), 0.030182566420169886, rtol=rtol) assert_allclose(special.agm(1e150, 1e180), 2.229223055945383e+178, rtol=rtol) assert_allclose(special.agm(1e180, 1e-150), 2.0634722510162677e+177, rtol=rtol) assert_allclose(special.agm(1e-150, 1e-170), 3.3112619670463756e-152, rtol=rtol) fi = np.finfo(1.0) assert_allclose(special.agm(fi.tiny, fi.max), 1.9892072050015473e+305, rtol=rtol) assert_allclose(special.agm(0.75*fi.max, fi.max), 1.564904312298045e+308, rtol=rtol) assert_allclose(special.agm(fi.tiny, 3*fi.tiny), 4.1466849866735005e-308, rtol=rtol) # zero, nan and inf cases. assert_equal(special.agm(0, 0), 0) assert_equal(special.agm(99, 0), 0) assert_equal(special.agm(-1, 10), np.nan) assert_equal(special.agm(0, np.inf), np.nan) assert_equal(special.agm(np.inf, 0), np.nan) assert_equal(special.agm(0, -np.inf), np.nan) assert_equal(special.agm(-np.inf, 0), np.nan) assert_equal(special.agm(np.inf, -np.inf), np.nan) assert_equal(special.agm(-np.inf, np.inf), np.nan) assert_equal(special.agm(1, np.nan), np.nan) assert_equal(special.agm(np.nan, -1), np.nan) assert_equal(special.agm(1, np.inf), np.inf) assert_equal(special.agm(np.inf, 1), np.inf) assert_equal(special.agm(-1, -np.inf), -np.inf) assert_equal(special.agm(-np.inf, -1), -np.inf) def test_legacy(): # Legacy behavior: truncating arguments to integers with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3)) assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3)) assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3)) assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3)) assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3)) assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3)) assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3)) assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3)) assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3)) @with_special_errors def test_error_raising(): assert_raises(special.SpecialFunctionError, special.iv, 1, 1e99j) def test_xlogy(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x*np.log(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float) z2 = np.r_[z1, [(0, 1j), (1, 1j)]] w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13) w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1]) assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13) def test_xlog1py(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x * np.log1p(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0), (1, 1e-30)], dtype=float) w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13) def test_entr(): def xfunc(x): if x < 0: return -np.inf else: return -special.xlogy(x, x) values = (0, 0.5, 1.0, np.inf) signs = [-1, 1] arr = [] for sgn, v in itertools.product(signs, values): arr.append(sgn * v) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z) assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13) def test_kl_div(): def xfunc(x, y): if x < 0 or y < 0 or (y == 0 and x != 0): # extension of natural domain to preserve convexity return np.inf elif np.isposinf(x) or np.isposinf(y): # limits within the natural domain return np.inf elif x == 0: return y else: return special.xlogy(x, x/y) - x + y values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13) def test_rel_entr(): def xfunc(x, y): if x > 0 and y > 0: return special.xlogy(x, x/y) elif x == 0 and y >= 0: return 0 else: return np.inf values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13) def test_huber(): assert_equal(special.huber(-1, 1.5), np.inf) assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5)) assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2)) def xfunc(delta, r): if delta < 0: return np.inf elif np.abs(r) < delta: return 0.5 * np.square(r) else: return delta * (np.abs(r) - 0.5 * delta) z = np.random.randn(10, 2) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13) def test_pseudo_huber(): def xfunc(delta, r): if delta < 0: return np.inf elif (not delta) or (not r): return 0 else: return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1) z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]]) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13)
aeklant/scipy
scipy/special/tests/test_basic.py
scipy/io/matlab/tests/test_mio.py
import numpy as np import scipy.special as sc from scipy.special._testutils import FuncData def test_sici_consistency(): # Make sure the implementation of sici for real arguments agrees # with the implementation of sici for complex arguments. # On the negative real axis Cephes drops the imaginary part in ci def sici(x): si, ci = sc.sici(x + 0j) return si.real, ci.real x = np.r_[-np.logspace(8, -30, 200), 0, np.logspace(-30, 8, 200)] si, ci = sc.sici(x) dataset = np.column_stack((x, si, ci)) FuncData(sici, dataset, 0, (1, 2), rtol=1e-12).check() def test_shichi_consistency(): # Make sure the implementation of shichi for real arguments agrees # with the implementation of shichi for complex arguments. # On the negative real axis Cephes drops the imaginary part in chi def shichi(x): shi, chi = sc.shichi(x + 0j) return shi.real, chi.real # Overflow happens quickly, so limit range x = np.r_[-np.logspace(np.log10(700), -30, 200), 0, np.logspace(-30, np.log10(700), 200)] shi, chi = sc.shichi(x) dataset = np.column_stack((x, shi, chi)) FuncData(shichi, dataset, 0, (1, 2), rtol=1e-14).check()
# this program corresponds to special.py ### Means test is not done yet # E Means test is giving error (E) # F Means test is failing (F) # EF Means test is giving error and Failing #! Means test is segfaulting # 8 Means test runs forever ### test_besselpoly ### test_mathieu_a ### test_mathieu_even_coef ### test_mathieu_odd_coef ### test_modfresnelp ### test_modfresnelm # test_pbdv_seq ### test_pbvv_seq ### test_sph_harm import itertools import platform import numpy as np from numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp, log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, float_) import pytest from pytest import raises as assert_raises from numpy.testing import (assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_approx_equal, assert_, assert_allclose, assert_array_almost_equal_nulp, suppress_warnings) from scipy import special import scipy.special._ufuncs as cephes from scipy.special import ellipk from scipy.special._testutils import with_special_errors, \ assert_func_equal, FuncData import math class TestCephes(object): def test_airy(self): cephes.airy(0) def test_airye(self): cephes.airye(0) def test_binom(self): n = np.array([0.264, 4, 5.2, 17]) k = np.array([2, 0.4, 7, 3.3]) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389, -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846], [10.92, 2.22993515861399, -0.00585728, 10.468891352063146], [136, 3.5252179590758828, 19448, 1024.5526916174495]]) assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13) # Test branches in implementation np.random.seed(1234) n = np.r_[np.arange(-7, 30), 1000*np.random.rand(30) - 500] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_2(self): # Test branches in implementation np.random.seed(1234) n = np.r_[np.logspace(1, 300, 20)] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_exact(self): @np.vectorize def binom_int(n, k): n = int(n) k = int(k) num = int(1) den = int(1) for i in range(1, k+1): num *= i + n - k den *= i return float(num/den) np.random.seed(1234) n = np.arange(1, 15) k = np.arange(0, 15) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T nk = nk[nk[:,0] >= nk[:,1]] assert_func_equal(cephes.binom, binom_int(nk[:,0], nk[:,1]), nk, atol=0, rtol=0) def test_binom_nooverflow_8346(self): # Test (binom(n, k) doesn't overflow prematurely */ dataset = [ (1000, 500, 2.70288240945436551e+299), (1002, 501, 1.08007396880791225e+300), (1004, 502, 4.31599279169058121e+300), (1006, 503, 1.72468101616263781e+301), (1008, 504, 6.89188009236419153e+301), (1010, 505, 2.75402257948335448e+302), (1012, 506, 1.10052048531923757e+303), (1014, 507, 4.39774063758732849e+303), (1016, 508, 1.75736486108312519e+304), (1018, 509, 7.02255427788423734e+304), (1020, 510, 2.80626776829962255e+305), (1022, 511, 1.12140876377061240e+306), (1024, 512, 4.48125455209897109e+306), (1026, 513, 1.79075474304149900e+307), (1028, 514, 7.15605105487789676e+307) ] dataset = np.asarray(dataset) FuncData(cephes.binom, dataset, (0, 1), 2, rtol=1e-12).check() def test_bdtr(self): assert_equal(cephes.bdtr(1,1,0.5),1.0) def test_bdtri(self): assert_equal(cephes.bdtri(1,3,0.5),0.5) def test_bdtrc(self): assert_equal(cephes.bdtrc(1,3,0.5),0.5) def test_bdtrin(self): assert_equal(cephes.bdtrin(1,0,1),5.0) def test_bdtrik(self): cephes.bdtrik(1,3,0.5) def test_bei(self): assert_equal(cephes.bei(0),0.0) def test_beip(self): assert_equal(cephes.beip(0),0.0) def test_ber(self): assert_equal(cephes.ber(0),1.0) def test_berp(self): assert_equal(cephes.berp(0),0.0) def test_besselpoly(self): assert_equal(cephes.besselpoly(0,0,0),1.0) def test_beta(self): assert_equal(cephes.beta(1,1),1.0) assert_allclose(cephes.beta(-100.3, 1e-200), cephes.gamma(1e-200)) assert_allclose(cephes.beta(0.0342, 171), 24.070498359873497, rtol=1e-13, atol=0) def test_betainc(self): assert_equal(cephes.betainc(1,1,1),1.0) assert_allclose(cephes.betainc(0.0342, 171, 1e-10), 0.55269916901806648) def test_betaln(self): assert_equal(cephes.betaln(1,1),0.0) assert_allclose(cephes.betaln(-100.3, 1e-200), cephes.gammaln(1e-200)) assert_allclose(cephes.betaln(0.0342, 170), 3.1811881124242447, rtol=1e-14, atol=0) def test_betaincinv(self): assert_equal(cephes.betaincinv(1,1,1),1.0) assert_allclose(cephes.betaincinv(0.0342, 171, 0.25), 8.4231316935498957e-21, rtol=3e-12, atol=0) def test_beta_inf(self): assert_(np.isinf(special.beta(-1, 2))) def test_btdtr(self): assert_equal(cephes.btdtr(1,1,1),1.0) def test_btdtri(self): assert_equal(cephes.btdtri(1,1,1),1.0) def test_btdtria(self): assert_equal(cephes.btdtria(1,1,1),5.0) def test_btdtrib(self): assert_equal(cephes.btdtrib(1,1,1),5.0) def test_cbrt(self): assert_approx_equal(cephes.cbrt(1),1.0) def test_chdtr(self): assert_equal(cephes.chdtr(1,0),0.0) def test_chdtrc(self): assert_equal(cephes.chdtrc(1,0),1.0) def test_chdtri(self): assert_equal(cephes.chdtri(1,1),0.0) def test_chdtriv(self): assert_equal(cephes.chdtriv(0,0),5.0) def test_chndtr(self): assert_equal(cephes.chndtr(0,1,0),0.0) # Each row holds (x, nu, lam, expected_value) # These values were computed using Wolfram Alpha with # CDF[NoncentralChiSquareDistribution[nu, lam], x] values = np.array([ [25.00, 20.0, 400, 4.1210655112396197139e-57], [25.00, 8.00, 250, 2.3988026526832425878e-29], [0.001, 8.00, 40., 5.3761806201366039084e-24], [0.010, 8.00, 40., 5.45396231055999457039e-20], [20.00, 2.00, 107, 1.39390743555819597802e-9], [22.50, 2.00, 107, 7.11803307138105870671e-9], [25.00, 2.00, 107, 3.11041244829864897313e-8], [3.000, 2.00, 1.0, 0.62064365321954362734], [350.0, 300., 10., 0.93880128006276407710], [100.0, 13.5, 10., 0.99999999650104210949], [700.0, 20.0, 400, 0.99999999925680650105], [150.0, 13.5, 10., 0.99999999999999983046], [160.0, 13.5, 10., 0.99999999999999999518], # 1.0 ]) cdf = cephes.chndtr(values[:, 0], values[:, 1], values[:, 2]) assert_allclose(cdf, values[:, 3], rtol=1e-12) assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0) assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0) assert_(np.isnan(cephes.chndtr(np.nan, 1, 2))) assert_(np.isnan(cephes.chndtr(5, np.nan, 2))) assert_(np.isnan(cephes.chndtr(5, 1, np.nan))) def test_chndtridf(self): assert_equal(cephes.chndtridf(0,0,1),5.0) def test_chndtrinc(self): assert_equal(cephes.chndtrinc(0,1,0),5.0) def test_chndtrix(self): assert_equal(cephes.chndtrix(0,1,0),0.0) def test_cosdg(self): assert_equal(cephes.cosdg(0),1.0) def test_cosm1(self): assert_equal(cephes.cosm1(0),0.0) def test_cotdg(self): assert_almost_equal(cephes.cotdg(45),1.0) def test_dawsn(self): assert_equal(cephes.dawsn(0),0.0) assert_allclose(cephes.dawsn(1.23), 0.50053727749081767) def test_diric(self): # Test behavior near multiples of 2pi. Regression test for issue # described in gh-4001. n_odd = [1, 5, 25] x = np.array(2*np.pi + 5e-5).astype(np.float32) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7) x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) x = np.array(2*np.pi + 1e-15).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) if hasattr(np, 'float128'): # No float128 available in 32-bit numpy x = np.array(2*np.pi + 1e-12).astype(np.float128) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19) n_even = [2, 4, 24] x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15) # Test at some values not near a multiple of pi x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi) octave_result = [0.872677996249965, 0.539344662916632, 0.127322003750035, -0.206011329583298] assert_almost_equal(special.diric(x, 3), octave_result, decimal=15) def test_diric_broadcasting(self): x = np.arange(5) n = np.array([1, 3, 7]) assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size)) def test_ellipe(self): assert_equal(cephes.ellipe(1),1.0) def test_ellipeinc(self): assert_equal(cephes.ellipeinc(0,1),0.0) def test_ellipj(self): cephes.ellipj(0,1) def test_ellipk(self): assert_allclose(ellipk(0), pi/2) def test_ellipkinc(self): assert_equal(cephes.ellipkinc(0,0),0.0) def test_erf(self): assert_equal(cephes.erf(0), 0.0) def test_erf_symmetry(self): x = 5.905732037710919 assert_equal(cephes.erf(x) + cephes.erf(-x), 0.0) def test_erfc(self): assert_equal(cephes.erfc(0), 1.0) def test_exp10(self): assert_approx_equal(cephes.exp10(2),100.0) def test_exp2(self): assert_equal(cephes.exp2(2),4.0) def test_expm1(self): assert_equal(cephes.expm1(0),0.0) assert_equal(cephes.expm1(np.inf), np.inf) assert_equal(cephes.expm1(-np.inf), -1) assert_equal(cephes.expm1(np.nan), np.nan) def test_expm1_complex(self): expm1 = cephes.expm1 assert_equal(expm1(0 + 0j), 0 + 0j) assert_equal(expm1(complex(np.inf, 0)), complex(np.inf, 0)) assert_equal(expm1(complex(np.inf, 1)), complex(np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 2)), complex(-np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 4)), complex(-np.inf, -np.inf)) assert_equal(expm1(complex(np.inf, 5)), complex(np.inf, -np.inf)) assert_equal(expm1(complex(1, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(0, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.inf, np.inf)), complex(np.inf, np.nan)) assert_equal(expm1(complex(-np.inf, np.inf)), complex(-1, 0)) assert_equal(expm1(complex(-np.inf, np.nan)), complex(-1, 0)) assert_equal(expm1(complex(np.inf, np.nan)), complex(np.inf, np.nan)) assert_equal(expm1(complex(0, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(1, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, 1)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, np.nan)), complex(np.nan, np.nan)) @pytest.mark.xfail(reason='The real part of expm1(z) bad at these points') def test_expm1_complex_hard(self): # The real part of this function is difficult to evaluate when # z.real = -log(cos(z.imag)). y = np.array([0.1, 0.2, 0.3, 5, 11, 20]) x = -np.log(np.cos(y)) z = x + 1j*y # evaluate using mpmath.expm1 with dps=1000 expected = np.array([-5.5507901846769623e-17+0.10033467208545054j, 2.4289354732893695e-18+0.20271003550867248j, 4.5235500262585768e-17+0.30933624960962319j, 7.8234305217489006e-17-3.3805150062465863j, -1.3685191953697676e-16-225.95084645419513j, 8.7175620481291045e-17+2.2371609442247422j]) found = cephes.expm1(z) # this passes. assert_array_almost_equal_nulp(found.imag, expected.imag, 3) # this fails. assert_array_almost_equal_nulp(found.real, expected.real, 20) def test_fdtr(self): assert_equal(cephes.fdtr(1, 1, 0), 0.0) # Computed using Wolfram Alpha: CDF[FRatioDistribution[1e-6, 5], 10] assert_allclose(cephes.fdtr(1e-6, 5, 10), 0.9999940790193488, rtol=1e-12) def test_fdtrc(self): assert_equal(cephes.fdtrc(1, 1, 0), 1.0) # Computed using Wolfram Alpha: # 1 - CDF[FRatioDistribution[2, 1/10], 1e10] assert_allclose(cephes.fdtrc(2, 0.1, 1e10), 0.27223784621293512, rtol=1e-12) def test_fdtri(self): assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]), array([0.9937365, 1.00630298]), rtol=1e-6) # From Wolfram Alpha: # CDF[FRatioDistribution[1/10, 1], 3] = 0.8756751669632105666874... p = 0.8756751669632105666874 assert_allclose(cephes.fdtri(0.1, 1, p), 3, rtol=1e-12) @pytest.mark.xfail(reason='Returns nan on i686.') def test_fdtri_mysterious_failure(self): assert_allclose(cephes.fdtri(1, 1, 0.5), 1) def test_fdtridfd(self): assert_equal(cephes.fdtridfd(1,0,0),5.0) def test_fresnel(self): assert_equal(cephes.fresnel(0),(0.0,0.0)) def test_gamma(self): assert_equal(cephes.gamma(5),24.0) def test_gammainccinv(self): assert_equal(cephes.gammainccinv(5,1),0.0) def test_gammaln(self): cephes.gammaln(10) def test_gammasgn(self): vals = np.array([-4, -3.5, -2.3, 1, 4.2], np.float64) assert_array_equal(cephes.gammasgn(vals), np.sign(cephes.rgamma(vals))) def test_gdtr(self): assert_equal(cephes.gdtr(1,1,0),0.0) def test_gdtr_inf(self): assert_equal(cephes.gdtr(1,1,np.inf),1.0) def test_gdtrc(self): assert_equal(cephes.gdtrc(1,1,0),1.0) def test_gdtria(self): assert_equal(cephes.gdtria(0,1,1),0.0) def test_gdtrib(self): cephes.gdtrib(1,0,1) # assert_equal(cephes.gdtrib(1,0,1),5.0) def test_gdtrix(self): cephes.gdtrix(1,1,.1) def test_hankel1(self): cephes.hankel1(1,1) def test_hankel1e(self): cephes.hankel1e(1,1) def test_hankel2(self): cephes.hankel2(1,1) def test_hankel2e(self): cephes.hankel2e(1,1) def test_hyp1f1(self): assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) cephes.hyp1f1(1,1,1) def test_hyp2f1(self): assert_equal(cephes.hyp2f1(1,1,1,0),1.0) def test_i0(self): assert_equal(cephes.i0(0),1.0) def test_i0e(self): assert_equal(cephes.i0e(0),1.0) def test_i1(self): assert_equal(cephes.i1(0),0.0) def test_i1e(self): assert_equal(cephes.i1e(0),0.0) def test_it2i0k0(self): cephes.it2i0k0(1) def test_it2j0y0(self): cephes.it2j0y0(1) def test_it2struve0(self): cephes.it2struve0(1) def test_itairy(self): cephes.itairy(1) def test_iti0k0(self): assert_equal(cephes.iti0k0(0),(0.0,0.0)) def test_itj0y0(self): assert_equal(cephes.itj0y0(0),(0.0,0.0)) def test_itmodstruve0(self): assert_equal(cephes.itmodstruve0(0),0.0) def test_itstruve0(self): assert_equal(cephes.itstruve0(0),0.0) def test_iv(self): assert_equal(cephes.iv(1,0),0.0) def _check_ive(self): assert_equal(cephes.ive(1,0),0.0) def test_j0(self): assert_equal(cephes.j0(0),1.0) def test_j1(self): assert_equal(cephes.j1(0),0.0) def test_jn(self): assert_equal(cephes.jn(0,0),1.0) def test_jv(self): assert_equal(cephes.jv(0,0),1.0) def _check_jve(self): assert_equal(cephes.jve(0,0),1.0) def test_k0(self): cephes.k0(2) def test_k0e(self): cephes.k0e(2) def test_k1(self): cephes.k1(2) def test_k1e(self): cephes.k1e(2) def test_kei(self): cephes.kei(2) def test_keip(self): assert_equal(cephes.keip(0),0.0) def test_ker(self): cephes.ker(2) def test_kerp(self): cephes.kerp(2) def _check_kelvin(self): cephes.kelvin(2) def test_kn(self): cephes.kn(1,1) def test_kolmogi(self): assert_equal(cephes.kolmogi(1),0.0) assert_(np.isnan(cephes.kolmogi(np.nan))) def test_kolmogorov(self): assert_equal(cephes.kolmogorov(0), 1.0) def test_kolmogp(self): assert_equal(cephes._kolmogp(0), -0.0) def test_kolmogc(self): assert_equal(cephes._kolmogc(0), 0.0) def test_kolmogci(self): assert_equal(cephes._kolmogci(0), 0.0) assert_(np.isnan(cephes._kolmogci(np.nan))) def _check_kv(self): cephes.kv(1,1) def _check_kve(self): cephes.kve(1,1) def test_log1p(self): log1p = cephes.log1p assert_equal(log1p(0), 0.0) assert_equal(log1p(-1), -np.inf) assert_equal(log1p(-2), np.nan) assert_equal(log1p(np.inf), np.inf) def test_log1p_complex(self): log1p = cephes.log1p c = complex assert_equal(log1p(0 + 0j), 0 + 0j) assert_equal(log1p(c(-1, 0)), c(-np.inf, 0)) with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in multiply") assert_allclose(log1p(c(1, np.inf)), c(np.inf, np.pi/2)) assert_equal(log1p(c(1, np.nan)), c(np.nan, np.nan)) assert_allclose(log1p(c(-np.inf, 1)), c(np.inf, np.pi)) assert_equal(log1p(c(np.inf, 1)), c(np.inf, 0)) assert_allclose(log1p(c(-np.inf, np.inf)), c(np.inf, 3*np.pi/4)) assert_allclose(log1p(c(np.inf, np.inf)), c(np.inf, np.pi/4)) assert_equal(log1p(c(np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(-np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, np.inf)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, 1)), c(np.nan, np.nan)) assert_equal(log1p(c(np.nan, np.nan)), c(np.nan, np.nan)) def test_lpmv(self): assert_equal(cephes.lpmv(0,0,1),1.0) def test_mathieu_a(self): assert_equal(cephes.mathieu_a(1,0),1.0) def test_mathieu_b(self): assert_equal(cephes.mathieu_b(1,0),1.0) def test_mathieu_cem(self): assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) # Test AMS 20.2.27 @np.vectorize def ce_smallq(m, q, z): z *= np.pi/180 if m == 0: return 2**(-0.5) * (1 - .5*q*cos(2*z)) # + O(q^2) elif m == 1: return cos(z) - q/8 * cos(3*z) # + O(q^2) elif m == 2: return cos(2*z) - q*(cos(4*z)/12 - 1/4) # + O(q^2) else: return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(0, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0], ce_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_sem(self): assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) # Test AMS 20.2.27 @np.vectorize def se_smallq(m, q, z): z *= np.pi/180 if m == 1: return sin(z) - q/8 * sin(3*z) # + O(q^2) elif m == 2: return sin(2*z) - q*sin(4*z)/12 # + O(q^2) else: return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(1, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0], se_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_modcem1(self): assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) def test_mathieu_modcem2(self): cephes.mathieu_modcem2(1,1,1) # Test reflection relation AMS 20.6.19 m = np.arange(0, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modcem2(m, q, -z)[0] fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0] y2 = -cephes.mathieu_modcem2(m, q, z)[0] - 2*fr*cephes.mathieu_modcem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_modsem1(self): assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) def test_mathieu_modsem2(self): cephes.mathieu_modsem2(1,1,1) # Test reflection relation AMS 20.6.20 m = np.arange(1, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modsem2(m, q, -z)[0] fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1] y2 = cephes.mathieu_modsem2(m, q, z)[0] - 2*fr*cephes.mathieu_modsem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_overflow(self): # Check that these return NaNs instead of causing a SEGV assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan)) def test_mathieu_ticket_1847(self): # Regression test --- this call had some out-of-bounds access # and could return nan occasionally for k in range(60): v = cephes.mathieu_modsem2(2, 100, -1) # Values from ACM TOMS 804 (derivate by numerical differentiation) assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10) assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4) def test_modfresnelm(self): cephes.modfresnelm(0) def test_modfresnelp(self): cephes.modfresnelp(0) def _check_modstruve(self): assert_equal(cephes.modstruve(1,0),0.0) def test_nbdtr(self): assert_equal(cephes.nbdtr(1,1,1),1.0) def test_nbdtrc(self): assert_equal(cephes.nbdtrc(1,1,1),0.0) def test_nbdtri(self): assert_equal(cephes.nbdtri(1,1,1),1.0) def __check_nbdtrik(self): cephes.nbdtrik(1,.4,.5) def test_nbdtrin(self): assert_equal(cephes.nbdtrin(1,0,0),5.0) def test_ncfdtr(self): assert_equal(cephes.ncfdtr(1,1,1,0),0.0) def test_ncfdtri(self): assert_equal(cephes.ncfdtri(1, 1, 1, 0), 0.0) f = [0.5, 1, 1.5] p = cephes.ncfdtr(2, 3, 1.5, f) assert_allclose(cephes.ncfdtri(2, 3, 1.5, p), f) def test_ncfdtridfd(self): dfd = [1, 2, 3] p = cephes.ncfdtr(2, dfd, 0.25, 15) assert_allclose(cephes.ncfdtridfd(2, p, 0.25, 15), dfd) def test_ncfdtridfn(self): dfn = [0.1, 1, 2, 3, 1e4] p = cephes.ncfdtr(dfn, 2, 0.25, 15) assert_allclose(cephes.ncfdtridfn(p, 2, 0.25, 15), dfn, rtol=1e-5) def test_ncfdtrinc(self): nc = [0.5, 1.5, 2.0] p = cephes.ncfdtr(2, 3, nc, 15) assert_allclose(cephes.ncfdtrinc(2, 3, p, 15), nc) def test_nctdtr(self): assert_equal(cephes.nctdtr(1,0,0),0.5) assert_equal(cephes.nctdtr(9, 65536, 45), 0.0) assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5) assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.))) assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.) assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.))) assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.))) assert_(np.isnan(cephes.nctdtr(2., 1., np.nan))) def __check_nctdtridf(self): cephes.nctdtridf(1,0.5,0) def test_nctdtrinc(self): cephes.nctdtrinc(1,0,0) def test_nctdtrit(self): cephes.nctdtrit(.1,0.2,.5) def test_nrdtrimn(self): assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) def test_nrdtrisd(self): assert_allclose(cephes.nrdtrisd(0.5,0.5,0.5), 0.0, atol=0, rtol=0) def test_obl_ang1(self): cephes.obl_ang1(1,1,1,0) def test_obl_ang1_cv(self): result = cephes.obl_ang1_cv(1,1,1,1,0) assert_almost_equal(result[0],1.0) assert_almost_equal(result[1],0.0) def _check_obl_cv(self): assert_equal(cephes.obl_cv(1,1,0),2.0) def test_obl_rad1(self): cephes.obl_rad1(1,1,1,0) def test_obl_rad1_cv(self): cephes.obl_rad1_cv(1,1,1,1,0) def test_obl_rad2(self): cephes.obl_rad2(1,1,1,0) def test_obl_rad2_cv(self): cephes.obl_rad2_cv(1,1,1,1,0) def test_pbdv(self): assert_equal(cephes.pbdv(1,0),(0.0,1.0)) def test_pbvv(self): cephes.pbvv(1,0) def test_pbwa(self): cephes.pbwa(1,0) def test_pdtr(self): val = cephes.pdtr(0, 1) assert_almost_equal(val, np.exp(-1)) # Edge case: m = 0. val = cephes.pdtr([0, 1, 2], 0) assert_array_equal(val, [1, 1, 1]) def test_pdtrc(self): val = cephes.pdtrc(0, 1) assert_almost_equal(val, 1 - np.exp(-1)) # Edge case: m = 0. val = cephes.pdtrc([0, 1, 2], 0.0) assert_array_equal(val, [0, 0, 0]) def test_pdtri(self): with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") cephes.pdtri(0.5,0.5) def test_pdtrik(self): k = cephes.pdtrik(0.5, 1) assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5) # Edge case: m = 0 or very small. k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6]) assert_array_equal(k, np.zeros((3, 3))) def test_pro_ang1(self): cephes.pro_ang1(1,1,1,0) def test_pro_ang1_cv(self): assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), array((1.0,0.0))) def _check_pro_cv(self): assert_equal(cephes.pro_cv(1,1,0),2.0) def test_pro_rad1(self): cephes.pro_rad1(1,1,1,0.1) def test_pro_rad1_cv(self): cephes.pro_rad1_cv(1,1,1,1,0) def test_pro_rad2(self): cephes.pro_rad2(1,1,1,0) def test_pro_rad2_cv(self): cephes.pro_rad2_cv(1,1,1,1,0) def test_psi(self): cephes.psi(1) def test_radian(self): assert_equal(cephes.radian(0,0,0),0) def test_rgamma(self): assert_equal(cephes.rgamma(1),1.0) def test_round(self): assert_equal(cephes.round(3.4),3.0) assert_equal(cephes.round(-3.4),-3.0) assert_equal(cephes.round(3.6),4.0) assert_equal(cephes.round(-3.6),-4.0) assert_equal(cephes.round(3.5),4.0) assert_equal(cephes.round(-3.5),-4.0) def test_shichi(self): cephes.shichi(1) def test_sici(self): cephes.sici(1) s, c = cephes.sici(np.inf) assert_almost_equal(s, np.pi * 0.5) assert_almost_equal(c, 0) s, c = cephes.sici(-np.inf) assert_almost_equal(s, -np.pi * 0.5) assert_(np.isnan(c), "cosine integral(-inf) is not nan") def test_sindg(self): assert_equal(cephes.sindg(90),1.0) def test_smirnov(self): assert_equal(cephes.smirnov(1,.1),0.9) assert_(np.isnan(cephes.smirnov(1,np.nan))) def test_smirnovp(self): assert_equal(cephes._smirnovp(1, .1), -1) assert_equal(cephes._smirnovp(2, 0.75), -2*(0.25)**(2-1)) assert_equal(cephes._smirnovp(3, 0.75), -3*(0.25)**(3-1)) assert_(np.isnan(cephes._smirnovp(1, np.nan))) def test_smirnovc(self): assert_equal(cephes._smirnovc(1,.1),0.1) assert_(np.isnan(cephes._smirnovc(1,np.nan))) x10 = np.linspace(0, 1, 11, endpoint=True) assert_almost_equal(cephes._smirnovc(3, x10), 1-cephes.smirnov(3, x10)) x4 = np.linspace(0, 1, 5, endpoint=True) assert_almost_equal(cephes._smirnovc(4, x4), 1-cephes.smirnov(4, x4)) def test_smirnovi(self): assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) assert_(np.isnan(cephes.smirnovi(1,np.nan))) def test_smirnovci(self): assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.4)),0.4) assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.6)),0.6) assert_(np.isnan(cephes._smirnovci(1,np.nan))) def test_spence(self): assert_equal(cephes.spence(1),0.0) def test_stdtr(self): assert_equal(cephes.stdtr(1,0),0.5) assert_almost_equal(cephes.stdtr(1,1), 0.75) assert_almost_equal(cephes.stdtr(1,2), 0.852416382349) def test_stdtridf(self): cephes.stdtridf(0.7,1) def test_stdtrit(self): cephes.stdtrit(1,0.7) def test_struve(self): assert_equal(cephes.struve(0,0),0.0) def test_tandg(self): assert_equal(cephes.tandg(45),1.0) def test_tklmbda(self): assert_almost_equal(cephes.tklmbda(1,1),1.0) def test_y0(self): cephes.y0(1) def test_y1(self): cephes.y1(1) def test_yn(self): cephes.yn(1,1) def test_yv(self): cephes.yv(1,1) def _check_yve(self): cephes.yve(1,1) def test_wofz(self): z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.), complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.), complex(-0.0000000234545,1.1234), complex(-3.,5.1), complex(-53,30.1), complex(0.0,0.12345), complex(11,1), complex(-22,-2), complex(9,-28), complex(21,-33), complex(1e5,1e5), complex(1e14,1e14) ] w = [ complex(-3.78270245518980507452677445620103199303131110e-7, 0.000903861276433172057331093754199933411710053155), complex(0.1764906227004816847297495349730234591778719532788, -0.02146550539468457616788719893991501311573031095617), complex(0.2410250715772692146133539023007113781272362309451, 0.06087579663428089745895459735240964093522265589350), complex(0.30474420525691259245713884106959496013413834051768, -0.20821893820283162728743734725471561394145872072738), complex(7.317131068972378096865595229600561710140617977e34, 8.321873499714402777186848353320412813066170427e34), complex(0.0615698507236323685519612934241429530190806818395, -0.00676005783716575013073036218018565206070072304635), complex(0.3960793007699874918961319170187598400134746631, -5.593152259116644920546186222529802777409274656e-9), complex(0.08217199226739447943295069917990417630675021771804, -0.04701291087643609891018366143118110965272615832184), complex(0.00457246000350281640952328010227885008541748668738, -0.00804900791411691821818731763401840373998654987934), complex(0.8746342859608052666092782112565360755791467973338452, 0.), complex(0.00468190164965444174367477874864366058339647648741, 0.0510735563901306197993676329845149741675029197050), complex(-0.0023193175200187620902125853834909543869428763219, -0.025460054739731556004902057663500272721780776336), complex(9.11463368405637174660562096516414499772662584e304, 3.97101807145263333769664875189354358563218932e305), complex(-4.4927207857715598976165541011143706155432296e281, -2.8019591213423077494444700357168707775769028e281), complex(2.820947917809305132678577516325951485807107151e-6, 2.820947917668257736791638444590253942253354058e-6), complex(2.82094791773878143474039725787438662716372268e-15, 2.82094791773878143474039725773333923127678361e-15) ] assert_func_equal(cephes.wofz, w, z, rtol=1e-13) class TestAiry(object): def test_airy(self): # This tests the airy function to ensure 8 place accuracy in computation x = special.airy(.99) assert_array_almost_equal(x,array([0.13689066,-0.16050153,1.19815925,0.92046818]),8) x = special.airy(.41) assert_array_almost_equal(x,array([0.25238916,-.23480512,0.80686202,0.51053919]),8) x = special.airy(-.36) assert_array_almost_equal(x,array([0.44508477,-0.23186773,0.44939534,0.48105354]),8) def test_airye(self): a = special.airye(0.01) b = special.airy(0.01) b1 = [None]*4 for n in range(2): b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01)) for n in range(2,4): b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) assert_array_almost_equal(a,b1,6) def test_bi_zeros(self): bi = special.bi_zeros(2) bia = (array([-1.17371322, -3.2710930]), array([-2.29443968, -4.07315509]), array([-0.45494438, 0.39652284]), array([0.60195789, -0.76031014])) assert_array_almost_equal(bi,bia,4) bi = special.bi_zeros(5) assert_array_almost_equal(bi[0],array([-1.173713222709127, -3.271093302836352, -4.830737841662016, -6.169852128310251, -7.376762079367764]),11) assert_array_almost_equal(bi[1],array([-2.294439682614122, -4.073155089071828, -5.512395729663599, -6.781294445990305, -7.940178689168587]),10) assert_array_almost_equal(bi[2],array([-0.454944383639657, 0.396522836094465, -0.367969161486959, 0.349499116831805, -0.336026240133662]),11) assert_array_almost_equal(bi[3],array([0.601957887976239, -0.760310141492801, 0.836991012619261, -0.88947990142654, 0.929983638568022]),10) def test_ai_zeros(self): ai = special.ai_zeros(1) assert_array_almost_equal(ai,(array([-2.33810741]), array([-1.01879297]), array([0.5357]), array([0.7012])),4) def test_ai_zeros_big(self): z, zp, ai_zpx, aip_zx = special.ai_zeros(50000) ai_z, aip_z, _, _ = special.airy(z) ai_zp, aip_zp, _, _ = special.airy(zp) ai_envelope = 1/abs(z)**(1./4) aip_envelope = abs(zp)**(1./4) # Check values assert_allclose(ai_zpx, ai_zp, rtol=1e-10) assert_allclose(aip_zx, aip_z, rtol=1e-10) # Check they are zeros assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0) assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.1 assert_allclose(z[:6], [-2.3381074105, -4.0879494441, -5.5205598281, -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10) assert_allclose(zp[:6], [-1.0187929716, -3.2481975822, -4.8200992112, -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10) def test_bi_zeros_big(self): z, zp, bi_zpx, bip_zx = special.bi_zeros(50000) _, _, bi_z, bip_z = special.airy(z) _, _, bi_zp, bip_zp = special.airy(zp) bi_envelope = 1/abs(z)**(1./4) bip_envelope = abs(zp)**(1./4) # Check values assert_allclose(bi_zpx, bi_zp, rtol=1e-10) assert_allclose(bip_zx, bip_z, rtol=1e-10) # Check they are zeros assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0) assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.2 assert_allclose(z[:6], [-1.1737132227, -3.2710933028, -4.8307378417, -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10) assert_allclose(zp[:6], [-2.2944396826, -4.0731550891, -5.5123957297, -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10) class TestAssocLaguerre(object): def test_assoc_laguerre(self): a1 = special.genlaguerre(11,1) a2 = special.assoc_laguerre(.2,11,1) assert_array_almost_equal(a2,a1(.2),8) a2 = special.assoc_laguerre(1,11,1) assert_array_almost_equal(a2,a1(1),8) class TestBesselpoly(object): def test_besselpoly(self): pass class TestKelvin(object): def test_bei(self): mbei = special.bei(2) assert_almost_equal(mbei, 0.9722916273066613,5) # this may not be exact def test_beip(self): mbeip = special.beip(2) assert_almost_equal(mbeip,0.91701361338403631,5) # this may not be exact def test_ber(self): mber = special.ber(2) assert_almost_equal(mber,0.75173418271380821,5) # this may not be exact def test_berp(self): mberp = special.berp(2) assert_almost_equal(mberp,-0.49306712470943909,5) # this may not be exact def test_bei_zeros(self): # Abramowitz & Stegun, Table 9.12 bi = special.bei_zeros(5) assert_array_almost_equal(bi,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) def test_beip_zeros(self): bip = special.beip_zeros(5) assert_array_almost_equal(bip,array([3.772673304934953, 8.280987849760042, 12.742147523633703, 17.193431752512542, 21.641143941167325]),8) def test_ber_zeros(self): ber = special.ber_zeros(5) assert_array_almost_equal(ber,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) def test_berp_zeros(self): brp = special.berp_zeros(5) assert_array_almost_equal(brp,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) def test_kelvin(self): mkelv = special.kelvin(2) assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j, special.ker(2) + special.kei(2)*1j, special.berp(2) + special.beip(2)*1j, special.kerp(2) + special.keip(2)*1j),8) def test_kei(self): mkei = special.kei(2) assert_almost_equal(mkei,-0.20240006776470432,5) def test_keip(self): mkeip = special.keip(2) assert_almost_equal(mkeip,0.21980790991960536,5) def test_ker(self): mker = special.ker(2) assert_almost_equal(mker,-0.041664513991509472,5) def test_kerp(self): mkerp = special.kerp(2) assert_almost_equal(mkerp,-0.10660096588105264,5) def test_kei_zeros(self): kei = special.kei_zeros(5) assert_array_almost_equal(kei,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) def test_keip_zeros(self): keip = special.keip_zeros(5) assert_array_almost_equal(keip,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) # numbers come from 9.9 of A&S pg. 381 def test_kelvin_zeros(self): tmp = special.kelvin_zeros(5) berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp assert_array_almost_equal(berz,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) assert_array_almost_equal(beiz,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) assert_array_almost_equal(kerz,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44382]),4) assert_array_almost_equal(keiz,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) assert_array_almost_equal(berpz,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) assert_array_almost_equal(beipz,array([3.77267, # table from 1927 had 3.77320 # but this is more accurate 8.28099, 12.74215, 17.19343, 21.64114]),4) assert_array_almost_equal(kerpz,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) assert_array_almost_equal(keipz,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) def test_ker_zeros(self): ker = special.ker_zeros(5) assert_array_almost_equal(ker,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44381]),4) def test_kerp_zeros(self): kerp = special.kerp_zeros(5) assert_array_almost_equal(kerp,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) class TestBernoulli(object): def test_bernoulli(self): brn = special.bernoulli(5) assert_array_almost_equal(brn,array([1.0000, -0.5000, 0.1667, 0.0000, -0.0333, 0.0000]),4) class TestBeta(object): def test_beta(self): bet = special.beta(2,4) betg = (special.gamma(2)*special.gamma(4))/special.gamma(6) assert_almost_equal(bet,betg,8) def test_betaln(self): betln = special.betaln(2,4) bet = log(abs(special.beta(2,4))) assert_almost_equal(betln,bet,8) def test_betainc(self): btinc = special.betainc(1,1,.2) assert_almost_equal(btinc,0.2,8) def test_betaincinv(self): y = special.betaincinv(2,4,.5) comp = special.betainc(2,4,y) assert_almost_equal(comp,.5,5) class TestCombinatorics(object): def test_comb(self): assert_array_almost_equal(special.comb([10, 10], [3, 4]), [120., 210.]) assert_almost_equal(special.comb(10, 3), 120.) assert_equal(special.comb(10, 3, exact=True), 120) assert_equal(special.comb(10, 3, exact=True, repetition=True), 220) assert_allclose([special.comb(20, k, exact=True) for k in range(21)], special.comb(20, list(range(21))), atol=1e-15) ii = np.iinfo(int).max + 1 assert_equal(special.comb(ii, ii-1, exact=True), ii) expected = 100891344545564193334812497256 assert_equal(special.comb(100, 50, exact=True), expected) def test_comb_with_np_int64(self): n = 70 k = 30 np_n = np.int64(n) np_k = np.int64(k) assert_equal(special.comb(np_n, np_k, exact=True), special.comb(n, k, exact=True)) def test_comb_zeros(self): assert_equal(special.comb(2, 3, exact=True), 0) assert_equal(special.comb(-1, 3, exact=True), 0) assert_equal(special.comb(2, -1, exact=True), 0) assert_equal(special.comb(2, -1, exact=False), 0) assert_array_almost_equal(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 120.]) def test_perm(self): assert_array_almost_equal(special.perm([10, 10], [3, 4]), [720., 5040.]) assert_almost_equal(special.perm(10, 3), 720.) assert_equal(special.perm(10, 3, exact=True), 720) def test_perm_zeros(self): assert_equal(special.perm(2, 3, exact=True), 0) assert_equal(special.perm(-1, 3, exact=True), 0) assert_equal(special.perm(2, -1, exact=True), 0) assert_equal(special.perm(2, -1, exact=False), 0) assert_array_almost_equal(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 720.]) class TestTrigonometric(object): def test_cbrt(self): cb = special.cbrt(27) cbrl = 27**(1.0/3.0) assert_approx_equal(cb,cbrl) def test_cbrtmore(self): cb1 = special.cbrt(27.9) cbrl1 = 27.9**(1.0/3.0) assert_almost_equal(cb1,cbrl1,8) def test_cosdg(self): cdg = special.cosdg(90) cdgrl = cos(pi/2.0) assert_almost_equal(cdg,cdgrl,8) def test_cosdgmore(self): cdgm = special.cosdg(30) cdgmrl = cos(pi/6.0) assert_almost_equal(cdgm,cdgmrl,8) def test_cosm1(self): cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10)) csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) assert_array_almost_equal(cs,csrl,8) def test_cotdg(self): ct = special.cotdg(30) ctrl = tan(pi/6.0)**(-1) assert_almost_equal(ct,ctrl,8) def test_cotdgmore(self): ct1 = special.cotdg(45) ctrl1 = tan(pi/4.0)**(-1) assert_almost_equal(ct1,ctrl1,8) def test_specialpoints(self): assert_almost_equal(special.cotdg(45), 1.0, 14) assert_almost_equal(special.cotdg(-45), -1.0, 14) assert_almost_equal(special.cotdg(90), 0.0, 14) assert_almost_equal(special.cotdg(-90), 0.0, 14) assert_almost_equal(special.cotdg(135), -1.0, 14) assert_almost_equal(special.cotdg(-135), 1.0, 14) assert_almost_equal(special.cotdg(225), 1.0, 14) assert_almost_equal(special.cotdg(-225), -1.0, 14) assert_almost_equal(special.cotdg(270), 0.0, 14) assert_almost_equal(special.cotdg(-270), 0.0, 14) assert_almost_equal(special.cotdg(315), -1.0, 14) assert_almost_equal(special.cotdg(-315), 1.0, 14) assert_almost_equal(special.cotdg(765), 1.0, 14) def test_sinc(self): # the sinc implementation and more extensive sinc tests are in numpy assert_array_equal(special.sinc([0]), 1) assert_equal(special.sinc(0.0), 1.0) def test_sindg(self): sn = special.sindg(90) assert_equal(sn,1.0) def test_sindgmore(self): snm = special.sindg(30) snmrl = sin(pi/6.0) assert_almost_equal(snm,snmrl,8) snm1 = special.sindg(45) snmrl1 = sin(pi/4.0) assert_almost_equal(snm1,snmrl1,8) class TestTandg(object): def test_tandg(self): tn = special.tandg(30) tnrl = tan(pi/6.0) assert_almost_equal(tn,tnrl,8) def test_tandgmore(self): tnm = special.tandg(45) tnmrl = tan(pi/4.0) assert_almost_equal(tnm,tnmrl,8) tnm1 = special.tandg(60) tnmrl1 = tan(pi/3.0) assert_almost_equal(tnm1,tnmrl1,8) def test_specialpoints(self): assert_almost_equal(special.tandg(0), 0.0, 14) assert_almost_equal(special.tandg(45), 1.0, 14) assert_almost_equal(special.tandg(-45), -1.0, 14) assert_almost_equal(special.tandg(135), -1.0, 14) assert_almost_equal(special.tandg(-135), 1.0, 14) assert_almost_equal(special.tandg(180), 0.0, 14) assert_almost_equal(special.tandg(-180), 0.0, 14) assert_almost_equal(special.tandg(225), 1.0, 14) assert_almost_equal(special.tandg(-225), -1.0, 14) assert_almost_equal(special.tandg(315), -1.0, 14) assert_almost_equal(special.tandg(-315), 1.0, 14) class TestEllip(object): def test_ellipj_nan(self): """Regression test for #912.""" special.ellipj(0.5, np.nan) def test_ellipj(self): el = special.ellipj(0.2,0) rel = [sin(0.2),cos(0.2),1.0,0.20] assert_array_almost_equal(el,rel,13) def test_ellipk(self): elk = special.ellipk(.2) assert_almost_equal(elk,1.659623598610528,11) assert_equal(special.ellipkm1(0.0), np.inf) assert_equal(special.ellipkm1(1.0), pi/2) assert_equal(special.ellipkm1(np.inf), 0.0) assert_equal(special.ellipkm1(np.nan), np.nan) assert_equal(special.ellipkm1(-1), np.nan) assert_allclose(special.ellipk(-10), 0.7908718902387385) def test_ellipkinc(self): elkinc = special.ellipkinc(pi/2,.2) elk = special.ellipk(0.2) assert_almost_equal(elkinc,elk,15) alpha = 20*pi/180 phi = 45*pi/180 m = sin(alpha)**2 elkinc = special.ellipkinc(phi,m) assert_almost_equal(elkinc,0.79398143,8) # From pg. 614 of A & S assert_equal(special.ellipkinc(pi/2, 0.0), pi/2) assert_equal(special.ellipkinc(pi/2, 1.0), np.inf) assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0) assert_equal(special.ellipkinc(pi/2, np.nan), np.nan) assert_equal(special.ellipkinc(pi/2, 2), np.nan) assert_equal(special.ellipkinc(0, 0.5), 0.0) assert_equal(special.ellipkinc(np.inf, 0.5), np.inf) assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipkinc(np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.nan, 0.5), np.nan) assert_equal(special.ellipkinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14) assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946) def test_ellipkinc_2(self): # Regression test for gh-3550 # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipkinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 1.0259330100195334), 1) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipkinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 5.1296650500976675), 2) def test_ellipkinc_singular(self): # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2) xlog = np.logspace(-300, -17, 25) xlin = np.linspace(1e-17, 0.1, 25) xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False) assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)), rtol=1e14) assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)), rtol=1e14) assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)), rtol=1e14) assert_equal(special.ellipkinc(np.pi/2, 1), np.inf) assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)), rtol=1e14) assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf) def test_ellipe(self): ele = special.ellipe(.2) assert_almost_equal(ele,1.4890350580958529,8) assert_equal(special.ellipe(0.0), pi/2) assert_equal(special.ellipe(1.0), 1.0) assert_equal(special.ellipe(-np.inf), np.inf) assert_equal(special.ellipe(np.nan), np.nan) assert_equal(special.ellipe(2), np.nan) assert_allclose(special.ellipe(-10), 3.6391380384177689) def test_ellipeinc(self): eleinc = special.ellipeinc(pi/2,.2) ele = special.ellipe(0.2) assert_almost_equal(eleinc,ele,14) # pg 617 of A & S alpha, phi = 52*pi/180,35*pi/180 m = sin(alpha)**2 eleinc = special.ellipeinc(phi,m) assert_almost_equal(eleinc, 0.58823065, 8) assert_equal(special.ellipeinc(pi/2, 0.0), pi/2) assert_equal(special.ellipeinc(pi/2, 1.0), 1.0) assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf) assert_equal(special.ellipeinc(pi/2, np.nan), np.nan) assert_equal(special.ellipeinc(pi/2, 2), np.nan) assert_equal(special.ellipeinc(0, 0.5), 0.0) assert_equal(special.ellipeinc(np.inf, 0.5), np.inf) assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf) assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf) assert_equal(special.ellipeinc(np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(np.nan, 0.5), np.nan) assert_equal(special.ellipeinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876) def test_ellipeinc_2(self): # Regression test for gh-3550 # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipeinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 0.84442884574781019), 2) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipeinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 3.3471442287390509), 4) class TestErf(object): def test_erf(self): er = special.erf(.25) assert_almost_equal(er,0.2763263902,8) def test_erf_zeros(self): erz = special.erf_zeros(5) erzr = array([1.45061616+1.88094300j, 2.24465928+2.61657514j, 2.83974105+3.17562810j, 3.33546074+3.64617438j, 3.76900557+4.06069723j]) assert_array_almost_equal(erz,erzr,4) def _check_variant_func(self, func, other_func, rtol, atol=0): np.random.seed(1234) n = 10000 x = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) y = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) z = x + 1j*y old_errors = np.seterr(all='ignore') try: w = other_func(z) w_real = other_func(x).real mask = np.isfinite(w) w = w[mask] z = z[mask] mask = np.isfinite(w_real) w_real = w_real[mask] x = x[mask] # test both real and complex variants assert_func_equal(func, w, z, rtol=rtol, atol=atol) assert_func_equal(func, w_real, x, rtol=rtol, atol=atol) finally: np.seterr(**old_errors) def test_erfc_consistent(self): self._check_variant_func( cephes.erfc, lambda z: 1 - cephes.erf(z), rtol=1e-12, atol=1e-14 # <- the test function loses precision ) def test_erfcx_consistent(self): self._check_variant_func( cephes.erfcx, lambda z: np.exp(z*z) * cephes.erfc(z), rtol=1e-12 ) def test_erfi_consistent(self): self._check_variant_func( cephes.erfi, lambda z: -1j * cephes.erf(1j*z), rtol=1e-12 ) def test_dawsn_consistent(self): self._check_variant_func( cephes.dawsn, lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z), rtol=1e-12 ) def test_erf_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -1, 1] assert_allclose(special.erf(vals), expected, rtol=1e-15) def test_erfc_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, 2, 0] assert_allclose(special.erfc(vals), expected, rtol=1e-15) def test_erfcx_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, np.inf, 0] assert_allclose(special.erfcx(vals), expected, rtol=1e-15) def test_erfi_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -np.inf, np.inf] assert_allclose(special.erfi(vals), expected, rtol=1e-15) def test_dawsn_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -0.0, 0.0] assert_allclose(special.dawsn(vals), expected, rtol=1e-15) def test_wofz_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan + np.nan * 1.j, 0.-0.j, 0.+0.j] assert_allclose(special.wofz(vals), expected, rtol=1e-15) class TestEuler(object): def test_euler(self): eu0 = special.euler(0) eu1 = special.euler(1) eu2 = special.euler(2) # just checking segfaults assert_allclose(eu0, [1], rtol=1e-15) assert_allclose(eu1, [1, 0], rtol=1e-15) assert_allclose(eu2, [1, 0, -1], rtol=1e-15) eu24 = special.euler(24) mathworld = [1,1,5,61,1385,50521,2702765,199360981, 19391512145,2404879675441, 370371188237525,69348874393137901, 15514534163557086905] correct = zeros((25,),'d') for k in range(0,13): if (k % 2): correct[2*k] = -float(mathworld[k]) else: correct[2*k] = float(mathworld[k]) olderr = np.seterr(all='ignore') try: err = nan_to_num((eu24-correct)/correct) errmax = max(err) finally: np.seterr(**olderr) assert_almost_equal(errmax, 0.0, 14) class TestExp(object): def test_exp2(self): ex = special.exp2(2) exrl = 2**2 assert_equal(ex,exrl) def test_exp2more(self): exm = special.exp2(2.5) exmrl = 2**(2.5) assert_almost_equal(exm,exmrl,8) def test_exp10(self): ex = special.exp10(2) exrl = 10**2 assert_approx_equal(ex,exrl) def test_exp10more(self): exm = special.exp10(2.5) exmrl = 10**(2.5) assert_almost_equal(exm,exmrl,8) def test_expm1(self): ex = (special.expm1(2),special.expm1(3),special.expm1(4)) exrl = (exp(2)-1,exp(3)-1,exp(4)-1) assert_array_almost_equal(ex,exrl,8) def test_expm1more(self): ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2)) exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) assert_array_almost_equal(ex1,exrl1,8) class TestFactorialFunctions(object): def test_factorial(self): # Some known values, float math assert_array_almost_equal(special.factorial(0), 1) assert_array_almost_equal(special.factorial(1), 1) assert_array_almost_equal(special.factorial(2), 2) assert_array_almost_equal([6., 24., 120.], special.factorial([3, 4, 5], exact=False)) assert_array_almost_equal(special.factorial([[5, 3], [4, 3]]), [[120, 6], [24, 6]]) # Some known values, integer math assert_equal(special.factorial(0, exact=True), 1) assert_equal(special.factorial(1, exact=True), 1) assert_equal(special.factorial(2, exact=True), 2) assert_equal(special.factorial(5, exact=True), 120) assert_equal(special.factorial(15, exact=True), 1307674368000) # ndarray shape is maintained assert_equal(special.factorial([7, 4, 15, 10], exact=True), [5040, 24, 1307674368000, 3628800]) assert_equal(special.factorial([[5, 3], [4, 3]], True), [[120, 6], [24, 6]]) # object arrays assert_equal(special.factorial(np.arange(-3, 22), True), special.factorial(np.arange(-3, 22), False)) # int64 array assert_equal(special.factorial(np.arange(-3, 15), True), special.factorial(np.arange(-3, 15), False)) # int32 array assert_equal(special.factorial(np.arange(-3, 5), True), special.factorial(np.arange(-3, 5), False)) # Consistent output for n < 0 for exact in (True, False): assert_array_equal(0, special.factorial(-3, exact)) assert_array_equal([1, 2, 0, 0], special.factorial([1, 2, -5, -4], exact)) for n in range(0, 22): # Compare all with math.factorial correct = math.factorial(n) assert_array_equal(correct, special.factorial(n, True)) assert_array_equal(correct, special.factorial([n], True)[0]) assert_allclose(float(correct), special.factorial(n, False)) assert_allclose(float(correct), special.factorial([n], False)[0]) # Compare exact=True vs False, scalar vs array assert_array_equal(special.factorial(n, True), special.factorial(n, False)) assert_array_equal(special.factorial([n], True), special.factorial([n], False)) @pytest.mark.parametrize('x, exact', [ (1, True), (1, False), (np.array(1), True), (np.array(1), False), ]) def test_factorial_0d_return_type(self, x, exact): assert np.isscalar(special.factorial(x, exact=exact)) def test_factorial2(self): assert_array_almost_equal([105., 384., 945.], special.factorial2([7, 8, 9], exact=False)) assert_equal(special.factorial2(7, exact=True), 105) def test_factorialk(self): assert_equal(special.factorialk(5, 1, exact=True), 120) assert_equal(special.factorialk(5, 3, exact=True), 10) @pytest.mark.parametrize('x, exact', [ (np.nan, True), (np.nan, False), (np.array([np.nan]), True), (np.array([np.nan]), False), ]) def test_nan_inputs(self, x, exact): result = special.factorial(x, exact=exact) assert_(np.isnan(result)) def test_mixed_nan_inputs(self): x = np.array([np.nan, 1, 2, 3, np.nan]) result = special.factorial(x, exact=True) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) result = special.factorial(x, exact=False) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) class TestFresnel(object): def test_fresnel(self): frs = array(special.fresnel(.5)) assert_array_almost_equal(frs,array([0.064732432859999287, 0.49234422587144644]),8) def test_fresnel_inf1(self): frs = special.fresnel(np.inf) assert_equal(frs, (0.5, 0.5)) def test_fresnel_inf2(self): frs = special.fresnel(-np.inf) assert_equal(frs, (-0.5, -0.5)) # values from pg 329 Table 7.11 of A & S # slightly corrected in 4th decimal place def test_fresnel_zeros(self): szo, czo = special.fresnel_zeros(5) assert_array_almost_equal(szo, array([2.0093+0.2885j, 2.8335+0.2443j, 3.4675+0.2185j, 4.0026+0.2009j, 4.4742+0.1877j]),3) assert_array_almost_equal(czo, array([1.7437+0.3057j, 2.6515+0.2529j, 3.3204+0.2240j, 3.8757+0.2047j, 4.3611+0.1907j]),3) vals1 = special.fresnel(szo)[0] vals2 = special.fresnel(czo)[1] assert_array_almost_equal(vals1,0,14) assert_array_almost_equal(vals2,0,14) def test_fresnelc_zeros(self): szo, czo = special.fresnel_zeros(6) frc = special.fresnelc_zeros(6) assert_array_almost_equal(frc,czo,12) def test_fresnels_zeros(self): szo, czo = special.fresnel_zeros(5) frs = special.fresnels_zeros(5) assert_array_almost_equal(frs,szo,12) class TestGamma(object): def test_gamma(self): gam = special.gamma(5) assert_equal(gam,24.0) def test_gammaln(self): gamln = special.gammaln(3) lngam = log(special.gamma(3)) assert_almost_equal(gamln,lngam,8) def test_gammainccinv(self): gccinv = special.gammainccinv(.5,.5) gcinv = special.gammaincinv(.5,.5) assert_almost_equal(gccinv,gcinv,8) @with_special_errors def test_gammaincinv(self): y = special.gammaincinv(.4,.4) x = special.gammainc(.4,y) assert_almost_equal(x,0.4,1) y = special.gammainc(10, 0.05) x = special.gammaincinv(10, 2.5715803516000736e-20) assert_almost_equal(0.05, x, decimal=10) assert_almost_equal(y, 2.5715803516000736e-20, decimal=10) x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18) assert_almost_equal(11.0, x, decimal=10) @with_special_errors def test_975(self): # Regression test for ticket #975 -- switch point in algorithm # check that things work OK at the point, immediately next floats # around it, and a bit further away pts = [0.25, np.nextafter(0.25, 0), 0.25 - 1e-12, np.nextafter(0.25, 1), 0.25 + 1e-12] for xp in pts: y = special.gammaincinv(.4, xp) x = special.gammainc(0.4, y) assert_allclose(x, xp, rtol=1e-12) def test_rgamma(self): rgam = special.rgamma(8) rlgam = 1/special.gamma(8) assert_almost_equal(rgam,rlgam,8) def test_infinity(self): assert_(np.isinf(special.gamma(-1))) assert_equal(special.rgamma(-1), 0) class TestHankel(object): def test_negv1(self): assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14) def test_hankel1(self): hank1 = special.hankel1(1,.1) hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j) assert_almost_equal(hank1,hankrl,8) def test_negv1e(self): assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14) def test_hankel1e(self): hank1e = special.hankel1e(1,.1) hankrle = special.hankel1(1,.1)*exp(-.1j) assert_almost_equal(hank1e,hankrle,8) def test_negv2(self): assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14) def test_hankel2(self): hank2 = special.hankel2(1,.1) hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j) assert_almost_equal(hank2,hankrl2,8) def test_neg2e(self): assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14) def test_hankl2e(self): hank2e = special.hankel2e(1,.1) hankrl2e = special.hankel2e(1,.1) assert_almost_equal(hank2e,hankrl2e,8) class TestHyper(object): def test_h1vp(self): h1 = special.h1vp(1,.1) h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j) assert_almost_equal(h1,h1real,8) def test_h2vp(self): h2 = special.h2vp(1,.1) h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j) assert_almost_equal(h2,h2real,8) def test_hyp0f1(self): # scalar input assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12) assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15) # float input, expected values match mpmath x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5]) expected = np.array([0.58493659229143, 0.70566805723127, 1.0, 1.37789689539747, 1.60373685288480]) assert_allclose(x, expected, rtol=1e-12) # complex input x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j) assert_allclose(x, expected.astype(complex), rtol=1e-12) # test broadcasting x1 = [0.5, 1.5, 2.5] x2 = [0, 1, 0.5] x = special.hyp0f1(x1, x2) expected = [1.0, 1.8134302039235093, 1.21482702689997] assert_allclose(x, expected, rtol=1e-12) x = special.hyp0f1(np.row_stack([x1] * 2), x2) assert_allclose(x, np.row_stack([expected] * 2), rtol=1e-12) assert_raises(ValueError, special.hyp0f1, np.row_stack([x1] * 3), [0, 1]) def test_hyp0f1_gh5764(self): # Just checks the point that failed; there's a more systematic # test in test_mpmath res = special.hyp0f1(0.8, 0.5 + 0.5*1J) # The expected value was generated using mpmath assert_almost_equal(res, 1.6139719776441115 + 1J*0.80893054061790665) def test_hyp1f1(self): hyp1 = special.hyp1f1(.1,.1,.3) assert_almost_equal(hyp1, 1.3498588075760032,7) # test contributed by Moritz Deger (2008-05-29) # https://github.com/scipy/scipy/issues/1186 (Trac #659) # reference data obtained from mathematica [ a, b, x, m(a,b,x)]: # produced with test_hyp1f1.nb ref_data = array([[-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04], [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00], [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05], [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08], [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24], [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21], [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13], [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13], [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02], [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10], [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01], [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21], [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20], [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07], [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03], [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02], [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11], [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03], [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17], [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01], [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00], [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00], [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23], [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01], [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04], [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08], [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01], [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07], [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03], [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09], [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06], [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00], [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01], [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02], [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02], [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02], [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00], [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09], [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01], [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00], [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02], [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05], [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05], [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02], [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02], [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13], [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05], [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12], [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01], [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16], [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37], [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06], [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02], [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12], [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27], [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04], [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06], [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07], [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03], [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07], [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27], [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12], [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32], [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04], [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01], [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02], [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19], [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09], [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31], [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01], [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02], [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08], [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09], [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33], [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01], [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29], [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01], [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29], [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02], [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00], [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08], [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01], [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01], [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01], [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13], [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11], [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02], [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02], [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01], [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31], [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04], [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25], [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01], [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00], [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02], [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05], [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02], [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01], [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01], [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00]]) for a,b,c,expected in ref_data: result = special.hyp1f1(a,b,c) assert_(abs(expected - result)/expected < 1e-4) def test_hyp1f1_gh2957(self): hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933) hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934) assert_almost_equal(hyp1, hyp2, 12) def test_hyp1f1_gh2282(self): hyp = special.hyp1f1(0.5, 1.5, -1000) assert_almost_equal(hyp, 0.028024956081989643, 12) def test_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], [3, 4, 8, 1, special.gamma(8)*special.gamma(8-4-3)/special.gamma(8-3)/special.gamma(8-4)], [3, 2, 3-2+1, -1, 1./2**3*sqrt(pi) * special.gamma(1+3-2)/special.gamma(1+0.5*3-2)/special.gamma(0.5+0.5*3)], [5, 2, 5-2+1, -1, 1./2**5*sqrt(pi) * special.gamma(1+5-2)/special.gamma(1+0.5*5-2)/special.gamma(0.5+0.5*5)], [4, 0.5+4, 1.5-2*4, -1./3, (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4)/special.gamma(3./2)/special.gamma(4./3-2*4)], # and some others # ticket #424 [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484], # negative integer a or b, with c-a-b integer and x > 0.9 [-2,3,1,0.95,0.715], [2,-3,1,0.95,-0.007], [-6,3,1,0.95,0.0000810625], [2,-5,1,0.95,-0.000029375], # huge negative integers (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24), (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18), ] for i, (a, b, c, x, v) in enumerate(values): cv = special.hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_hyperu(self): val1 = special.hyperu(1,0.1,100) assert_almost_equal(val1,0.0098153,7) a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] a,b = asarray(a), asarray(b) z = 0.5 hypu = special.hyperu(a,b,z) hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) / (special.gamma(1+a-b)*special.gamma(b)) - z**(1-b)*special.hyp1f1(1+a-b,2-b,z) / (special.gamma(a)*special.gamma(2-b))) assert_array_almost_equal(hypu,hprl,12) def test_hyperu_gh2287(self): assert_almost_equal(special.hyperu(1, 1.5, 20.2), 0.048360918656699191, 12) class TestBessel(object): def test_itj0y0(self): it0 = array(special.itj0y0(.2)) assert_array_almost_equal(it0,array([0.19933433254006822, -0.34570883800412566]),8) def test_it2j0y0(self): it2 = array(special.it2j0y0(.2)) assert_array_almost_equal(it2,array([0.0049937546274601858, -0.43423067011231614]),8) def test_negv_iv(self): assert_equal(special.iv(3,2), special.iv(-3,2)) def test_j0(self): oz = special.j0(.1) ozr = special.jn(0,.1) assert_almost_equal(oz,ozr,8) def test_j1(self): o1 = special.j1(.1) o1r = special.jn(1,.1) assert_almost_equal(o1,o1r,8) def test_jn(self): jnnr = special.jn(1,.2) assert_almost_equal(jnnr,0.099500832639235995,8) def test_negv_jv(self): assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14) def test_jv(self): values = [[0, 0.1, 0.99750156206604002], [2./3, 1e-8, 0.3239028506761532e-5], [2./3, 1e-10, 0.1503423854873779e-6], [3.1, 1e-10, 0.1711956265409013e-32], [2./3, 4.0, -0.2325440850267039], ] for i, (v, x, y) in enumerate(values): yc = special.jv(v, x) assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) def test_negv_jve(self): assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14) def test_jve(self): jvexp = special.jve(1,.2) assert_almost_equal(jvexp,0.099500832639235995,8) jvexp1 = special.jve(1,.2+1j) z = .2+1j jvexpr = special.jv(1,z)*exp(-abs(z.imag)) assert_almost_equal(jvexp1,jvexpr,8) def test_jn_zeros(self): jn0 = special.jn_zeros(0,5) jn1 = special.jn_zeros(1,5) assert_array_almost_equal(jn0,array([2.4048255577, 5.5200781103, 8.6537279129, 11.7915344391, 14.9309177086]),4) assert_array_almost_equal(jn1,array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]),4) jn102 = special.jn_zeros(102,5) assert_allclose(jn102, array([110.89174935992040343, 117.83464175788308398, 123.70194191713507279, 129.02417238949092824, 134.00114761868422559]), rtol=1e-13) jn301 = special.jn_zeros(301,5) assert_allclose(jn301, array([313.59097866698830153, 323.21549776096288280, 331.22338738656748796, 338.39676338872084500, 345.03284233056064157]), rtol=1e-13) def test_jn_zeros_slow(self): jn0 = special.jn_zeros(0, 300) assert_allclose(jn0[260-1], 816.02884495068867280, rtol=1e-13) assert_allclose(jn0[280-1], 878.86068707124422606, rtol=1e-13) assert_allclose(jn0[300-1], 941.69253065317954064, rtol=1e-13) jn10 = special.jn_zeros(10, 300) assert_allclose(jn10[260-1], 831.67668514305631151, rtol=1e-13) assert_allclose(jn10[280-1], 894.51275095371316931, rtol=1e-13) assert_allclose(jn10[300-1], 957.34826370866539775, rtol=1e-13) jn3010 = special.jn_zeros(3010,5) assert_allclose(jn3010, array([3036.86590780927, 3057.06598526482, 3073.66360690272, 3088.37736494778, 3101.86438139042]), rtol=1e-8) def test_jnjnp_zeros(self): jn = special.jn def jnp(n, x): return (jn(n-1,x) - jn(n+1,x))/2 for nt in range(1, 30): z, n, m, t = special.jnjnp_zeros(nt) for zz, nn, tt in zip(z, n, t): if tt == 0: assert_allclose(jn(nn, zz), 0, atol=1e-6) elif tt == 1: assert_allclose(jnp(nn, zz), 0, atol=1e-6) else: raise AssertionError("Invalid t return for nt=%d" % nt) def test_jnp_zeros(self): jnp = special.jnp_zeros(1,5) assert_array_almost_equal(jnp, array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]),4) jnp = special.jnp_zeros(443,5) assert_allclose(special.jvp(443, jnp), 0, atol=1e-15) def test_jnyn_zeros(self): jnz = special.jnyn_zeros(1,5) assert_array_almost_equal(jnz,(array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]), array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]), array([2.19714, 5.42968, 8.59601, 11.74915, 14.89744]), array([3.68302, 6.94150, 10.12340, 13.28576, 16.44006])),5) def test_jvp(self): jvprim = special.jvp(2,2) jv0 = (special.jv(1,2)-special.jv(3,2))/2 assert_almost_equal(jvprim,jv0,10) def test_k0(self): ozk = special.k0(.1) ozkr = special.kv(0,.1) assert_almost_equal(ozk,ozkr,8) def test_k0e(self): ozke = special.k0e(.1) ozker = special.kve(0,.1) assert_almost_equal(ozke,ozker,8) def test_k1(self): o1k = special.k1(.1) o1kr = special.kv(1,.1) assert_almost_equal(o1k,o1kr,8) def test_k1e(self): o1ke = special.k1e(.1) o1ker = special.kve(1,.1) assert_almost_equal(o1ke,o1ker,8) def test_jacobi(self): a = 5*np.random.random() - 1 b = 5*np.random.random() - 1 P0 = special.jacobi(0,a,b) P1 = special.jacobi(1,a,b) P2 = special.jacobi(2,a,b) P3 = special.jacobi(3,a,b) assert_array_almost_equal(P0.c,[1],13) assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13) cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)] p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]] assert_array_almost_equal(P2.c,array(p2c)/8.0,13) cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3), 12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)] p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] assert_array_almost_equal(P3.c,array(p3c)/48.0,13) def test_kn(self): kn1 = special.kn(0,.2) assert_almost_equal(kn1,1.7527038555281462,8) def test_negv_kv(self): assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2)) def test_kv0(self): kv0 = special.kv(0,.2) assert_almost_equal(kv0, 1.7527038555281462, 10) def test_kv1(self): kv1 = special.kv(1,0.2) assert_almost_equal(kv1, 4.775972543220472, 10) def test_kv2(self): kv2 = special.kv(2,0.2) assert_almost_equal(kv2, 49.51242928773287, 10) def test_kn_largeorder(self): assert_allclose(special.kn(32, 1), 1.7516596664574289e+43) def test_kv_largearg(self): assert_equal(special.kv(0, 1e19), 0) def test_negv_kve(self): assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2)) def test_kve(self): kve1 = special.kve(0,.2) kv1 = special.kv(0,.2)*exp(.2) assert_almost_equal(kve1,kv1,8) z = .2+1j kve2 = special.kve(0,z) kv2 = special.kv(0,z)*exp(z) assert_almost_equal(kve2,kv2,8) def test_kvp_v0n1(self): z = 2.2 assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10) def test_kvp_n1(self): v = 3. z = 2.2 xc = -special.kv(v+1,z) + v/z*special.kv(v,z) x = special.kvp(v,z, n=1) assert_almost_equal(xc, x, 10) # this function (kvp) is broken def test_kvp_n2(self): v = 3. z = 2.2 xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z x = special.kvp(v, z, n=2) assert_almost_equal(xc, x, 10) def test_y0(self): oz = special.y0(.1) ozr = special.yn(0,.1) assert_almost_equal(oz,ozr,8) def test_y1(self): o1 = special.y1(.1) o1r = special.yn(1,.1) assert_almost_equal(o1,o1r,8) def test_y0_zeros(self): yo,ypo = special.y0_zeros(2) zo,zpo = special.y0_zeros(2,complex=1) all = r_[yo,zo] allval = r_[ypo,zpo] assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11) assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11) def test_y1_zeros(self): y1 = special.y1_zeros(1) assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) def test_y1p_zeros(self): y1p = special.y1p_zeros(1,complex=1) assert_array_almost_equal(y1p,(array([0.5768+0.904j]), array([-0.7635+0.5892j])),3) def test_yn_zeros(self): an = special.yn_zeros(4,2) assert_array_almost_equal(an,array([5.64515, 9.36162]),5) an = special.yn_zeros(443,5) assert_allclose(an, [450.13573091578090314, 463.05692376675001542, 472.80651546418663566, 481.27353184725625838, 488.98055964441374646], rtol=1e-15) def test_ynp_zeros(self): ao = special.ynp_zeros(0,2) assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6) ao = special.ynp_zeros(43,5) assert_allclose(special.yvp(43, ao), 0, atol=1e-15) ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-9) def test_ynp_zeros_large_order(self): ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-14) def test_yn(self): yn2n = special.yn(1,.2) assert_almost_equal(yn2n,-3.3238249881118471,8) def test_negv_yv(self): assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14) def test_yv(self): yv2 = special.yv(1,.2) assert_almost_equal(yv2,-3.3238249881118471,8) def test_negv_yve(self): assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14) def test_yve(self): yve2 = special.yve(1,.2) assert_almost_equal(yve2,-3.3238249881118471,8) yve2r = special.yv(1,.2+1j)*exp(-1) yve22 = special.yve(1,.2+1j) assert_almost_equal(yve22,yve2r,8) def test_yvp(self): yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0 yvp1 = special.yvp(2,.2) assert_array_almost_equal(yvp1,yvpr,10) def _cephes_vs_amos_points(self): """Yield points at which to compare Cephes implementation to AMOS""" # check several points, including large-amplitude ones for v in [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301]: for z in [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300, 10003]: yield v, z # check half-integers; these are problematic points at least # for cephes/iv for v in 0.5 + arange(-60, 60): yield v, 3.5 def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None): for v, z in self._cephes_vs_amos_points(): if skip is not None and skip(v, z): continue c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z) if np.isinf(c1): assert_(np.abs(c2) >= 1e300, (v, z)) elif np.isnan(c1): assert_(c2.imag != 0, (v, z)) else: assert_allclose(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol) if v == int(v): assert_allclose(c3, c2, err_msg=(v, z), rtol=rtol, atol=atol) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_jv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_yv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305) def test_yv_cephes_vs_amos_only_small_orders(self): skipper = lambda v, z: (abs(v) > 50) self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305, skip=skipper) def test_iv_cephes_vs_amos(self): olderr = np.seterr(all='ignore') try: self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305) finally: np.seterr(**olderr) @pytest.mark.slow def test_iv_cephes_vs_amos_mass_test(self): N = 1000000 np.random.seed(1) v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N) x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N) imsk = (np.random.randint(8, size=N) == 0) v[imsk] = v[imsk].astype(int) old_err = np.seterr(all='ignore') try: c1 = special.iv(v, x) c2 = special.iv(v, x+0j) # deal with differences in the inf and zero cutoffs c1[abs(c1) > 1e300] = np.inf c2[abs(c2) > 1e300] = np.inf c1[abs(c1) < 1e-300] = 0 c2[abs(c2) < 1e-300] = 0 dc = abs(c1/c2 - 1) dc[np.isnan(dc)] = 0 finally: np.seterr(**old_err) k = np.argmax(dc) # Most error apparently comes from AMOS and not our implementation; # there are some problems near integer orders there assert_(dc[k] < 2e-7, (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j))) def test_kv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305) self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305) def test_ticket_623(self): assert_allclose(special.jv(3, 4), 0.43017147387562193) assert_allclose(special.jv(301, 1300), 0.0183487151115275) assert_allclose(special.jv(301, 1296.0682), -0.0224174325312048) def test_ticket_853(self): """Negative-order Bessels""" # cephes assert_allclose(special.jv(-1, 1), -0.4400505857449335) assert_allclose(special.jv(-2, 1), 0.1149034849319005) assert_allclose(special.yv(-1, 1), 0.7812128213002887) assert_allclose(special.yv(-2, 1), -1.650682606816255) assert_allclose(special.iv(-1, 1), 0.5651591039924851) assert_allclose(special.iv(-2, 1), 0.1357476697670383) assert_allclose(special.kv(-1, 1), 0.6019072301972347) assert_allclose(special.kv(-2, 1), 1.624838898635178) assert_allclose(special.jv(-0.5, 1), 0.43109886801837607952) assert_allclose(special.yv(-0.5, 1), 0.6713967071418031) assert_allclose(special.iv(-0.5, 1), 1.231200214592967) assert_allclose(special.kv(-0.5, 1), 0.4610685044478945) # amos assert_allclose(special.jv(-1, 1+0j), -0.4400505857449335) assert_allclose(special.jv(-2, 1+0j), 0.1149034849319005) assert_allclose(special.yv(-1, 1+0j), 0.7812128213002887) assert_allclose(special.yv(-2, 1+0j), -1.650682606816255) assert_allclose(special.iv(-1, 1+0j), 0.5651591039924851) assert_allclose(special.iv(-2, 1+0j), 0.1357476697670383) assert_allclose(special.kv(-1, 1+0j), 0.6019072301972347) assert_allclose(special.kv(-2, 1+0j), 1.624838898635178) assert_allclose(special.jv(-0.5, 1+0j), 0.43109886801837607952) assert_allclose(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j) assert_allclose(special.yv(-0.5, 1+0j), 0.6713967071418031) assert_allclose(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j) assert_allclose(special.iv(-0.5, 1+0j), 1.231200214592967) assert_allclose(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j) assert_allclose(special.kv(-0.5, 1+0j), 0.4610685044478945) assert_allclose(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j) assert_allclose(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3)) assert_allclose(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j)) assert_allclose(special.hankel1(-0.5, 1+1j), special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j)) assert_allclose(special.hankel2(-0.5, 1+1j), special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j)) def test_ticket_854(self): """Real-valued Bessel domains""" assert_(isnan(special.jv(0.5, -1))) assert_(isnan(special.iv(0.5, -1))) assert_(isnan(special.yv(0.5, -1))) assert_(isnan(special.yv(1, -1))) assert_(isnan(special.kv(0.5, -1))) assert_(isnan(special.kv(1, -1))) assert_(isnan(special.jve(0.5, -1))) assert_(isnan(special.ive(0.5, -1))) assert_(isnan(special.yve(0.5, -1))) assert_(isnan(special.yve(1, -1))) assert_(isnan(special.kve(0.5, -1))) assert_(isnan(special.kve(1, -1))) assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1)) assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1)) def test_gh_7909(self): assert_(special.kv(1.5, 0) == np.inf) assert_(special.kve(1.5, 0) == np.inf) def test_ticket_503(self): """Real-valued Bessel I overflow""" assert_allclose(special.iv(1, 700), 1.528500390233901e302) assert_allclose(special.iv(1000, 1120), 1.301564549405821e301) def test_iv_hyperg_poles(self): assert_allclose(special.iv(-0.5, 1), 1.231200214592967) def iv_series(self, v, z, n=200): k = arange(0, n).astype(float_) r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1) r[isnan(r)] = inf r = exp(r) err = abs(r).max() * finfo(float_).eps * n + abs(r[-1])*10 return r.sum(), err def test_i0_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(0, z) assert_allclose(special.i0(z), value, atol=err, err_msg=z) def test_i1_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(1, z) assert_allclose(special.i1(z), value, atol=err, err_msg=z) def test_iv_series(self): for v in [-20., -10., -1., 0., 1., 12.49, 120.]: for z in [1., 10., 200.5, -1+2j]: value, err = self.iv_series(v, z) assert_allclose(special.iv(v, z), value, atol=err, err_msg=(v, z)) def test_i0(self): values = [[0.0, 1.0], [1e-10, 1.0], [0.1, 0.9071009258], [0.5, 0.6450352706], [1.0, 0.4657596077], [2.5, 0.2700464416], [5.0, 0.1835408126], [20.0, 0.0897803119], ] for i, (x, v) in enumerate(values): cv = special.i0(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i0e(self): oize = special.i0e(.1) oizer = special.ive(0,.1) assert_almost_equal(oize,oizer,8) def test_i1(self): values = [[0.0, 0.0], [1e-10, 0.4999999999500000e-10], [0.1, 0.0452984468], [0.5, 0.1564208032], [1.0, 0.2079104154], [5.0, 0.1639722669], [20.0, 0.0875062222], ] for i, (x, v) in enumerate(values): cv = special.i1(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i1e(self): oi1e = special.i1e(.1) oi1er = special.ive(1,.1) assert_almost_equal(oi1e,oi1er,8) def test_iti0k0(self): iti0 = array(special.iti0k0(5)) assert_array_almost_equal(iti0,array([31.848667776169801, 1.5673873907283657]),5) def test_it2i0k0(self): it2k = special.it2i0k0(.1) assert_array_almost_equal(it2k,array([0.0012503906973464409, 3.3309450354686687]),6) def test_iv(self): iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(iv1,0.90710092578230106,10) def test_negv_ive(self): assert_equal(special.ive(3,2), special.ive(-3,2)) def test_ive(self): ive1 = special.ive(0,.1) iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(ive1,iv1,10) def test_ivp0(self): assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10) def test_ivp(self): y = (special.iv(0,2) + special.iv(2,2))/2 x = special.ivp(1,2) assert_almost_equal(x,y,10) class TestLaguerre(object): def test_laguerre(self): lag0 = special.laguerre(0) lag1 = special.laguerre(1) lag2 = special.laguerre(2) lag3 = special.laguerre(3) lag4 = special.laguerre(4) lag5 = special.laguerre(5) assert_array_almost_equal(lag0.c,[1],13) assert_array_almost_equal(lag1.c,[-1,1],13) assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13) assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13) assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) def test_genlaguerre(self): k = 5*np.random.random() - 0.9 lag0 = special.genlaguerre(0,k) lag1 = special.genlaguerre(1,k) lag2 = special.genlaguerre(2,k) lag3 = special.genlaguerre(3,k) assert_equal(lag0.c,[1]) assert_equal(lag1.c,[-1,k+1]) assert_almost_equal(lag2.c,array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0) assert_almost_equal(lag3.c,array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0) # Base polynomials come from Abrahmowitz and Stegan class TestLegendre(object): def test_legendre(self): leg0 = special.legendre(0) leg1 = special.legendre(1) leg2 = special.legendre(2) leg3 = special.legendre(3) leg4 = special.legendre(4) leg5 = special.legendre(5) assert_equal(leg0.c, [1]) assert_equal(leg1.c, [1,0]) assert_almost_equal(leg2.c, array([3,0,-1])/2.0, decimal=13) assert_almost_equal(leg3.c, array([5,0,-3,0])/2.0) assert_almost_equal(leg4.c, array([35,0,-30,0,3])/8.0) assert_almost_equal(leg5.c, array([63,0,-70,0,15,0])/8.0) class TestLambda(object): def test_lmbda(self): lam = special.lmbda(1,.1) lamr = (array([special.jn(0,.1), 2*special.jn(1,.1)/.1]), array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])) assert_array_almost_equal(lam,lamr,8) class TestLog1p(object): def test_log1p(self): l1p = (special.log1p(10), special.log1p(11), special.log1p(12)) l1prl = (log(11), log(12), log(13)) assert_array_almost_equal(l1p,l1prl,8) def test_log1pmore(self): l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2)) l1pmrl = (log(2),log(2.1),log(2.2)) assert_array_almost_equal(l1pm,l1pmrl,8) class TestLegendreFunctions(object): def test_clpmn(self): z = 0.5+0.3j clp = special.clpmn(2, 2, z, 3) assert_array_almost_equal(clp, (array([[1.0000, z, 0.5*(3*z*z-1)], [0.0000, sqrt(z*z-1), 3*z*sqrt(z*z-1)], [0.0000, 0.0000, 3*(z*z-1)]]), array([[0.0000, 1.0000, 3*z], [0.0000, z/sqrt(z*z-1), 3*(2*z*z-1)/sqrt(z*z-1)], [0.0000, 0.0000, 6*z]])), 7) def test_clpmn_close_to_real_2(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x), special.lpmv(m, n, x)]), 7) def test_clpmn_close_to_real_3(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi), special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]), 7) def test_clpmn_across_unit_circle(self): eps = 1e-7 m = 1 n = 1 x = 1j for type in [2, 3]: assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n], special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6) def test_inf(self): for z in (1, -1): for n in range(4): for m in range(1, n): lp = special.clpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) lp = special.lpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) def test_deriv_clpmn(self): # data inside and outside of the unit circle zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j, 1+1j, -1+1j, -1-1j, 1-1j] m = 2 n = 3 for type in [2, 3]: for z in zvals: for h in [1e-3, 1e-3j]: approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0] - special.clpmn(m, n, z-0.5*h, type)[0])/h assert_allclose(special.clpmn(m, n, z, type)[1], approx_derivative, rtol=1e-4) def test_lpmn(self): lp = special.lpmn(0,2,.5) assert_array_almost_equal(lp,(array([[1.00000, 0.50000, -0.12500]]), array([[0.00000, 1.00000, 1.50000]])),4) def test_lpn(self): lpnf = special.lpn(2,.5) assert_array_almost_equal(lpnf,(array([1.00000, 0.50000, -0.12500]), array([0.00000, 1.00000, 1.50000])),4) def test_lpmv(self): lp = special.lpmv(0,2,.5) assert_almost_equal(lp,-0.125,7) lp = special.lpmv(0,40,.001) assert_almost_equal(lp,0.1252678976534484,7) # XXX: this is outside the domain of the current implementation, # so ensure it returns a NaN rather than a wrong answer. olderr = np.seterr(all='ignore') try: lp = special.lpmv(-1,-1,.001) finally: np.seterr(**olderr) assert_(lp != 0 or np.isnan(lp)) def test_lqmn(self): lqmnf = special.lqmn(0,2,.5) lqf = special.lqn(2,.5) assert_array_almost_equal(lqmnf[0][0],lqf[0],4) assert_array_almost_equal(lqmnf[1][0],lqf[1],4) def test_lqmn_gt1(self): """algorithm for real arguments changes at 1.0001 test against analytical result for m=2, n=1 """ x0 = 1.0001 delta = 0.00002 for x in (x0-delta, x0+delta): lq = special.lqmn(2, 1, x)[0][-1, -1] expected = 2/(x*x-1) assert_almost_equal(lq, expected) def test_lqmn_shape(self): a, b = special.lqmn(4, 4, 1.1) assert_equal(a.shape, (5, 5)) assert_equal(b.shape, (5, 5)) a, b = special.lqmn(4, 0, 1.1) assert_equal(a.shape, (5, 1)) assert_equal(b.shape, (5, 1)) def test_lqn(self): lqf = special.lqn(2,.5) assert_array_almost_equal(lqf,(array([0.5493, -0.7253, -0.8187]), array([1.3333, 1.216, -0.8427])),4) class TestMathieu(object): def test_mathieu_a(self): pass def test_mathieu_even_coef(self): special.mathieu_even_coef(2,5) # Q not defined broken and cannot figure out proper reporting order def test_mathieu_odd_coef(self): # same problem as above pass class TestFresnelIntegral(object): def test_modfresnelp(self): pass def test_modfresnelm(self): pass class TestOblCvSeq(object): def test_obl_cv_seq(self): obl = special.obl_cv_seq(0,3,1) assert_array_almost_equal(obl,array([-0.348602, 1.393206, 5.486800, 11.492120]),5) class TestParabolicCylinder(object): def test_pbdn_seq(self): pb = special.pbdn_seq(1,.1) assert_array_almost_equal(pb,(array([0.9975, 0.0998]), array([-0.0499, 0.9925])),4) def test_pbdv(self): special.pbdv(1,.2) 1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0] def test_pbdv_seq(self): pbn = special.pbdn_seq(1,.1) pbv = special.pbdv_seq(1,.1) assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) def test_pbdv_points(self): # simple case eta = np.linspace(-10, 10, 5) z = 2**(eta/2)*np.sqrt(np.pi)/special.gamma(.5-.5*eta) assert_allclose(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14) # some points assert_allclose(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12) assert_allclose(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12) def test_pbdv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbdv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) def test_pbvv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbvv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) class TestPolygamma(object): # from Table 6.2 (pg. 271) of A&S def test_polygamma(self): poly2 = special.polygamma(2,1) poly3 = special.polygamma(3,1) assert_almost_equal(poly2,-2.4041138063,10) assert_almost_equal(poly3,6.4939394023,10) # Test polygamma(0, x) == psi(x) x = [2, 3, 1.1e14] assert_almost_equal(special.polygamma(0, x), special.psi(x)) # Test broadcasting n = [0, 1, 2] x = [0.5, 1.5, 2.5] expected = [-1.9635100260214238, 0.93480220054467933, -0.23620405164172739] assert_almost_equal(special.polygamma(n, x), expected) expected = np.row_stack([expected]*2) assert_almost_equal(special.polygamma(n, np.row_stack([x]*2)), expected) assert_almost_equal(special.polygamma(np.row_stack([n]*2), x), expected) class TestProCvSeq(object): def test_pro_cv_seq(self): prol = special.pro_cv_seq(0,3,1) assert_array_almost_equal(prol,array([0.319000, 2.593084, 6.533471, 12.514462]),5) class TestPsi(object): def test_psi(self): ps = special.psi(1) assert_almost_equal(ps,-0.57721566490153287,8) class TestRadian(object): def test_radian(self): rad = special.radian(90,0,0) assert_almost_equal(rad,pi/2.0,5) def test_radianmore(self): rad1 = special.radian(90,1,60) assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) class TestRiccati(object): def test_riccati_jn(self): N, x = 2, 0.2 S = np.empty((N, N)) for n in range(N): j = special.spherical_jn(n, x) jp = special.spherical_jn(n, x, derivative=True) S[0,n] = x*j S[1,n] = x*jp + j assert_array_almost_equal(S, special.riccati_jn(n, x), 8) def test_riccati_yn(self): N, x = 2, 0.2 C = np.empty((N, N)) for n in range(N): y = special.spherical_yn(n, x) yp = special.spherical_yn(n, x, derivative=True) C[0,n] = x*y C[1,n] = x*yp + y assert_array_almost_equal(C, special.riccati_yn(n, x), 8) class TestRound(object): def test_round(self): rnd = list(map(int,(special.round(10.1),special.round(10.4),special.round(10.5),special.round(10.6)))) # Note: According to the documentation, scipy.special.round is # supposed to round to the nearest even number if the fractional # part is exactly 0.5. On some platforms, this does not appear # to work and thus this test may fail. However, this unit test is # correctly written. rndrl = (10,10,10,11) assert_array_equal(rnd,rndrl) def test_sph_harm(): # Tests derived from tables in # https://en.wikipedia.org/wiki/Table_of_spherical_harmonics sh = special.sph_harm pi = np.pi exp = np.exp sqrt = np.sqrt sin = np.sin cos = np.cos assert_array_almost_equal(sh(0,0,0,0), 0.5/sqrt(pi)) assert_array_almost_equal(sh(-2,2,0.,pi/4), 0.25*sqrt(15./(2.*pi)) * (sin(pi/4))**2.) assert_array_almost_equal(sh(-2,2,0.,pi/2), 0.25*sqrt(15./(2.*pi))) assert_array_almost_equal(sh(2,2,pi,pi/2), 0.25*sqrt(15/(2.*pi)) * exp(0+2.*pi*1j)*sin(pi/2.)**2.) assert_array_almost_equal(sh(2,4,pi/4.,pi/3.), (3./8.)*sqrt(5./(2.*pi)) * exp(0+2.*pi/4.*1j) * sin(pi/3.)**2. * (7.*cos(pi/3.)**2.-1)) assert_array_almost_equal(sh(4,4,pi/8.,pi/6.), (3./16.)*sqrt(35./(2.*pi)) * exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.) def test_sph_harm_ufunc_loop_selection(): # see https://github.com/scipy/scipy/issues/4895 dt = np.dtype(np.complex128) assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt) assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt) assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt) assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt) assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt) assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt) class TestStruve(object): def _series(self, v, z, n=100): """Compute Struve function & error estimate from its power series.""" k = arange(0, n) r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5) err = abs(r).max() * finfo(float_).eps * n return r.sum(), err def test_vs_series(self): """Check Struve function versus its power series""" for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]: for z in [1, 10, 19, 21, 30]: value, err = self._series(v, z) assert_allclose(special.struve(v, z), value, rtol=0, atol=err), (v, z) def test_some_values(self): assert_allclose(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7) assert_allclose(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8) assert_allclose(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12) assert_allclose(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11) assert_equal(special.struve(-12, -41), -special.struve(-12, 41)) assert_equal(special.struve(+12, -41), -special.struve(+12, 41)) assert_equal(special.struve(-11, -41), +special.struve(-11, 41)) assert_equal(special.struve(+11, -41), +special.struve(+11, 41)) assert_(isnan(special.struve(-7.1, -1))) assert_(isnan(special.struve(-10.1, -1))) def test_regression_679(self): """Regression test for #679""" assert_allclose(special.struve(-1.0, 20 - 1e-8), special.struve(-1.0, 20 + 1e-8)) assert_allclose(special.struve(-2.0, 20 - 1e-8), special.struve(-2.0, 20 + 1e-8)) assert_allclose(special.struve(-4.3, 20 - 1e-8), special.struve(-4.3, 20 + 1e-8)) def test_chi2_smalldf(): assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110) def test_ch2_inf(): assert_equal(special.chdtr(0.7,np.inf), 1.0) def test_chi2c_smalldf(): assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110) def test_chi2_inv_smalldf(): assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3) def test_agm_simple(): rtol = 1e-13 # Gauss's constant assert_allclose(1/special.agm(1, np.sqrt(2)), 0.834626841674073186, rtol=rtol) # These values were computed using Wolfram Alpha, with the # function ArithmeticGeometricMean[a, b]. agm13 = 1.863616783244897 agm15 = 2.604008190530940 agm35 = 3.936235503649555 assert_allclose(special.agm([[1], [3]], [1, 3, 5]), [[1, agm13, agm15], [agm13, 3, agm35]], rtol=rtol) # Computed by the iteration formula using mpmath, # with mpmath.mp.prec = 1000: agm12 = 1.4567910310469068 assert_allclose(special.agm(1, 2), agm12, rtol=rtol) assert_allclose(special.agm(2, 1), agm12, rtol=rtol) assert_allclose(special.agm(-1, -2), -agm12, rtol=rtol) assert_allclose(special.agm(24, 6), 13.458171481725614, rtol=rtol) assert_allclose(special.agm(13, 123456789.5), 11111458.498599306, rtol=rtol) assert_allclose(special.agm(1e30, 1), 2.229223055945383e+28, rtol=rtol) assert_allclose(special.agm(1e-22, 1), 0.030182566420169886, rtol=rtol) assert_allclose(special.agm(1e150, 1e180), 2.229223055945383e+178, rtol=rtol) assert_allclose(special.agm(1e180, 1e-150), 2.0634722510162677e+177, rtol=rtol) assert_allclose(special.agm(1e-150, 1e-170), 3.3112619670463756e-152, rtol=rtol) fi = np.finfo(1.0) assert_allclose(special.agm(fi.tiny, fi.max), 1.9892072050015473e+305, rtol=rtol) assert_allclose(special.agm(0.75*fi.max, fi.max), 1.564904312298045e+308, rtol=rtol) assert_allclose(special.agm(fi.tiny, 3*fi.tiny), 4.1466849866735005e-308, rtol=rtol) # zero, nan and inf cases. assert_equal(special.agm(0, 0), 0) assert_equal(special.agm(99, 0), 0) assert_equal(special.agm(-1, 10), np.nan) assert_equal(special.agm(0, np.inf), np.nan) assert_equal(special.agm(np.inf, 0), np.nan) assert_equal(special.agm(0, -np.inf), np.nan) assert_equal(special.agm(-np.inf, 0), np.nan) assert_equal(special.agm(np.inf, -np.inf), np.nan) assert_equal(special.agm(-np.inf, np.inf), np.nan) assert_equal(special.agm(1, np.nan), np.nan) assert_equal(special.agm(np.nan, -1), np.nan) assert_equal(special.agm(1, np.inf), np.inf) assert_equal(special.agm(np.inf, 1), np.inf) assert_equal(special.agm(-1, -np.inf), -np.inf) assert_equal(special.agm(-np.inf, -1), -np.inf) def test_legacy(): # Legacy behavior: truncating arguments to integers with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3)) assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3)) assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3)) assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3)) assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3)) assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3)) assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3)) assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3)) assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3)) @with_special_errors def test_error_raising(): assert_raises(special.SpecialFunctionError, special.iv, 1, 1e99j) def test_xlogy(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x*np.log(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float) z2 = np.r_[z1, [(0, 1j), (1, 1j)]] w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13) w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1]) assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13) def test_xlog1py(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x * np.log1p(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0), (1, 1e-30)], dtype=float) w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13) def test_entr(): def xfunc(x): if x < 0: return -np.inf else: return -special.xlogy(x, x) values = (0, 0.5, 1.0, np.inf) signs = [-1, 1] arr = [] for sgn, v in itertools.product(signs, values): arr.append(sgn * v) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z) assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13) def test_kl_div(): def xfunc(x, y): if x < 0 or y < 0 or (y == 0 and x != 0): # extension of natural domain to preserve convexity return np.inf elif np.isposinf(x) or np.isposinf(y): # limits within the natural domain return np.inf elif x == 0: return y else: return special.xlogy(x, x/y) - x + y values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13) def test_rel_entr(): def xfunc(x, y): if x > 0 and y > 0: return special.xlogy(x, x/y) elif x == 0 and y >= 0: return 0 else: return np.inf values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13) def test_huber(): assert_equal(special.huber(-1, 1.5), np.inf) assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5)) assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2)) def xfunc(delta, r): if delta < 0: return np.inf elif np.abs(r) < delta: return 0.5 * np.square(r) else: return delta * (np.abs(r) - 0.5 * delta) z = np.random.randn(10, 2) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13) def test_pseudo_huber(): def xfunc(delta, r): if delta < 0: return np.inf elif (not delta) or (not r): return 0 else: return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1) z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]]) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13)
aeklant/scipy
scipy/special/tests/test_basic.py
scipy/special/tests/test_sici.py
""" ================================================= Orthogonal distance regression (:mod:`scipy.odr`) ================================================= .. currentmodule:: scipy.odr Package Content =============== .. autosummary:: :toctree: generated/ Data -- The data to fit. RealData -- Data with weights as actual std. dev.s and/or covariances. Model -- Stores information about the function to be fit. ODR -- Gathers all info & manages the main fitting routine. Output -- Result from the fit. odr -- Low-level function for ODR. OdrWarning -- Warning about potential problems when running ODR. OdrError -- Error exception. OdrStop -- Stop exception. Prebuilt models: .. autosummary:: polynomial .. data:: exponential .. data:: multilinear .. data:: unilinear .. data:: quadratic .. data:: polynomial Usage information ================= Introduction ------------ Why Orthogonal Distance Regression (ODR)? Sometimes one has measurement errors in the explanatory (a.k.a., "independent") variable(s), not just the response (a.k.a., "dependent") variable(s). Ordinary Least Squares (OLS) fitting procedures treat the data for explanatory variables as fixed, i.e., not subject to error of any kind. Furthermore, OLS procedures require that the response variables be an explicit function of the explanatory variables; sometimes making the equation explicit is impractical and/or introduces errors. ODR can handle both of these cases with ease, and can even reduce to the OLS case if that is sufficient for the problem. ODRPACK is a FORTRAN-77 library for performing ODR with possibly non-linear fitting functions. It uses a modified trust-region Levenberg-Marquardt-type algorithm [1]_ to estimate the function parameters. The fitting functions are provided by Python functions operating on NumPy arrays. The required derivatives may be provided by Python functions as well, or may be estimated numerically. ODRPACK can do explicit or implicit ODR fits, or it can do OLS. Input and output variables may be multidimensional. Weights can be provided to account for different variances of the observations, and even covariances between dimensions of the variables. The `scipy.odr` package offers an object-oriented interface to ODRPACK, in addition to the low-level `odr` function. Additional background information about ODRPACK can be found in the `ODRPACK User's Guide <https://docs.scipy.org/doc/external/odrpack_guide.pdf>`_, reading which is recommended. Basic usage ----------- 1. Define the function you want to fit against.:: def f(B, x): '''Linear function y = m*x + b''' # B is a vector of the parameters. # x is an array of the current x values. # x is in the same format as the x passed to Data or RealData. # # Return an array in the same format as y passed to Data or RealData. return B[0]*x + B[1] 2. Create a Model.:: linear = Model(f) 3. Create a Data or RealData instance.:: mydata = Data(x, y, wd=1./power(sx,2), we=1./power(sy,2)) or, when the actual covariances are known:: mydata = RealData(x, y, sx=sx, sy=sy) 4. Instantiate ODR with your data, model and initial parameter estimate.:: myodr = ODR(mydata, linear, beta0=[1., 2.]) 5. Run the fit.:: myoutput = myodr.run() 6. Examine output.:: myoutput.pprint() References ---------- .. [1] P. T. Boggs and J. E. Rogers, "Orthogonal Distance Regression," in "Statistical analysis of measurement error models and applications: proceedings of the AMS-IMS-SIAM joint summer research conference held June 10-16, 1989," Contemporary Mathematics, vol. 112, pg. 186, 1990. """ # version: 0.7 # author: Robert Kern <robert.kern@gmail.com> # date: 2006-09-21 from .odrpack import * from .models import * __all__ = [s for s in dir() if not (s.startswith('_') or s in ('odr_stop', 'odr_error'))] from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester
# this program corresponds to special.py ### Means test is not done yet # E Means test is giving error (E) # F Means test is failing (F) # EF Means test is giving error and Failing #! Means test is segfaulting # 8 Means test runs forever ### test_besselpoly ### test_mathieu_a ### test_mathieu_even_coef ### test_mathieu_odd_coef ### test_modfresnelp ### test_modfresnelm # test_pbdv_seq ### test_pbvv_seq ### test_sph_harm import itertools import platform import numpy as np from numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp, log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, float_) import pytest from pytest import raises as assert_raises from numpy.testing import (assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_approx_equal, assert_, assert_allclose, assert_array_almost_equal_nulp, suppress_warnings) from scipy import special import scipy.special._ufuncs as cephes from scipy.special import ellipk from scipy.special._testutils import with_special_errors, \ assert_func_equal, FuncData import math class TestCephes(object): def test_airy(self): cephes.airy(0) def test_airye(self): cephes.airye(0) def test_binom(self): n = np.array([0.264, 4, 5.2, 17]) k = np.array([2, 0.4, 7, 3.3]) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389, -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846], [10.92, 2.22993515861399, -0.00585728, 10.468891352063146], [136, 3.5252179590758828, 19448, 1024.5526916174495]]) assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13) # Test branches in implementation np.random.seed(1234) n = np.r_[np.arange(-7, 30), 1000*np.random.rand(30) - 500] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_2(self): # Test branches in implementation np.random.seed(1234) n = np.r_[np.logspace(1, 300, 20)] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_exact(self): @np.vectorize def binom_int(n, k): n = int(n) k = int(k) num = int(1) den = int(1) for i in range(1, k+1): num *= i + n - k den *= i return float(num/den) np.random.seed(1234) n = np.arange(1, 15) k = np.arange(0, 15) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T nk = nk[nk[:,0] >= nk[:,1]] assert_func_equal(cephes.binom, binom_int(nk[:,0], nk[:,1]), nk, atol=0, rtol=0) def test_binom_nooverflow_8346(self): # Test (binom(n, k) doesn't overflow prematurely */ dataset = [ (1000, 500, 2.70288240945436551e+299), (1002, 501, 1.08007396880791225e+300), (1004, 502, 4.31599279169058121e+300), (1006, 503, 1.72468101616263781e+301), (1008, 504, 6.89188009236419153e+301), (1010, 505, 2.75402257948335448e+302), (1012, 506, 1.10052048531923757e+303), (1014, 507, 4.39774063758732849e+303), (1016, 508, 1.75736486108312519e+304), (1018, 509, 7.02255427788423734e+304), (1020, 510, 2.80626776829962255e+305), (1022, 511, 1.12140876377061240e+306), (1024, 512, 4.48125455209897109e+306), (1026, 513, 1.79075474304149900e+307), (1028, 514, 7.15605105487789676e+307) ] dataset = np.asarray(dataset) FuncData(cephes.binom, dataset, (0, 1), 2, rtol=1e-12).check() def test_bdtr(self): assert_equal(cephes.bdtr(1,1,0.5),1.0) def test_bdtri(self): assert_equal(cephes.bdtri(1,3,0.5),0.5) def test_bdtrc(self): assert_equal(cephes.bdtrc(1,3,0.5),0.5) def test_bdtrin(self): assert_equal(cephes.bdtrin(1,0,1),5.0) def test_bdtrik(self): cephes.bdtrik(1,3,0.5) def test_bei(self): assert_equal(cephes.bei(0),0.0) def test_beip(self): assert_equal(cephes.beip(0),0.0) def test_ber(self): assert_equal(cephes.ber(0),1.0) def test_berp(self): assert_equal(cephes.berp(0),0.0) def test_besselpoly(self): assert_equal(cephes.besselpoly(0,0,0),1.0) def test_beta(self): assert_equal(cephes.beta(1,1),1.0) assert_allclose(cephes.beta(-100.3, 1e-200), cephes.gamma(1e-200)) assert_allclose(cephes.beta(0.0342, 171), 24.070498359873497, rtol=1e-13, atol=0) def test_betainc(self): assert_equal(cephes.betainc(1,1,1),1.0) assert_allclose(cephes.betainc(0.0342, 171, 1e-10), 0.55269916901806648) def test_betaln(self): assert_equal(cephes.betaln(1,1),0.0) assert_allclose(cephes.betaln(-100.3, 1e-200), cephes.gammaln(1e-200)) assert_allclose(cephes.betaln(0.0342, 170), 3.1811881124242447, rtol=1e-14, atol=0) def test_betaincinv(self): assert_equal(cephes.betaincinv(1,1,1),1.0) assert_allclose(cephes.betaincinv(0.0342, 171, 0.25), 8.4231316935498957e-21, rtol=3e-12, atol=0) def test_beta_inf(self): assert_(np.isinf(special.beta(-1, 2))) def test_btdtr(self): assert_equal(cephes.btdtr(1,1,1),1.0) def test_btdtri(self): assert_equal(cephes.btdtri(1,1,1),1.0) def test_btdtria(self): assert_equal(cephes.btdtria(1,1,1),5.0) def test_btdtrib(self): assert_equal(cephes.btdtrib(1,1,1),5.0) def test_cbrt(self): assert_approx_equal(cephes.cbrt(1),1.0) def test_chdtr(self): assert_equal(cephes.chdtr(1,0),0.0) def test_chdtrc(self): assert_equal(cephes.chdtrc(1,0),1.0) def test_chdtri(self): assert_equal(cephes.chdtri(1,1),0.0) def test_chdtriv(self): assert_equal(cephes.chdtriv(0,0),5.0) def test_chndtr(self): assert_equal(cephes.chndtr(0,1,0),0.0) # Each row holds (x, nu, lam, expected_value) # These values were computed using Wolfram Alpha with # CDF[NoncentralChiSquareDistribution[nu, lam], x] values = np.array([ [25.00, 20.0, 400, 4.1210655112396197139e-57], [25.00, 8.00, 250, 2.3988026526832425878e-29], [0.001, 8.00, 40., 5.3761806201366039084e-24], [0.010, 8.00, 40., 5.45396231055999457039e-20], [20.00, 2.00, 107, 1.39390743555819597802e-9], [22.50, 2.00, 107, 7.11803307138105870671e-9], [25.00, 2.00, 107, 3.11041244829864897313e-8], [3.000, 2.00, 1.0, 0.62064365321954362734], [350.0, 300., 10., 0.93880128006276407710], [100.0, 13.5, 10., 0.99999999650104210949], [700.0, 20.0, 400, 0.99999999925680650105], [150.0, 13.5, 10., 0.99999999999999983046], [160.0, 13.5, 10., 0.99999999999999999518], # 1.0 ]) cdf = cephes.chndtr(values[:, 0], values[:, 1], values[:, 2]) assert_allclose(cdf, values[:, 3], rtol=1e-12) assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0) assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0) assert_(np.isnan(cephes.chndtr(np.nan, 1, 2))) assert_(np.isnan(cephes.chndtr(5, np.nan, 2))) assert_(np.isnan(cephes.chndtr(5, 1, np.nan))) def test_chndtridf(self): assert_equal(cephes.chndtridf(0,0,1),5.0) def test_chndtrinc(self): assert_equal(cephes.chndtrinc(0,1,0),5.0) def test_chndtrix(self): assert_equal(cephes.chndtrix(0,1,0),0.0) def test_cosdg(self): assert_equal(cephes.cosdg(0),1.0) def test_cosm1(self): assert_equal(cephes.cosm1(0),0.0) def test_cotdg(self): assert_almost_equal(cephes.cotdg(45),1.0) def test_dawsn(self): assert_equal(cephes.dawsn(0),0.0) assert_allclose(cephes.dawsn(1.23), 0.50053727749081767) def test_diric(self): # Test behavior near multiples of 2pi. Regression test for issue # described in gh-4001. n_odd = [1, 5, 25] x = np.array(2*np.pi + 5e-5).astype(np.float32) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7) x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) x = np.array(2*np.pi + 1e-15).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) if hasattr(np, 'float128'): # No float128 available in 32-bit numpy x = np.array(2*np.pi + 1e-12).astype(np.float128) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19) n_even = [2, 4, 24] x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15) # Test at some values not near a multiple of pi x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi) octave_result = [0.872677996249965, 0.539344662916632, 0.127322003750035, -0.206011329583298] assert_almost_equal(special.diric(x, 3), octave_result, decimal=15) def test_diric_broadcasting(self): x = np.arange(5) n = np.array([1, 3, 7]) assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size)) def test_ellipe(self): assert_equal(cephes.ellipe(1),1.0) def test_ellipeinc(self): assert_equal(cephes.ellipeinc(0,1),0.0) def test_ellipj(self): cephes.ellipj(0,1) def test_ellipk(self): assert_allclose(ellipk(0), pi/2) def test_ellipkinc(self): assert_equal(cephes.ellipkinc(0,0),0.0) def test_erf(self): assert_equal(cephes.erf(0), 0.0) def test_erf_symmetry(self): x = 5.905732037710919 assert_equal(cephes.erf(x) + cephes.erf(-x), 0.0) def test_erfc(self): assert_equal(cephes.erfc(0), 1.0) def test_exp10(self): assert_approx_equal(cephes.exp10(2),100.0) def test_exp2(self): assert_equal(cephes.exp2(2),4.0) def test_expm1(self): assert_equal(cephes.expm1(0),0.0) assert_equal(cephes.expm1(np.inf), np.inf) assert_equal(cephes.expm1(-np.inf), -1) assert_equal(cephes.expm1(np.nan), np.nan) def test_expm1_complex(self): expm1 = cephes.expm1 assert_equal(expm1(0 + 0j), 0 + 0j) assert_equal(expm1(complex(np.inf, 0)), complex(np.inf, 0)) assert_equal(expm1(complex(np.inf, 1)), complex(np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 2)), complex(-np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 4)), complex(-np.inf, -np.inf)) assert_equal(expm1(complex(np.inf, 5)), complex(np.inf, -np.inf)) assert_equal(expm1(complex(1, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(0, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.inf, np.inf)), complex(np.inf, np.nan)) assert_equal(expm1(complex(-np.inf, np.inf)), complex(-1, 0)) assert_equal(expm1(complex(-np.inf, np.nan)), complex(-1, 0)) assert_equal(expm1(complex(np.inf, np.nan)), complex(np.inf, np.nan)) assert_equal(expm1(complex(0, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(1, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, 1)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, np.nan)), complex(np.nan, np.nan)) @pytest.mark.xfail(reason='The real part of expm1(z) bad at these points') def test_expm1_complex_hard(self): # The real part of this function is difficult to evaluate when # z.real = -log(cos(z.imag)). y = np.array([0.1, 0.2, 0.3, 5, 11, 20]) x = -np.log(np.cos(y)) z = x + 1j*y # evaluate using mpmath.expm1 with dps=1000 expected = np.array([-5.5507901846769623e-17+0.10033467208545054j, 2.4289354732893695e-18+0.20271003550867248j, 4.5235500262585768e-17+0.30933624960962319j, 7.8234305217489006e-17-3.3805150062465863j, -1.3685191953697676e-16-225.95084645419513j, 8.7175620481291045e-17+2.2371609442247422j]) found = cephes.expm1(z) # this passes. assert_array_almost_equal_nulp(found.imag, expected.imag, 3) # this fails. assert_array_almost_equal_nulp(found.real, expected.real, 20) def test_fdtr(self): assert_equal(cephes.fdtr(1, 1, 0), 0.0) # Computed using Wolfram Alpha: CDF[FRatioDistribution[1e-6, 5], 10] assert_allclose(cephes.fdtr(1e-6, 5, 10), 0.9999940790193488, rtol=1e-12) def test_fdtrc(self): assert_equal(cephes.fdtrc(1, 1, 0), 1.0) # Computed using Wolfram Alpha: # 1 - CDF[FRatioDistribution[2, 1/10], 1e10] assert_allclose(cephes.fdtrc(2, 0.1, 1e10), 0.27223784621293512, rtol=1e-12) def test_fdtri(self): assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]), array([0.9937365, 1.00630298]), rtol=1e-6) # From Wolfram Alpha: # CDF[FRatioDistribution[1/10, 1], 3] = 0.8756751669632105666874... p = 0.8756751669632105666874 assert_allclose(cephes.fdtri(0.1, 1, p), 3, rtol=1e-12) @pytest.mark.xfail(reason='Returns nan on i686.') def test_fdtri_mysterious_failure(self): assert_allclose(cephes.fdtri(1, 1, 0.5), 1) def test_fdtridfd(self): assert_equal(cephes.fdtridfd(1,0,0),5.0) def test_fresnel(self): assert_equal(cephes.fresnel(0),(0.0,0.0)) def test_gamma(self): assert_equal(cephes.gamma(5),24.0) def test_gammainccinv(self): assert_equal(cephes.gammainccinv(5,1),0.0) def test_gammaln(self): cephes.gammaln(10) def test_gammasgn(self): vals = np.array([-4, -3.5, -2.3, 1, 4.2], np.float64) assert_array_equal(cephes.gammasgn(vals), np.sign(cephes.rgamma(vals))) def test_gdtr(self): assert_equal(cephes.gdtr(1,1,0),0.0) def test_gdtr_inf(self): assert_equal(cephes.gdtr(1,1,np.inf),1.0) def test_gdtrc(self): assert_equal(cephes.gdtrc(1,1,0),1.0) def test_gdtria(self): assert_equal(cephes.gdtria(0,1,1),0.0) def test_gdtrib(self): cephes.gdtrib(1,0,1) # assert_equal(cephes.gdtrib(1,0,1),5.0) def test_gdtrix(self): cephes.gdtrix(1,1,.1) def test_hankel1(self): cephes.hankel1(1,1) def test_hankel1e(self): cephes.hankel1e(1,1) def test_hankel2(self): cephes.hankel2(1,1) def test_hankel2e(self): cephes.hankel2e(1,1) def test_hyp1f1(self): assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) cephes.hyp1f1(1,1,1) def test_hyp2f1(self): assert_equal(cephes.hyp2f1(1,1,1,0),1.0) def test_i0(self): assert_equal(cephes.i0(0),1.0) def test_i0e(self): assert_equal(cephes.i0e(0),1.0) def test_i1(self): assert_equal(cephes.i1(0),0.0) def test_i1e(self): assert_equal(cephes.i1e(0),0.0) def test_it2i0k0(self): cephes.it2i0k0(1) def test_it2j0y0(self): cephes.it2j0y0(1) def test_it2struve0(self): cephes.it2struve0(1) def test_itairy(self): cephes.itairy(1) def test_iti0k0(self): assert_equal(cephes.iti0k0(0),(0.0,0.0)) def test_itj0y0(self): assert_equal(cephes.itj0y0(0),(0.0,0.0)) def test_itmodstruve0(self): assert_equal(cephes.itmodstruve0(0),0.0) def test_itstruve0(self): assert_equal(cephes.itstruve0(0),0.0) def test_iv(self): assert_equal(cephes.iv(1,0),0.0) def _check_ive(self): assert_equal(cephes.ive(1,0),0.0) def test_j0(self): assert_equal(cephes.j0(0),1.0) def test_j1(self): assert_equal(cephes.j1(0),0.0) def test_jn(self): assert_equal(cephes.jn(0,0),1.0) def test_jv(self): assert_equal(cephes.jv(0,0),1.0) def _check_jve(self): assert_equal(cephes.jve(0,0),1.0) def test_k0(self): cephes.k0(2) def test_k0e(self): cephes.k0e(2) def test_k1(self): cephes.k1(2) def test_k1e(self): cephes.k1e(2) def test_kei(self): cephes.kei(2) def test_keip(self): assert_equal(cephes.keip(0),0.0) def test_ker(self): cephes.ker(2) def test_kerp(self): cephes.kerp(2) def _check_kelvin(self): cephes.kelvin(2) def test_kn(self): cephes.kn(1,1) def test_kolmogi(self): assert_equal(cephes.kolmogi(1),0.0) assert_(np.isnan(cephes.kolmogi(np.nan))) def test_kolmogorov(self): assert_equal(cephes.kolmogorov(0), 1.0) def test_kolmogp(self): assert_equal(cephes._kolmogp(0), -0.0) def test_kolmogc(self): assert_equal(cephes._kolmogc(0), 0.0) def test_kolmogci(self): assert_equal(cephes._kolmogci(0), 0.0) assert_(np.isnan(cephes._kolmogci(np.nan))) def _check_kv(self): cephes.kv(1,1) def _check_kve(self): cephes.kve(1,1) def test_log1p(self): log1p = cephes.log1p assert_equal(log1p(0), 0.0) assert_equal(log1p(-1), -np.inf) assert_equal(log1p(-2), np.nan) assert_equal(log1p(np.inf), np.inf) def test_log1p_complex(self): log1p = cephes.log1p c = complex assert_equal(log1p(0 + 0j), 0 + 0j) assert_equal(log1p(c(-1, 0)), c(-np.inf, 0)) with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in multiply") assert_allclose(log1p(c(1, np.inf)), c(np.inf, np.pi/2)) assert_equal(log1p(c(1, np.nan)), c(np.nan, np.nan)) assert_allclose(log1p(c(-np.inf, 1)), c(np.inf, np.pi)) assert_equal(log1p(c(np.inf, 1)), c(np.inf, 0)) assert_allclose(log1p(c(-np.inf, np.inf)), c(np.inf, 3*np.pi/4)) assert_allclose(log1p(c(np.inf, np.inf)), c(np.inf, np.pi/4)) assert_equal(log1p(c(np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(-np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, np.inf)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, 1)), c(np.nan, np.nan)) assert_equal(log1p(c(np.nan, np.nan)), c(np.nan, np.nan)) def test_lpmv(self): assert_equal(cephes.lpmv(0,0,1),1.0) def test_mathieu_a(self): assert_equal(cephes.mathieu_a(1,0),1.0) def test_mathieu_b(self): assert_equal(cephes.mathieu_b(1,0),1.0) def test_mathieu_cem(self): assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) # Test AMS 20.2.27 @np.vectorize def ce_smallq(m, q, z): z *= np.pi/180 if m == 0: return 2**(-0.5) * (1 - .5*q*cos(2*z)) # + O(q^2) elif m == 1: return cos(z) - q/8 * cos(3*z) # + O(q^2) elif m == 2: return cos(2*z) - q*(cos(4*z)/12 - 1/4) # + O(q^2) else: return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(0, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0], ce_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_sem(self): assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) # Test AMS 20.2.27 @np.vectorize def se_smallq(m, q, z): z *= np.pi/180 if m == 1: return sin(z) - q/8 * sin(3*z) # + O(q^2) elif m == 2: return sin(2*z) - q*sin(4*z)/12 # + O(q^2) else: return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(1, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0], se_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_modcem1(self): assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) def test_mathieu_modcem2(self): cephes.mathieu_modcem2(1,1,1) # Test reflection relation AMS 20.6.19 m = np.arange(0, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modcem2(m, q, -z)[0] fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0] y2 = -cephes.mathieu_modcem2(m, q, z)[0] - 2*fr*cephes.mathieu_modcem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_modsem1(self): assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) def test_mathieu_modsem2(self): cephes.mathieu_modsem2(1,1,1) # Test reflection relation AMS 20.6.20 m = np.arange(1, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modsem2(m, q, -z)[0] fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1] y2 = cephes.mathieu_modsem2(m, q, z)[0] - 2*fr*cephes.mathieu_modsem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_overflow(self): # Check that these return NaNs instead of causing a SEGV assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan)) def test_mathieu_ticket_1847(self): # Regression test --- this call had some out-of-bounds access # and could return nan occasionally for k in range(60): v = cephes.mathieu_modsem2(2, 100, -1) # Values from ACM TOMS 804 (derivate by numerical differentiation) assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10) assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4) def test_modfresnelm(self): cephes.modfresnelm(0) def test_modfresnelp(self): cephes.modfresnelp(0) def _check_modstruve(self): assert_equal(cephes.modstruve(1,0),0.0) def test_nbdtr(self): assert_equal(cephes.nbdtr(1,1,1),1.0) def test_nbdtrc(self): assert_equal(cephes.nbdtrc(1,1,1),0.0) def test_nbdtri(self): assert_equal(cephes.nbdtri(1,1,1),1.0) def __check_nbdtrik(self): cephes.nbdtrik(1,.4,.5) def test_nbdtrin(self): assert_equal(cephes.nbdtrin(1,0,0),5.0) def test_ncfdtr(self): assert_equal(cephes.ncfdtr(1,1,1,0),0.0) def test_ncfdtri(self): assert_equal(cephes.ncfdtri(1, 1, 1, 0), 0.0) f = [0.5, 1, 1.5] p = cephes.ncfdtr(2, 3, 1.5, f) assert_allclose(cephes.ncfdtri(2, 3, 1.5, p), f) def test_ncfdtridfd(self): dfd = [1, 2, 3] p = cephes.ncfdtr(2, dfd, 0.25, 15) assert_allclose(cephes.ncfdtridfd(2, p, 0.25, 15), dfd) def test_ncfdtridfn(self): dfn = [0.1, 1, 2, 3, 1e4] p = cephes.ncfdtr(dfn, 2, 0.25, 15) assert_allclose(cephes.ncfdtridfn(p, 2, 0.25, 15), dfn, rtol=1e-5) def test_ncfdtrinc(self): nc = [0.5, 1.5, 2.0] p = cephes.ncfdtr(2, 3, nc, 15) assert_allclose(cephes.ncfdtrinc(2, 3, p, 15), nc) def test_nctdtr(self): assert_equal(cephes.nctdtr(1,0,0),0.5) assert_equal(cephes.nctdtr(9, 65536, 45), 0.0) assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5) assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.))) assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.) assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.))) assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.))) assert_(np.isnan(cephes.nctdtr(2., 1., np.nan))) def __check_nctdtridf(self): cephes.nctdtridf(1,0.5,0) def test_nctdtrinc(self): cephes.nctdtrinc(1,0,0) def test_nctdtrit(self): cephes.nctdtrit(.1,0.2,.5) def test_nrdtrimn(self): assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) def test_nrdtrisd(self): assert_allclose(cephes.nrdtrisd(0.5,0.5,0.5), 0.0, atol=0, rtol=0) def test_obl_ang1(self): cephes.obl_ang1(1,1,1,0) def test_obl_ang1_cv(self): result = cephes.obl_ang1_cv(1,1,1,1,0) assert_almost_equal(result[0],1.0) assert_almost_equal(result[1],0.0) def _check_obl_cv(self): assert_equal(cephes.obl_cv(1,1,0),2.0) def test_obl_rad1(self): cephes.obl_rad1(1,1,1,0) def test_obl_rad1_cv(self): cephes.obl_rad1_cv(1,1,1,1,0) def test_obl_rad2(self): cephes.obl_rad2(1,1,1,0) def test_obl_rad2_cv(self): cephes.obl_rad2_cv(1,1,1,1,0) def test_pbdv(self): assert_equal(cephes.pbdv(1,0),(0.0,1.0)) def test_pbvv(self): cephes.pbvv(1,0) def test_pbwa(self): cephes.pbwa(1,0) def test_pdtr(self): val = cephes.pdtr(0, 1) assert_almost_equal(val, np.exp(-1)) # Edge case: m = 0. val = cephes.pdtr([0, 1, 2], 0) assert_array_equal(val, [1, 1, 1]) def test_pdtrc(self): val = cephes.pdtrc(0, 1) assert_almost_equal(val, 1 - np.exp(-1)) # Edge case: m = 0. val = cephes.pdtrc([0, 1, 2], 0.0) assert_array_equal(val, [0, 0, 0]) def test_pdtri(self): with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") cephes.pdtri(0.5,0.5) def test_pdtrik(self): k = cephes.pdtrik(0.5, 1) assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5) # Edge case: m = 0 or very small. k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6]) assert_array_equal(k, np.zeros((3, 3))) def test_pro_ang1(self): cephes.pro_ang1(1,1,1,0) def test_pro_ang1_cv(self): assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), array((1.0,0.0))) def _check_pro_cv(self): assert_equal(cephes.pro_cv(1,1,0),2.0) def test_pro_rad1(self): cephes.pro_rad1(1,1,1,0.1) def test_pro_rad1_cv(self): cephes.pro_rad1_cv(1,1,1,1,0) def test_pro_rad2(self): cephes.pro_rad2(1,1,1,0) def test_pro_rad2_cv(self): cephes.pro_rad2_cv(1,1,1,1,0) def test_psi(self): cephes.psi(1) def test_radian(self): assert_equal(cephes.radian(0,0,0),0) def test_rgamma(self): assert_equal(cephes.rgamma(1),1.0) def test_round(self): assert_equal(cephes.round(3.4),3.0) assert_equal(cephes.round(-3.4),-3.0) assert_equal(cephes.round(3.6),4.0) assert_equal(cephes.round(-3.6),-4.0) assert_equal(cephes.round(3.5),4.0) assert_equal(cephes.round(-3.5),-4.0) def test_shichi(self): cephes.shichi(1) def test_sici(self): cephes.sici(1) s, c = cephes.sici(np.inf) assert_almost_equal(s, np.pi * 0.5) assert_almost_equal(c, 0) s, c = cephes.sici(-np.inf) assert_almost_equal(s, -np.pi * 0.5) assert_(np.isnan(c), "cosine integral(-inf) is not nan") def test_sindg(self): assert_equal(cephes.sindg(90),1.0) def test_smirnov(self): assert_equal(cephes.smirnov(1,.1),0.9) assert_(np.isnan(cephes.smirnov(1,np.nan))) def test_smirnovp(self): assert_equal(cephes._smirnovp(1, .1), -1) assert_equal(cephes._smirnovp(2, 0.75), -2*(0.25)**(2-1)) assert_equal(cephes._smirnovp(3, 0.75), -3*(0.25)**(3-1)) assert_(np.isnan(cephes._smirnovp(1, np.nan))) def test_smirnovc(self): assert_equal(cephes._smirnovc(1,.1),0.1) assert_(np.isnan(cephes._smirnovc(1,np.nan))) x10 = np.linspace(0, 1, 11, endpoint=True) assert_almost_equal(cephes._smirnovc(3, x10), 1-cephes.smirnov(3, x10)) x4 = np.linspace(0, 1, 5, endpoint=True) assert_almost_equal(cephes._smirnovc(4, x4), 1-cephes.smirnov(4, x4)) def test_smirnovi(self): assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) assert_(np.isnan(cephes.smirnovi(1,np.nan))) def test_smirnovci(self): assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.4)),0.4) assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.6)),0.6) assert_(np.isnan(cephes._smirnovci(1,np.nan))) def test_spence(self): assert_equal(cephes.spence(1),0.0) def test_stdtr(self): assert_equal(cephes.stdtr(1,0),0.5) assert_almost_equal(cephes.stdtr(1,1), 0.75) assert_almost_equal(cephes.stdtr(1,2), 0.852416382349) def test_stdtridf(self): cephes.stdtridf(0.7,1) def test_stdtrit(self): cephes.stdtrit(1,0.7) def test_struve(self): assert_equal(cephes.struve(0,0),0.0) def test_tandg(self): assert_equal(cephes.tandg(45),1.0) def test_tklmbda(self): assert_almost_equal(cephes.tklmbda(1,1),1.0) def test_y0(self): cephes.y0(1) def test_y1(self): cephes.y1(1) def test_yn(self): cephes.yn(1,1) def test_yv(self): cephes.yv(1,1) def _check_yve(self): cephes.yve(1,1) def test_wofz(self): z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.), complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.), complex(-0.0000000234545,1.1234), complex(-3.,5.1), complex(-53,30.1), complex(0.0,0.12345), complex(11,1), complex(-22,-2), complex(9,-28), complex(21,-33), complex(1e5,1e5), complex(1e14,1e14) ] w = [ complex(-3.78270245518980507452677445620103199303131110e-7, 0.000903861276433172057331093754199933411710053155), complex(0.1764906227004816847297495349730234591778719532788, -0.02146550539468457616788719893991501311573031095617), complex(0.2410250715772692146133539023007113781272362309451, 0.06087579663428089745895459735240964093522265589350), complex(0.30474420525691259245713884106959496013413834051768, -0.20821893820283162728743734725471561394145872072738), complex(7.317131068972378096865595229600561710140617977e34, 8.321873499714402777186848353320412813066170427e34), complex(0.0615698507236323685519612934241429530190806818395, -0.00676005783716575013073036218018565206070072304635), complex(0.3960793007699874918961319170187598400134746631, -5.593152259116644920546186222529802777409274656e-9), complex(0.08217199226739447943295069917990417630675021771804, -0.04701291087643609891018366143118110965272615832184), complex(0.00457246000350281640952328010227885008541748668738, -0.00804900791411691821818731763401840373998654987934), complex(0.8746342859608052666092782112565360755791467973338452, 0.), complex(0.00468190164965444174367477874864366058339647648741, 0.0510735563901306197993676329845149741675029197050), complex(-0.0023193175200187620902125853834909543869428763219, -0.025460054739731556004902057663500272721780776336), complex(9.11463368405637174660562096516414499772662584e304, 3.97101807145263333769664875189354358563218932e305), complex(-4.4927207857715598976165541011143706155432296e281, -2.8019591213423077494444700357168707775769028e281), complex(2.820947917809305132678577516325951485807107151e-6, 2.820947917668257736791638444590253942253354058e-6), complex(2.82094791773878143474039725787438662716372268e-15, 2.82094791773878143474039725773333923127678361e-15) ] assert_func_equal(cephes.wofz, w, z, rtol=1e-13) class TestAiry(object): def test_airy(self): # This tests the airy function to ensure 8 place accuracy in computation x = special.airy(.99) assert_array_almost_equal(x,array([0.13689066,-0.16050153,1.19815925,0.92046818]),8) x = special.airy(.41) assert_array_almost_equal(x,array([0.25238916,-.23480512,0.80686202,0.51053919]),8) x = special.airy(-.36) assert_array_almost_equal(x,array([0.44508477,-0.23186773,0.44939534,0.48105354]),8) def test_airye(self): a = special.airye(0.01) b = special.airy(0.01) b1 = [None]*4 for n in range(2): b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01)) for n in range(2,4): b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) assert_array_almost_equal(a,b1,6) def test_bi_zeros(self): bi = special.bi_zeros(2) bia = (array([-1.17371322, -3.2710930]), array([-2.29443968, -4.07315509]), array([-0.45494438, 0.39652284]), array([0.60195789, -0.76031014])) assert_array_almost_equal(bi,bia,4) bi = special.bi_zeros(5) assert_array_almost_equal(bi[0],array([-1.173713222709127, -3.271093302836352, -4.830737841662016, -6.169852128310251, -7.376762079367764]),11) assert_array_almost_equal(bi[1],array([-2.294439682614122, -4.073155089071828, -5.512395729663599, -6.781294445990305, -7.940178689168587]),10) assert_array_almost_equal(bi[2],array([-0.454944383639657, 0.396522836094465, -0.367969161486959, 0.349499116831805, -0.336026240133662]),11) assert_array_almost_equal(bi[3],array([0.601957887976239, -0.760310141492801, 0.836991012619261, -0.88947990142654, 0.929983638568022]),10) def test_ai_zeros(self): ai = special.ai_zeros(1) assert_array_almost_equal(ai,(array([-2.33810741]), array([-1.01879297]), array([0.5357]), array([0.7012])),4) def test_ai_zeros_big(self): z, zp, ai_zpx, aip_zx = special.ai_zeros(50000) ai_z, aip_z, _, _ = special.airy(z) ai_zp, aip_zp, _, _ = special.airy(zp) ai_envelope = 1/abs(z)**(1./4) aip_envelope = abs(zp)**(1./4) # Check values assert_allclose(ai_zpx, ai_zp, rtol=1e-10) assert_allclose(aip_zx, aip_z, rtol=1e-10) # Check they are zeros assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0) assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.1 assert_allclose(z[:6], [-2.3381074105, -4.0879494441, -5.5205598281, -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10) assert_allclose(zp[:6], [-1.0187929716, -3.2481975822, -4.8200992112, -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10) def test_bi_zeros_big(self): z, zp, bi_zpx, bip_zx = special.bi_zeros(50000) _, _, bi_z, bip_z = special.airy(z) _, _, bi_zp, bip_zp = special.airy(zp) bi_envelope = 1/abs(z)**(1./4) bip_envelope = abs(zp)**(1./4) # Check values assert_allclose(bi_zpx, bi_zp, rtol=1e-10) assert_allclose(bip_zx, bip_z, rtol=1e-10) # Check they are zeros assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0) assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.2 assert_allclose(z[:6], [-1.1737132227, -3.2710933028, -4.8307378417, -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10) assert_allclose(zp[:6], [-2.2944396826, -4.0731550891, -5.5123957297, -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10) class TestAssocLaguerre(object): def test_assoc_laguerre(self): a1 = special.genlaguerre(11,1) a2 = special.assoc_laguerre(.2,11,1) assert_array_almost_equal(a2,a1(.2),8) a2 = special.assoc_laguerre(1,11,1) assert_array_almost_equal(a2,a1(1),8) class TestBesselpoly(object): def test_besselpoly(self): pass class TestKelvin(object): def test_bei(self): mbei = special.bei(2) assert_almost_equal(mbei, 0.9722916273066613,5) # this may not be exact def test_beip(self): mbeip = special.beip(2) assert_almost_equal(mbeip,0.91701361338403631,5) # this may not be exact def test_ber(self): mber = special.ber(2) assert_almost_equal(mber,0.75173418271380821,5) # this may not be exact def test_berp(self): mberp = special.berp(2) assert_almost_equal(mberp,-0.49306712470943909,5) # this may not be exact def test_bei_zeros(self): # Abramowitz & Stegun, Table 9.12 bi = special.bei_zeros(5) assert_array_almost_equal(bi,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) def test_beip_zeros(self): bip = special.beip_zeros(5) assert_array_almost_equal(bip,array([3.772673304934953, 8.280987849760042, 12.742147523633703, 17.193431752512542, 21.641143941167325]),8) def test_ber_zeros(self): ber = special.ber_zeros(5) assert_array_almost_equal(ber,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) def test_berp_zeros(self): brp = special.berp_zeros(5) assert_array_almost_equal(brp,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) def test_kelvin(self): mkelv = special.kelvin(2) assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j, special.ker(2) + special.kei(2)*1j, special.berp(2) + special.beip(2)*1j, special.kerp(2) + special.keip(2)*1j),8) def test_kei(self): mkei = special.kei(2) assert_almost_equal(mkei,-0.20240006776470432,5) def test_keip(self): mkeip = special.keip(2) assert_almost_equal(mkeip,0.21980790991960536,5) def test_ker(self): mker = special.ker(2) assert_almost_equal(mker,-0.041664513991509472,5) def test_kerp(self): mkerp = special.kerp(2) assert_almost_equal(mkerp,-0.10660096588105264,5) def test_kei_zeros(self): kei = special.kei_zeros(5) assert_array_almost_equal(kei,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) def test_keip_zeros(self): keip = special.keip_zeros(5) assert_array_almost_equal(keip,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) # numbers come from 9.9 of A&S pg. 381 def test_kelvin_zeros(self): tmp = special.kelvin_zeros(5) berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp assert_array_almost_equal(berz,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) assert_array_almost_equal(beiz,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) assert_array_almost_equal(kerz,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44382]),4) assert_array_almost_equal(keiz,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) assert_array_almost_equal(berpz,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) assert_array_almost_equal(beipz,array([3.77267, # table from 1927 had 3.77320 # but this is more accurate 8.28099, 12.74215, 17.19343, 21.64114]),4) assert_array_almost_equal(kerpz,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) assert_array_almost_equal(keipz,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) def test_ker_zeros(self): ker = special.ker_zeros(5) assert_array_almost_equal(ker,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44381]),4) def test_kerp_zeros(self): kerp = special.kerp_zeros(5) assert_array_almost_equal(kerp,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) class TestBernoulli(object): def test_bernoulli(self): brn = special.bernoulli(5) assert_array_almost_equal(brn,array([1.0000, -0.5000, 0.1667, 0.0000, -0.0333, 0.0000]),4) class TestBeta(object): def test_beta(self): bet = special.beta(2,4) betg = (special.gamma(2)*special.gamma(4))/special.gamma(6) assert_almost_equal(bet,betg,8) def test_betaln(self): betln = special.betaln(2,4) bet = log(abs(special.beta(2,4))) assert_almost_equal(betln,bet,8) def test_betainc(self): btinc = special.betainc(1,1,.2) assert_almost_equal(btinc,0.2,8) def test_betaincinv(self): y = special.betaincinv(2,4,.5) comp = special.betainc(2,4,y) assert_almost_equal(comp,.5,5) class TestCombinatorics(object): def test_comb(self): assert_array_almost_equal(special.comb([10, 10], [3, 4]), [120., 210.]) assert_almost_equal(special.comb(10, 3), 120.) assert_equal(special.comb(10, 3, exact=True), 120) assert_equal(special.comb(10, 3, exact=True, repetition=True), 220) assert_allclose([special.comb(20, k, exact=True) for k in range(21)], special.comb(20, list(range(21))), atol=1e-15) ii = np.iinfo(int).max + 1 assert_equal(special.comb(ii, ii-1, exact=True), ii) expected = 100891344545564193334812497256 assert_equal(special.comb(100, 50, exact=True), expected) def test_comb_with_np_int64(self): n = 70 k = 30 np_n = np.int64(n) np_k = np.int64(k) assert_equal(special.comb(np_n, np_k, exact=True), special.comb(n, k, exact=True)) def test_comb_zeros(self): assert_equal(special.comb(2, 3, exact=True), 0) assert_equal(special.comb(-1, 3, exact=True), 0) assert_equal(special.comb(2, -1, exact=True), 0) assert_equal(special.comb(2, -1, exact=False), 0) assert_array_almost_equal(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 120.]) def test_perm(self): assert_array_almost_equal(special.perm([10, 10], [3, 4]), [720., 5040.]) assert_almost_equal(special.perm(10, 3), 720.) assert_equal(special.perm(10, 3, exact=True), 720) def test_perm_zeros(self): assert_equal(special.perm(2, 3, exact=True), 0) assert_equal(special.perm(-1, 3, exact=True), 0) assert_equal(special.perm(2, -1, exact=True), 0) assert_equal(special.perm(2, -1, exact=False), 0) assert_array_almost_equal(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 720.]) class TestTrigonometric(object): def test_cbrt(self): cb = special.cbrt(27) cbrl = 27**(1.0/3.0) assert_approx_equal(cb,cbrl) def test_cbrtmore(self): cb1 = special.cbrt(27.9) cbrl1 = 27.9**(1.0/3.0) assert_almost_equal(cb1,cbrl1,8) def test_cosdg(self): cdg = special.cosdg(90) cdgrl = cos(pi/2.0) assert_almost_equal(cdg,cdgrl,8) def test_cosdgmore(self): cdgm = special.cosdg(30) cdgmrl = cos(pi/6.0) assert_almost_equal(cdgm,cdgmrl,8) def test_cosm1(self): cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10)) csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) assert_array_almost_equal(cs,csrl,8) def test_cotdg(self): ct = special.cotdg(30) ctrl = tan(pi/6.0)**(-1) assert_almost_equal(ct,ctrl,8) def test_cotdgmore(self): ct1 = special.cotdg(45) ctrl1 = tan(pi/4.0)**(-1) assert_almost_equal(ct1,ctrl1,8) def test_specialpoints(self): assert_almost_equal(special.cotdg(45), 1.0, 14) assert_almost_equal(special.cotdg(-45), -1.0, 14) assert_almost_equal(special.cotdg(90), 0.0, 14) assert_almost_equal(special.cotdg(-90), 0.0, 14) assert_almost_equal(special.cotdg(135), -1.0, 14) assert_almost_equal(special.cotdg(-135), 1.0, 14) assert_almost_equal(special.cotdg(225), 1.0, 14) assert_almost_equal(special.cotdg(-225), -1.0, 14) assert_almost_equal(special.cotdg(270), 0.0, 14) assert_almost_equal(special.cotdg(-270), 0.0, 14) assert_almost_equal(special.cotdg(315), -1.0, 14) assert_almost_equal(special.cotdg(-315), 1.0, 14) assert_almost_equal(special.cotdg(765), 1.0, 14) def test_sinc(self): # the sinc implementation and more extensive sinc tests are in numpy assert_array_equal(special.sinc([0]), 1) assert_equal(special.sinc(0.0), 1.0) def test_sindg(self): sn = special.sindg(90) assert_equal(sn,1.0) def test_sindgmore(self): snm = special.sindg(30) snmrl = sin(pi/6.0) assert_almost_equal(snm,snmrl,8) snm1 = special.sindg(45) snmrl1 = sin(pi/4.0) assert_almost_equal(snm1,snmrl1,8) class TestTandg(object): def test_tandg(self): tn = special.tandg(30) tnrl = tan(pi/6.0) assert_almost_equal(tn,tnrl,8) def test_tandgmore(self): tnm = special.tandg(45) tnmrl = tan(pi/4.0) assert_almost_equal(tnm,tnmrl,8) tnm1 = special.tandg(60) tnmrl1 = tan(pi/3.0) assert_almost_equal(tnm1,tnmrl1,8) def test_specialpoints(self): assert_almost_equal(special.tandg(0), 0.0, 14) assert_almost_equal(special.tandg(45), 1.0, 14) assert_almost_equal(special.tandg(-45), -1.0, 14) assert_almost_equal(special.tandg(135), -1.0, 14) assert_almost_equal(special.tandg(-135), 1.0, 14) assert_almost_equal(special.tandg(180), 0.0, 14) assert_almost_equal(special.tandg(-180), 0.0, 14) assert_almost_equal(special.tandg(225), 1.0, 14) assert_almost_equal(special.tandg(-225), -1.0, 14) assert_almost_equal(special.tandg(315), -1.0, 14) assert_almost_equal(special.tandg(-315), 1.0, 14) class TestEllip(object): def test_ellipj_nan(self): """Regression test for #912.""" special.ellipj(0.5, np.nan) def test_ellipj(self): el = special.ellipj(0.2,0) rel = [sin(0.2),cos(0.2),1.0,0.20] assert_array_almost_equal(el,rel,13) def test_ellipk(self): elk = special.ellipk(.2) assert_almost_equal(elk,1.659623598610528,11) assert_equal(special.ellipkm1(0.0), np.inf) assert_equal(special.ellipkm1(1.0), pi/2) assert_equal(special.ellipkm1(np.inf), 0.0) assert_equal(special.ellipkm1(np.nan), np.nan) assert_equal(special.ellipkm1(-1), np.nan) assert_allclose(special.ellipk(-10), 0.7908718902387385) def test_ellipkinc(self): elkinc = special.ellipkinc(pi/2,.2) elk = special.ellipk(0.2) assert_almost_equal(elkinc,elk,15) alpha = 20*pi/180 phi = 45*pi/180 m = sin(alpha)**2 elkinc = special.ellipkinc(phi,m) assert_almost_equal(elkinc,0.79398143,8) # From pg. 614 of A & S assert_equal(special.ellipkinc(pi/2, 0.0), pi/2) assert_equal(special.ellipkinc(pi/2, 1.0), np.inf) assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0) assert_equal(special.ellipkinc(pi/2, np.nan), np.nan) assert_equal(special.ellipkinc(pi/2, 2), np.nan) assert_equal(special.ellipkinc(0, 0.5), 0.0) assert_equal(special.ellipkinc(np.inf, 0.5), np.inf) assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipkinc(np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.nan, 0.5), np.nan) assert_equal(special.ellipkinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14) assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946) def test_ellipkinc_2(self): # Regression test for gh-3550 # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipkinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 1.0259330100195334), 1) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipkinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 5.1296650500976675), 2) def test_ellipkinc_singular(self): # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2) xlog = np.logspace(-300, -17, 25) xlin = np.linspace(1e-17, 0.1, 25) xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False) assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)), rtol=1e14) assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)), rtol=1e14) assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)), rtol=1e14) assert_equal(special.ellipkinc(np.pi/2, 1), np.inf) assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)), rtol=1e14) assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf) def test_ellipe(self): ele = special.ellipe(.2) assert_almost_equal(ele,1.4890350580958529,8) assert_equal(special.ellipe(0.0), pi/2) assert_equal(special.ellipe(1.0), 1.0) assert_equal(special.ellipe(-np.inf), np.inf) assert_equal(special.ellipe(np.nan), np.nan) assert_equal(special.ellipe(2), np.nan) assert_allclose(special.ellipe(-10), 3.6391380384177689) def test_ellipeinc(self): eleinc = special.ellipeinc(pi/2,.2) ele = special.ellipe(0.2) assert_almost_equal(eleinc,ele,14) # pg 617 of A & S alpha, phi = 52*pi/180,35*pi/180 m = sin(alpha)**2 eleinc = special.ellipeinc(phi,m) assert_almost_equal(eleinc, 0.58823065, 8) assert_equal(special.ellipeinc(pi/2, 0.0), pi/2) assert_equal(special.ellipeinc(pi/2, 1.0), 1.0) assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf) assert_equal(special.ellipeinc(pi/2, np.nan), np.nan) assert_equal(special.ellipeinc(pi/2, 2), np.nan) assert_equal(special.ellipeinc(0, 0.5), 0.0) assert_equal(special.ellipeinc(np.inf, 0.5), np.inf) assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf) assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf) assert_equal(special.ellipeinc(np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(np.nan, 0.5), np.nan) assert_equal(special.ellipeinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876) def test_ellipeinc_2(self): # Regression test for gh-3550 # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipeinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 0.84442884574781019), 2) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipeinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 3.3471442287390509), 4) class TestErf(object): def test_erf(self): er = special.erf(.25) assert_almost_equal(er,0.2763263902,8) def test_erf_zeros(self): erz = special.erf_zeros(5) erzr = array([1.45061616+1.88094300j, 2.24465928+2.61657514j, 2.83974105+3.17562810j, 3.33546074+3.64617438j, 3.76900557+4.06069723j]) assert_array_almost_equal(erz,erzr,4) def _check_variant_func(self, func, other_func, rtol, atol=0): np.random.seed(1234) n = 10000 x = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) y = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) z = x + 1j*y old_errors = np.seterr(all='ignore') try: w = other_func(z) w_real = other_func(x).real mask = np.isfinite(w) w = w[mask] z = z[mask] mask = np.isfinite(w_real) w_real = w_real[mask] x = x[mask] # test both real and complex variants assert_func_equal(func, w, z, rtol=rtol, atol=atol) assert_func_equal(func, w_real, x, rtol=rtol, atol=atol) finally: np.seterr(**old_errors) def test_erfc_consistent(self): self._check_variant_func( cephes.erfc, lambda z: 1 - cephes.erf(z), rtol=1e-12, atol=1e-14 # <- the test function loses precision ) def test_erfcx_consistent(self): self._check_variant_func( cephes.erfcx, lambda z: np.exp(z*z) * cephes.erfc(z), rtol=1e-12 ) def test_erfi_consistent(self): self._check_variant_func( cephes.erfi, lambda z: -1j * cephes.erf(1j*z), rtol=1e-12 ) def test_dawsn_consistent(self): self._check_variant_func( cephes.dawsn, lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z), rtol=1e-12 ) def test_erf_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -1, 1] assert_allclose(special.erf(vals), expected, rtol=1e-15) def test_erfc_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, 2, 0] assert_allclose(special.erfc(vals), expected, rtol=1e-15) def test_erfcx_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, np.inf, 0] assert_allclose(special.erfcx(vals), expected, rtol=1e-15) def test_erfi_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -np.inf, np.inf] assert_allclose(special.erfi(vals), expected, rtol=1e-15) def test_dawsn_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -0.0, 0.0] assert_allclose(special.dawsn(vals), expected, rtol=1e-15) def test_wofz_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan + np.nan * 1.j, 0.-0.j, 0.+0.j] assert_allclose(special.wofz(vals), expected, rtol=1e-15) class TestEuler(object): def test_euler(self): eu0 = special.euler(0) eu1 = special.euler(1) eu2 = special.euler(2) # just checking segfaults assert_allclose(eu0, [1], rtol=1e-15) assert_allclose(eu1, [1, 0], rtol=1e-15) assert_allclose(eu2, [1, 0, -1], rtol=1e-15) eu24 = special.euler(24) mathworld = [1,1,5,61,1385,50521,2702765,199360981, 19391512145,2404879675441, 370371188237525,69348874393137901, 15514534163557086905] correct = zeros((25,),'d') for k in range(0,13): if (k % 2): correct[2*k] = -float(mathworld[k]) else: correct[2*k] = float(mathworld[k]) olderr = np.seterr(all='ignore') try: err = nan_to_num((eu24-correct)/correct) errmax = max(err) finally: np.seterr(**olderr) assert_almost_equal(errmax, 0.0, 14) class TestExp(object): def test_exp2(self): ex = special.exp2(2) exrl = 2**2 assert_equal(ex,exrl) def test_exp2more(self): exm = special.exp2(2.5) exmrl = 2**(2.5) assert_almost_equal(exm,exmrl,8) def test_exp10(self): ex = special.exp10(2) exrl = 10**2 assert_approx_equal(ex,exrl) def test_exp10more(self): exm = special.exp10(2.5) exmrl = 10**(2.5) assert_almost_equal(exm,exmrl,8) def test_expm1(self): ex = (special.expm1(2),special.expm1(3),special.expm1(4)) exrl = (exp(2)-1,exp(3)-1,exp(4)-1) assert_array_almost_equal(ex,exrl,8) def test_expm1more(self): ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2)) exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) assert_array_almost_equal(ex1,exrl1,8) class TestFactorialFunctions(object): def test_factorial(self): # Some known values, float math assert_array_almost_equal(special.factorial(0), 1) assert_array_almost_equal(special.factorial(1), 1) assert_array_almost_equal(special.factorial(2), 2) assert_array_almost_equal([6., 24., 120.], special.factorial([3, 4, 5], exact=False)) assert_array_almost_equal(special.factorial([[5, 3], [4, 3]]), [[120, 6], [24, 6]]) # Some known values, integer math assert_equal(special.factorial(0, exact=True), 1) assert_equal(special.factorial(1, exact=True), 1) assert_equal(special.factorial(2, exact=True), 2) assert_equal(special.factorial(5, exact=True), 120) assert_equal(special.factorial(15, exact=True), 1307674368000) # ndarray shape is maintained assert_equal(special.factorial([7, 4, 15, 10], exact=True), [5040, 24, 1307674368000, 3628800]) assert_equal(special.factorial([[5, 3], [4, 3]], True), [[120, 6], [24, 6]]) # object arrays assert_equal(special.factorial(np.arange(-3, 22), True), special.factorial(np.arange(-3, 22), False)) # int64 array assert_equal(special.factorial(np.arange(-3, 15), True), special.factorial(np.arange(-3, 15), False)) # int32 array assert_equal(special.factorial(np.arange(-3, 5), True), special.factorial(np.arange(-3, 5), False)) # Consistent output for n < 0 for exact in (True, False): assert_array_equal(0, special.factorial(-3, exact)) assert_array_equal([1, 2, 0, 0], special.factorial([1, 2, -5, -4], exact)) for n in range(0, 22): # Compare all with math.factorial correct = math.factorial(n) assert_array_equal(correct, special.factorial(n, True)) assert_array_equal(correct, special.factorial([n], True)[0]) assert_allclose(float(correct), special.factorial(n, False)) assert_allclose(float(correct), special.factorial([n], False)[0]) # Compare exact=True vs False, scalar vs array assert_array_equal(special.factorial(n, True), special.factorial(n, False)) assert_array_equal(special.factorial([n], True), special.factorial([n], False)) @pytest.mark.parametrize('x, exact', [ (1, True), (1, False), (np.array(1), True), (np.array(1), False), ]) def test_factorial_0d_return_type(self, x, exact): assert np.isscalar(special.factorial(x, exact=exact)) def test_factorial2(self): assert_array_almost_equal([105., 384., 945.], special.factorial2([7, 8, 9], exact=False)) assert_equal(special.factorial2(7, exact=True), 105) def test_factorialk(self): assert_equal(special.factorialk(5, 1, exact=True), 120) assert_equal(special.factorialk(5, 3, exact=True), 10) @pytest.mark.parametrize('x, exact', [ (np.nan, True), (np.nan, False), (np.array([np.nan]), True), (np.array([np.nan]), False), ]) def test_nan_inputs(self, x, exact): result = special.factorial(x, exact=exact) assert_(np.isnan(result)) def test_mixed_nan_inputs(self): x = np.array([np.nan, 1, 2, 3, np.nan]) result = special.factorial(x, exact=True) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) result = special.factorial(x, exact=False) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) class TestFresnel(object): def test_fresnel(self): frs = array(special.fresnel(.5)) assert_array_almost_equal(frs,array([0.064732432859999287, 0.49234422587144644]),8) def test_fresnel_inf1(self): frs = special.fresnel(np.inf) assert_equal(frs, (0.5, 0.5)) def test_fresnel_inf2(self): frs = special.fresnel(-np.inf) assert_equal(frs, (-0.5, -0.5)) # values from pg 329 Table 7.11 of A & S # slightly corrected in 4th decimal place def test_fresnel_zeros(self): szo, czo = special.fresnel_zeros(5) assert_array_almost_equal(szo, array([2.0093+0.2885j, 2.8335+0.2443j, 3.4675+0.2185j, 4.0026+0.2009j, 4.4742+0.1877j]),3) assert_array_almost_equal(czo, array([1.7437+0.3057j, 2.6515+0.2529j, 3.3204+0.2240j, 3.8757+0.2047j, 4.3611+0.1907j]),3) vals1 = special.fresnel(szo)[0] vals2 = special.fresnel(czo)[1] assert_array_almost_equal(vals1,0,14) assert_array_almost_equal(vals2,0,14) def test_fresnelc_zeros(self): szo, czo = special.fresnel_zeros(6) frc = special.fresnelc_zeros(6) assert_array_almost_equal(frc,czo,12) def test_fresnels_zeros(self): szo, czo = special.fresnel_zeros(5) frs = special.fresnels_zeros(5) assert_array_almost_equal(frs,szo,12) class TestGamma(object): def test_gamma(self): gam = special.gamma(5) assert_equal(gam,24.0) def test_gammaln(self): gamln = special.gammaln(3) lngam = log(special.gamma(3)) assert_almost_equal(gamln,lngam,8) def test_gammainccinv(self): gccinv = special.gammainccinv(.5,.5) gcinv = special.gammaincinv(.5,.5) assert_almost_equal(gccinv,gcinv,8) @with_special_errors def test_gammaincinv(self): y = special.gammaincinv(.4,.4) x = special.gammainc(.4,y) assert_almost_equal(x,0.4,1) y = special.gammainc(10, 0.05) x = special.gammaincinv(10, 2.5715803516000736e-20) assert_almost_equal(0.05, x, decimal=10) assert_almost_equal(y, 2.5715803516000736e-20, decimal=10) x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18) assert_almost_equal(11.0, x, decimal=10) @with_special_errors def test_975(self): # Regression test for ticket #975 -- switch point in algorithm # check that things work OK at the point, immediately next floats # around it, and a bit further away pts = [0.25, np.nextafter(0.25, 0), 0.25 - 1e-12, np.nextafter(0.25, 1), 0.25 + 1e-12] for xp in pts: y = special.gammaincinv(.4, xp) x = special.gammainc(0.4, y) assert_allclose(x, xp, rtol=1e-12) def test_rgamma(self): rgam = special.rgamma(8) rlgam = 1/special.gamma(8) assert_almost_equal(rgam,rlgam,8) def test_infinity(self): assert_(np.isinf(special.gamma(-1))) assert_equal(special.rgamma(-1), 0) class TestHankel(object): def test_negv1(self): assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14) def test_hankel1(self): hank1 = special.hankel1(1,.1) hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j) assert_almost_equal(hank1,hankrl,8) def test_negv1e(self): assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14) def test_hankel1e(self): hank1e = special.hankel1e(1,.1) hankrle = special.hankel1(1,.1)*exp(-.1j) assert_almost_equal(hank1e,hankrle,8) def test_negv2(self): assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14) def test_hankel2(self): hank2 = special.hankel2(1,.1) hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j) assert_almost_equal(hank2,hankrl2,8) def test_neg2e(self): assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14) def test_hankl2e(self): hank2e = special.hankel2e(1,.1) hankrl2e = special.hankel2e(1,.1) assert_almost_equal(hank2e,hankrl2e,8) class TestHyper(object): def test_h1vp(self): h1 = special.h1vp(1,.1) h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j) assert_almost_equal(h1,h1real,8) def test_h2vp(self): h2 = special.h2vp(1,.1) h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j) assert_almost_equal(h2,h2real,8) def test_hyp0f1(self): # scalar input assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12) assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15) # float input, expected values match mpmath x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5]) expected = np.array([0.58493659229143, 0.70566805723127, 1.0, 1.37789689539747, 1.60373685288480]) assert_allclose(x, expected, rtol=1e-12) # complex input x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j) assert_allclose(x, expected.astype(complex), rtol=1e-12) # test broadcasting x1 = [0.5, 1.5, 2.5] x2 = [0, 1, 0.5] x = special.hyp0f1(x1, x2) expected = [1.0, 1.8134302039235093, 1.21482702689997] assert_allclose(x, expected, rtol=1e-12) x = special.hyp0f1(np.row_stack([x1] * 2), x2) assert_allclose(x, np.row_stack([expected] * 2), rtol=1e-12) assert_raises(ValueError, special.hyp0f1, np.row_stack([x1] * 3), [0, 1]) def test_hyp0f1_gh5764(self): # Just checks the point that failed; there's a more systematic # test in test_mpmath res = special.hyp0f1(0.8, 0.5 + 0.5*1J) # The expected value was generated using mpmath assert_almost_equal(res, 1.6139719776441115 + 1J*0.80893054061790665) def test_hyp1f1(self): hyp1 = special.hyp1f1(.1,.1,.3) assert_almost_equal(hyp1, 1.3498588075760032,7) # test contributed by Moritz Deger (2008-05-29) # https://github.com/scipy/scipy/issues/1186 (Trac #659) # reference data obtained from mathematica [ a, b, x, m(a,b,x)]: # produced with test_hyp1f1.nb ref_data = array([[-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04], [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00], [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05], [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08], [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24], [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21], [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13], [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13], [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02], [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10], [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01], [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21], [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20], [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07], [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03], [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02], [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11], [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03], [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17], [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01], [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00], [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00], [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23], [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01], [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04], [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08], [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01], [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07], [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03], [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09], [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06], [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00], [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01], [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02], [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02], [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02], [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00], [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09], [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01], [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00], [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02], [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05], [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05], [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02], [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02], [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13], [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05], [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12], [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01], [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16], [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37], [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06], [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02], [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12], [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27], [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04], [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06], [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07], [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03], [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07], [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27], [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12], [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32], [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04], [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01], [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02], [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19], [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09], [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31], [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01], [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02], [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08], [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09], [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33], [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01], [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29], [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01], [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29], [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02], [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00], [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08], [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01], [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01], [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01], [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13], [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11], [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02], [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02], [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01], [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31], [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04], [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25], [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01], [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00], [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02], [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05], [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02], [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01], [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01], [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00]]) for a,b,c,expected in ref_data: result = special.hyp1f1(a,b,c) assert_(abs(expected - result)/expected < 1e-4) def test_hyp1f1_gh2957(self): hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933) hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934) assert_almost_equal(hyp1, hyp2, 12) def test_hyp1f1_gh2282(self): hyp = special.hyp1f1(0.5, 1.5, -1000) assert_almost_equal(hyp, 0.028024956081989643, 12) def test_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], [3, 4, 8, 1, special.gamma(8)*special.gamma(8-4-3)/special.gamma(8-3)/special.gamma(8-4)], [3, 2, 3-2+1, -1, 1./2**3*sqrt(pi) * special.gamma(1+3-2)/special.gamma(1+0.5*3-2)/special.gamma(0.5+0.5*3)], [5, 2, 5-2+1, -1, 1./2**5*sqrt(pi) * special.gamma(1+5-2)/special.gamma(1+0.5*5-2)/special.gamma(0.5+0.5*5)], [4, 0.5+4, 1.5-2*4, -1./3, (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4)/special.gamma(3./2)/special.gamma(4./3-2*4)], # and some others # ticket #424 [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484], # negative integer a or b, with c-a-b integer and x > 0.9 [-2,3,1,0.95,0.715], [2,-3,1,0.95,-0.007], [-6,3,1,0.95,0.0000810625], [2,-5,1,0.95,-0.000029375], # huge negative integers (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24), (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18), ] for i, (a, b, c, x, v) in enumerate(values): cv = special.hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_hyperu(self): val1 = special.hyperu(1,0.1,100) assert_almost_equal(val1,0.0098153,7) a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] a,b = asarray(a), asarray(b) z = 0.5 hypu = special.hyperu(a,b,z) hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) / (special.gamma(1+a-b)*special.gamma(b)) - z**(1-b)*special.hyp1f1(1+a-b,2-b,z) / (special.gamma(a)*special.gamma(2-b))) assert_array_almost_equal(hypu,hprl,12) def test_hyperu_gh2287(self): assert_almost_equal(special.hyperu(1, 1.5, 20.2), 0.048360918656699191, 12) class TestBessel(object): def test_itj0y0(self): it0 = array(special.itj0y0(.2)) assert_array_almost_equal(it0,array([0.19933433254006822, -0.34570883800412566]),8) def test_it2j0y0(self): it2 = array(special.it2j0y0(.2)) assert_array_almost_equal(it2,array([0.0049937546274601858, -0.43423067011231614]),8) def test_negv_iv(self): assert_equal(special.iv(3,2), special.iv(-3,2)) def test_j0(self): oz = special.j0(.1) ozr = special.jn(0,.1) assert_almost_equal(oz,ozr,8) def test_j1(self): o1 = special.j1(.1) o1r = special.jn(1,.1) assert_almost_equal(o1,o1r,8) def test_jn(self): jnnr = special.jn(1,.2) assert_almost_equal(jnnr,0.099500832639235995,8) def test_negv_jv(self): assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14) def test_jv(self): values = [[0, 0.1, 0.99750156206604002], [2./3, 1e-8, 0.3239028506761532e-5], [2./3, 1e-10, 0.1503423854873779e-6], [3.1, 1e-10, 0.1711956265409013e-32], [2./3, 4.0, -0.2325440850267039], ] for i, (v, x, y) in enumerate(values): yc = special.jv(v, x) assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) def test_negv_jve(self): assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14) def test_jve(self): jvexp = special.jve(1,.2) assert_almost_equal(jvexp,0.099500832639235995,8) jvexp1 = special.jve(1,.2+1j) z = .2+1j jvexpr = special.jv(1,z)*exp(-abs(z.imag)) assert_almost_equal(jvexp1,jvexpr,8) def test_jn_zeros(self): jn0 = special.jn_zeros(0,5) jn1 = special.jn_zeros(1,5) assert_array_almost_equal(jn0,array([2.4048255577, 5.5200781103, 8.6537279129, 11.7915344391, 14.9309177086]),4) assert_array_almost_equal(jn1,array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]),4) jn102 = special.jn_zeros(102,5) assert_allclose(jn102, array([110.89174935992040343, 117.83464175788308398, 123.70194191713507279, 129.02417238949092824, 134.00114761868422559]), rtol=1e-13) jn301 = special.jn_zeros(301,5) assert_allclose(jn301, array([313.59097866698830153, 323.21549776096288280, 331.22338738656748796, 338.39676338872084500, 345.03284233056064157]), rtol=1e-13) def test_jn_zeros_slow(self): jn0 = special.jn_zeros(0, 300) assert_allclose(jn0[260-1], 816.02884495068867280, rtol=1e-13) assert_allclose(jn0[280-1], 878.86068707124422606, rtol=1e-13) assert_allclose(jn0[300-1], 941.69253065317954064, rtol=1e-13) jn10 = special.jn_zeros(10, 300) assert_allclose(jn10[260-1], 831.67668514305631151, rtol=1e-13) assert_allclose(jn10[280-1], 894.51275095371316931, rtol=1e-13) assert_allclose(jn10[300-1], 957.34826370866539775, rtol=1e-13) jn3010 = special.jn_zeros(3010,5) assert_allclose(jn3010, array([3036.86590780927, 3057.06598526482, 3073.66360690272, 3088.37736494778, 3101.86438139042]), rtol=1e-8) def test_jnjnp_zeros(self): jn = special.jn def jnp(n, x): return (jn(n-1,x) - jn(n+1,x))/2 for nt in range(1, 30): z, n, m, t = special.jnjnp_zeros(nt) for zz, nn, tt in zip(z, n, t): if tt == 0: assert_allclose(jn(nn, zz), 0, atol=1e-6) elif tt == 1: assert_allclose(jnp(nn, zz), 0, atol=1e-6) else: raise AssertionError("Invalid t return for nt=%d" % nt) def test_jnp_zeros(self): jnp = special.jnp_zeros(1,5) assert_array_almost_equal(jnp, array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]),4) jnp = special.jnp_zeros(443,5) assert_allclose(special.jvp(443, jnp), 0, atol=1e-15) def test_jnyn_zeros(self): jnz = special.jnyn_zeros(1,5) assert_array_almost_equal(jnz,(array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]), array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]), array([2.19714, 5.42968, 8.59601, 11.74915, 14.89744]), array([3.68302, 6.94150, 10.12340, 13.28576, 16.44006])),5) def test_jvp(self): jvprim = special.jvp(2,2) jv0 = (special.jv(1,2)-special.jv(3,2))/2 assert_almost_equal(jvprim,jv0,10) def test_k0(self): ozk = special.k0(.1) ozkr = special.kv(0,.1) assert_almost_equal(ozk,ozkr,8) def test_k0e(self): ozke = special.k0e(.1) ozker = special.kve(0,.1) assert_almost_equal(ozke,ozker,8) def test_k1(self): o1k = special.k1(.1) o1kr = special.kv(1,.1) assert_almost_equal(o1k,o1kr,8) def test_k1e(self): o1ke = special.k1e(.1) o1ker = special.kve(1,.1) assert_almost_equal(o1ke,o1ker,8) def test_jacobi(self): a = 5*np.random.random() - 1 b = 5*np.random.random() - 1 P0 = special.jacobi(0,a,b) P1 = special.jacobi(1,a,b) P2 = special.jacobi(2,a,b) P3 = special.jacobi(3,a,b) assert_array_almost_equal(P0.c,[1],13) assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13) cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)] p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]] assert_array_almost_equal(P2.c,array(p2c)/8.0,13) cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3), 12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)] p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] assert_array_almost_equal(P3.c,array(p3c)/48.0,13) def test_kn(self): kn1 = special.kn(0,.2) assert_almost_equal(kn1,1.7527038555281462,8) def test_negv_kv(self): assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2)) def test_kv0(self): kv0 = special.kv(0,.2) assert_almost_equal(kv0, 1.7527038555281462, 10) def test_kv1(self): kv1 = special.kv(1,0.2) assert_almost_equal(kv1, 4.775972543220472, 10) def test_kv2(self): kv2 = special.kv(2,0.2) assert_almost_equal(kv2, 49.51242928773287, 10) def test_kn_largeorder(self): assert_allclose(special.kn(32, 1), 1.7516596664574289e+43) def test_kv_largearg(self): assert_equal(special.kv(0, 1e19), 0) def test_negv_kve(self): assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2)) def test_kve(self): kve1 = special.kve(0,.2) kv1 = special.kv(0,.2)*exp(.2) assert_almost_equal(kve1,kv1,8) z = .2+1j kve2 = special.kve(0,z) kv2 = special.kv(0,z)*exp(z) assert_almost_equal(kve2,kv2,8) def test_kvp_v0n1(self): z = 2.2 assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10) def test_kvp_n1(self): v = 3. z = 2.2 xc = -special.kv(v+1,z) + v/z*special.kv(v,z) x = special.kvp(v,z, n=1) assert_almost_equal(xc, x, 10) # this function (kvp) is broken def test_kvp_n2(self): v = 3. z = 2.2 xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z x = special.kvp(v, z, n=2) assert_almost_equal(xc, x, 10) def test_y0(self): oz = special.y0(.1) ozr = special.yn(0,.1) assert_almost_equal(oz,ozr,8) def test_y1(self): o1 = special.y1(.1) o1r = special.yn(1,.1) assert_almost_equal(o1,o1r,8) def test_y0_zeros(self): yo,ypo = special.y0_zeros(2) zo,zpo = special.y0_zeros(2,complex=1) all = r_[yo,zo] allval = r_[ypo,zpo] assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11) assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11) def test_y1_zeros(self): y1 = special.y1_zeros(1) assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) def test_y1p_zeros(self): y1p = special.y1p_zeros(1,complex=1) assert_array_almost_equal(y1p,(array([0.5768+0.904j]), array([-0.7635+0.5892j])),3) def test_yn_zeros(self): an = special.yn_zeros(4,2) assert_array_almost_equal(an,array([5.64515, 9.36162]),5) an = special.yn_zeros(443,5) assert_allclose(an, [450.13573091578090314, 463.05692376675001542, 472.80651546418663566, 481.27353184725625838, 488.98055964441374646], rtol=1e-15) def test_ynp_zeros(self): ao = special.ynp_zeros(0,2) assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6) ao = special.ynp_zeros(43,5) assert_allclose(special.yvp(43, ao), 0, atol=1e-15) ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-9) def test_ynp_zeros_large_order(self): ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-14) def test_yn(self): yn2n = special.yn(1,.2) assert_almost_equal(yn2n,-3.3238249881118471,8) def test_negv_yv(self): assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14) def test_yv(self): yv2 = special.yv(1,.2) assert_almost_equal(yv2,-3.3238249881118471,8) def test_negv_yve(self): assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14) def test_yve(self): yve2 = special.yve(1,.2) assert_almost_equal(yve2,-3.3238249881118471,8) yve2r = special.yv(1,.2+1j)*exp(-1) yve22 = special.yve(1,.2+1j) assert_almost_equal(yve22,yve2r,8) def test_yvp(self): yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0 yvp1 = special.yvp(2,.2) assert_array_almost_equal(yvp1,yvpr,10) def _cephes_vs_amos_points(self): """Yield points at which to compare Cephes implementation to AMOS""" # check several points, including large-amplitude ones for v in [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301]: for z in [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300, 10003]: yield v, z # check half-integers; these are problematic points at least # for cephes/iv for v in 0.5 + arange(-60, 60): yield v, 3.5 def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None): for v, z in self._cephes_vs_amos_points(): if skip is not None and skip(v, z): continue c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z) if np.isinf(c1): assert_(np.abs(c2) >= 1e300, (v, z)) elif np.isnan(c1): assert_(c2.imag != 0, (v, z)) else: assert_allclose(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol) if v == int(v): assert_allclose(c3, c2, err_msg=(v, z), rtol=rtol, atol=atol) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_jv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_yv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305) def test_yv_cephes_vs_amos_only_small_orders(self): skipper = lambda v, z: (abs(v) > 50) self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305, skip=skipper) def test_iv_cephes_vs_amos(self): olderr = np.seterr(all='ignore') try: self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305) finally: np.seterr(**olderr) @pytest.mark.slow def test_iv_cephes_vs_amos_mass_test(self): N = 1000000 np.random.seed(1) v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N) x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N) imsk = (np.random.randint(8, size=N) == 0) v[imsk] = v[imsk].astype(int) old_err = np.seterr(all='ignore') try: c1 = special.iv(v, x) c2 = special.iv(v, x+0j) # deal with differences in the inf and zero cutoffs c1[abs(c1) > 1e300] = np.inf c2[abs(c2) > 1e300] = np.inf c1[abs(c1) < 1e-300] = 0 c2[abs(c2) < 1e-300] = 0 dc = abs(c1/c2 - 1) dc[np.isnan(dc)] = 0 finally: np.seterr(**old_err) k = np.argmax(dc) # Most error apparently comes from AMOS and not our implementation; # there are some problems near integer orders there assert_(dc[k] < 2e-7, (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j))) def test_kv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305) self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305) def test_ticket_623(self): assert_allclose(special.jv(3, 4), 0.43017147387562193) assert_allclose(special.jv(301, 1300), 0.0183487151115275) assert_allclose(special.jv(301, 1296.0682), -0.0224174325312048) def test_ticket_853(self): """Negative-order Bessels""" # cephes assert_allclose(special.jv(-1, 1), -0.4400505857449335) assert_allclose(special.jv(-2, 1), 0.1149034849319005) assert_allclose(special.yv(-1, 1), 0.7812128213002887) assert_allclose(special.yv(-2, 1), -1.650682606816255) assert_allclose(special.iv(-1, 1), 0.5651591039924851) assert_allclose(special.iv(-2, 1), 0.1357476697670383) assert_allclose(special.kv(-1, 1), 0.6019072301972347) assert_allclose(special.kv(-2, 1), 1.624838898635178) assert_allclose(special.jv(-0.5, 1), 0.43109886801837607952) assert_allclose(special.yv(-0.5, 1), 0.6713967071418031) assert_allclose(special.iv(-0.5, 1), 1.231200214592967) assert_allclose(special.kv(-0.5, 1), 0.4610685044478945) # amos assert_allclose(special.jv(-1, 1+0j), -0.4400505857449335) assert_allclose(special.jv(-2, 1+0j), 0.1149034849319005) assert_allclose(special.yv(-1, 1+0j), 0.7812128213002887) assert_allclose(special.yv(-2, 1+0j), -1.650682606816255) assert_allclose(special.iv(-1, 1+0j), 0.5651591039924851) assert_allclose(special.iv(-2, 1+0j), 0.1357476697670383) assert_allclose(special.kv(-1, 1+0j), 0.6019072301972347) assert_allclose(special.kv(-2, 1+0j), 1.624838898635178) assert_allclose(special.jv(-0.5, 1+0j), 0.43109886801837607952) assert_allclose(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j) assert_allclose(special.yv(-0.5, 1+0j), 0.6713967071418031) assert_allclose(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j) assert_allclose(special.iv(-0.5, 1+0j), 1.231200214592967) assert_allclose(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j) assert_allclose(special.kv(-0.5, 1+0j), 0.4610685044478945) assert_allclose(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j) assert_allclose(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3)) assert_allclose(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j)) assert_allclose(special.hankel1(-0.5, 1+1j), special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j)) assert_allclose(special.hankel2(-0.5, 1+1j), special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j)) def test_ticket_854(self): """Real-valued Bessel domains""" assert_(isnan(special.jv(0.5, -1))) assert_(isnan(special.iv(0.5, -1))) assert_(isnan(special.yv(0.5, -1))) assert_(isnan(special.yv(1, -1))) assert_(isnan(special.kv(0.5, -1))) assert_(isnan(special.kv(1, -1))) assert_(isnan(special.jve(0.5, -1))) assert_(isnan(special.ive(0.5, -1))) assert_(isnan(special.yve(0.5, -1))) assert_(isnan(special.yve(1, -1))) assert_(isnan(special.kve(0.5, -1))) assert_(isnan(special.kve(1, -1))) assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1)) assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1)) def test_gh_7909(self): assert_(special.kv(1.5, 0) == np.inf) assert_(special.kve(1.5, 0) == np.inf) def test_ticket_503(self): """Real-valued Bessel I overflow""" assert_allclose(special.iv(1, 700), 1.528500390233901e302) assert_allclose(special.iv(1000, 1120), 1.301564549405821e301) def test_iv_hyperg_poles(self): assert_allclose(special.iv(-0.5, 1), 1.231200214592967) def iv_series(self, v, z, n=200): k = arange(0, n).astype(float_) r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1) r[isnan(r)] = inf r = exp(r) err = abs(r).max() * finfo(float_).eps * n + abs(r[-1])*10 return r.sum(), err def test_i0_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(0, z) assert_allclose(special.i0(z), value, atol=err, err_msg=z) def test_i1_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(1, z) assert_allclose(special.i1(z), value, atol=err, err_msg=z) def test_iv_series(self): for v in [-20., -10., -1., 0., 1., 12.49, 120.]: for z in [1., 10., 200.5, -1+2j]: value, err = self.iv_series(v, z) assert_allclose(special.iv(v, z), value, atol=err, err_msg=(v, z)) def test_i0(self): values = [[0.0, 1.0], [1e-10, 1.0], [0.1, 0.9071009258], [0.5, 0.6450352706], [1.0, 0.4657596077], [2.5, 0.2700464416], [5.0, 0.1835408126], [20.0, 0.0897803119], ] for i, (x, v) in enumerate(values): cv = special.i0(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i0e(self): oize = special.i0e(.1) oizer = special.ive(0,.1) assert_almost_equal(oize,oizer,8) def test_i1(self): values = [[0.0, 0.0], [1e-10, 0.4999999999500000e-10], [0.1, 0.0452984468], [0.5, 0.1564208032], [1.0, 0.2079104154], [5.0, 0.1639722669], [20.0, 0.0875062222], ] for i, (x, v) in enumerate(values): cv = special.i1(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i1e(self): oi1e = special.i1e(.1) oi1er = special.ive(1,.1) assert_almost_equal(oi1e,oi1er,8) def test_iti0k0(self): iti0 = array(special.iti0k0(5)) assert_array_almost_equal(iti0,array([31.848667776169801, 1.5673873907283657]),5) def test_it2i0k0(self): it2k = special.it2i0k0(.1) assert_array_almost_equal(it2k,array([0.0012503906973464409, 3.3309450354686687]),6) def test_iv(self): iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(iv1,0.90710092578230106,10) def test_negv_ive(self): assert_equal(special.ive(3,2), special.ive(-3,2)) def test_ive(self): ive1 = special.ive(0,.1) iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(ive1,iv1,10) def test_ivp0(self): assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10) def test_ivp(self): y = (special.iv(0,2) + special.iv(2,2))/2 x = special.ivp(1,2) assert_almost_equal(x,y,10) class TestLaguerre(object): def test_laguerre(self): lag0 = special.laguerre(0) lag1 = special.laguerre(1) lag2 = special.laguerre(2) lag3 = special.laguerre(3) lag4 = special.laguerre(4) lag5 = special.laguerre(5) assert_array_almost_equal(lag0.c,[1],13) assert_array_almost_equal(lag1.c,[-1,1],13) assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13) assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13) assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) def test_genlaguerre(self): k = 5*np.random.random() - 0.9 lag0 = special.genlaguerre(0,k) lag1 = special.genlaguerre(1,k) lag2 = special.genlaguerre(2,k) lag3 = special.genlaguerre(3,k) assert_equal(lag0.c,[1]) assert_equal(lag1.c,[-1,k+1]) assert_almost_equal(lag2.c,array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0) assert_almost_equal(lag3.c,array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0) # Base polynomials come from Abrahmowitz and Stegan class TestLegendre(object): def test_legendre(self): leg0 = special.legendre(0) leg1 = special.legendre(1) leg2 = special.legendre(2) leg3 = special.legendre(3) leg4 = special.legendre(4) leg5 = special.legendre(5) assert_equal(leg0.c, [1]) assert_equal(leg1.c, [1,0]) assert_almost_equal(leg2.c, array([3,0,-1])/2.0, decimal=13) assert_almost_equal(leg3.c, array([5,0,-3,0])/2.0) assert_almost_equal(leg4.c, array([35,0,-30,0,3])/8.0) assert_almost_equal(leg5.c, array([63,0,-70,0,15,0])/8.0) class TestLambda(object): def test_lmbda(self): lam = special.lmbda(1,.1) lamr = (array([special.jn(0,.1), 2*special.jn(1,.1)/.1]), array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])) assert_array_almost_equal(lam,lamr,8) class TestLog1p(object): def test_log1p(self): l1p = (special.log1p(10), special.log1p(11), special.log1p(12)) l1prl = (log(11), log(12), log(13)) assert_array_almost_equal(l1p,l1prl,8) def test_log1pmore(self): l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2)) l1pmrl = (log(2),log(2.1),log(2.2)) assert_array_almost_equal(l1pm,l1pmrl,8) class TestLegendreFunctions(object): def test_clpmn(self): z = 0.5+0.3j clp = special.clpmn(2, 2, z, 3) assert_array_almost_equal(clp, (array([[1.0000, z, 0.5*(3*z*z-1)], [0.0000, sqrt(z*z-1), 3*z*sqrt(z*z-1)], [0.0000, 0.0000, 3*(z*z-1)]]), array([[0.0000, 1.0000, 3*z], [0.0000, z/sqrt(z*z-1), 3*(2*z*z-1)/sqrt(z*z-1)], [0.0000, 0.0000, 6*z]])), 7) def test_clpmn_close_to_real_2(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x), special.lpmv(m, n, x)]), 7) def test_clpmn_close_to_real_3(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi), special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]), 7) def test_clpmn_across_unit_circle(self): eps = 1e-7 m = 1 n = 1 x = 1j for type in [2, 3]: assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n], special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6) def test_inf(self): for z in (1, -1): for n in range(4): for m in range(1, n): lp = special.clpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) lp = special.lpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) def test_deriv_clpmn(self): # data inside and outside of the unit circle zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j, 1+1j, -1+1j, -1-1j, 1-1j] m = 2 n = 3 for type in [2, 3]: for z in zvals: for h in [1e-3, 1e-3j]: approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0] - special.clpmn(m, n, z-0.5*h, type)[0])/h assert_allclose(special.clpmn(m, n, z, type)[1], approx_derivative, rtol=1e-4) def test_lpmn(self): lp = special.lpmn(0,2,.5) assert_array_almost_equal(lp,(array([[1.00000, 0.50000, -0.12500]]), array([[0.00000, 1.00000, 1.50000]])),4) def test_lpn(self): lpnf = special.lpn(2,.5) assert_array_almost_equal(lpnf,(array([1.00000, 0.50000, -0.12500]), array([0.00000, 1.00000, 1.50000])),4) def test_lpmv(self): lp = special.lpmv(0,2,.5) assert_almost_equal(lp,-0.125,7) lp = special.lpmv(0,40,.001) assert_almost_equal(lp,0.1252678976534484,7) # XXX: this is outside the domain of the current implementation, # so ensure it returns a NaN rather than a wrong answer. olderr = np.seterr(all='ignore') try: lp = special.lpmv(-1,-1,.001) finally: np.seterr(**olderr) assert_(lp != 0 or np.isnan(lp)) def test_lqmn(self): lqmnf = special.lqmn(0,2,.5) lqf = special.lqn(2,.5) assert_array_almost_equal(lqmnf[0][0],lqf[0],4) assert_array_almost_equal(lqmnf[1][0],lqf[1],4) def test_lqmn_gt1(self): """algorithm for real arguments changes at 1.0001 test against analytical result for m=2, n=1 """ x0 = 1.0001 delta = 0.00002 for x in (x0-delta, x0+delta): lq = special.lqmn(2, 1, x)[0][-1, -1] expected = 2/(x*x-1) assert_almost_equal(lq, expected) def test_lqmn_shape(self): a, b = special.lqmn(4, 4, 1.1) assert_equal(a.shape, (5, 5)) assert_equal(b.shape, (5, 5)) a, b = special.lqmn(4, 0, 1.1) assert_equal(a.shape, (5, 1)) assert_equal(b.shape, (5, 1)) def test_lqn(self): lqf = special.lqn(2,.5) assert_array_almost_equal(lqf,(array([0.5493, -0.7253, -0.8187]), array([1.3333, 1.216, -0.8427])),4) class TestMathieu(object): def test_mathieu_a(self): pass def test_mathieu_even_coef(self): special.mathieu_even_coef(2,5) # Q not defined broken and cannot figure out proper reporting order def test_mathieu_odd_coef(self): # same problem as above pass class TestFresnelIntegral(object): def test_modfresnelp(self): pass def test_modfresnelm(self): pass class TestOblCvSeq(object): def test_obl_cv_seq(self): obl = special.obl_cv_seq(0,3,1) assert_array_almost_equal(obl,array([-0.348602, 1.393206, 5.486800, 11.492120]),5) class TestParabolicCylinder(object): def test_pbdn_seq(self): pb = special.pbdn_seq(1,.1) assert_array_almost_equal(pb,(array([0.9975, 0.0998]), array([-0.0499, 0.9925])),4) def test_pbdv(self): special.pbdv(1,.2) 1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0] def test_pbdv_seq(self): pbn = special.pbdn_seq(1,.1) pbv = special.pbdv_seq(1,.1) assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) def test_pbdv_points(self): # simple case eta = np.linspace(-10, 10, 5) z = 2**(eta/2)*np.sqrt(np.pi)/special.gamma(.5-.5*eta) assert_allclose(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14) # some points assert_allclose(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12) assert_allclose(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12) def test_pbdv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbdv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) def test_pbvv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbvv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) class TestPolygamma(object): # from Table 6.2 (pg. 271) of A&S def test_polygamma(self): poly2 = special.polygamma(2,1) poly3 = special.polygamma(3,1) assert_almost_equal(poly2,-2.4041138063,10) assert_almost_equal(poly3,6.4939394023,10) # Test polygamma(0, x) == psi(x) x = [2, 3, 1.1e14] assert_almost_equal(special.polygamma(0, x), special.psi(x)) # Test broadcasting n = [0, 1, 2] x = [0.5, 1.5, 2.5] expected = [-1.9635100260214238, 0.93480220054467933, -0.23620405164172739] assert_almost_equal(special.polygamma(n, x), expected) expected = np.row_stack([expected]*2) assert_almost_equal(special.polygamma(n, np.row_stack([x]*2)), expected) assert_almost_equal(special.polygamma(np.row_stack([n]*2), x), expected) class TestProCvSeq(object): def test_pro_cv_seq(self): prol = special.pro_cv_seq(0,3,1) assert_array_almost_equal(prol,array([0.319000, 2.593084, 6.533471, 12.514462]),5) class TestPsi(object): def test_psi(self): ps = special.psi(1) assert_almost_equal(ps,-0.57721566490153287,8) class TestRadian(object): def test_radian(self): rad = special.radian(90,0,0) assert_almost_equal(rad,pi/2.0,5) def test_radianmore(self): rad1 = special.radian(90,1,60) assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) class TestRiccati(object): def test_riccati_jn(self): N, x = 2, 0.2 S = np.empty((N, N)) for n in range(N): j = special.spherical_jn(n, x) jp = special.spherical_jn(n, x, derivative=True) S[0,n] = x*j S[1,n] = x*jp + j assert_array_almost_equal(S, special.riccati_jn(n, x), 8) def test_riccati_yn(self): N, x = 2, 0.2 C = np.empty((N, N)) for n in range(N): y = special.spherical_yn(n, x) yp = special.spherical_yn(n, x, derivative=True) C[0,n] = x*y C[1,n] = x*yp + y assert_array_almost_equal(C, special.riccati_yn(n, x), 8) class TestRound(object): def test_round(self): rnd = list(map(int,(special.round(10.1),special.round(10.4),special.round(10.5),special.round(10.6)))) # Note: According to the documentation, scipy.special.round is # supposed to round to the nearest even number if the fractional # part is exactly 0.5. On some platforms, this does not appear # to work and thus this test may fail. However, this unit test is # correctly written. rndrl = (10,10,10,11) assert_array_equal(rnd,rndrl) def test_sph_harm(): # Tests derived from tables in # https://en.wikipedia.org/wiki/Table_of_spherical_harmonics sh = special.sph_harm pi = np.pi exp = np.exp sqrt = np.sqrt sin = np.sin cos = np.cos assert_array_almost_equal(sh(0,0,0,0), 0.5/sqrt(pi)) assert_array_almost_equal(sh(-2,2,0.,pi/4), 0.25*sqrt(15./(2.*pi)) * (sin(pi/4))**2.) assert_array_almost_equal(sh(-2,2,0.,pi/2), 0.25*sqrt(15./(2.*pi))) assert_array_almost_equal(sh(2,2,pi,pi/2), 0.25*sqrt(15/(2.*pi)) * exp(0+2.*pi*1j)*sin(pi/2.)**2.) assert_array_almost_equal(sh(2,4,pi/4.,pi/3.), (3./8.)*sqrt(5./(2.*pi)) * exp(0+2.*pi/4.*1j) * sin(pi/3.)**2. * (7.*cos(pi/3.)**2.-1)) assert_array_almost_equal(sh(4,4,pi/8.,pi/6.), (3./16.)*sqrt(35./(2.*pi)) * exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.) def test_sph_harm_ufunc_loop_selection(): # see https://github.com/scipy/scipy/issues/4895 dt = np.dtype(np.complex128) assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt) assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt) assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt) assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt) assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt) assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt) class TestStruve(object): def _series(self, v, z, n=100): """Compute Struve function & error estimate from its power series.""" k = arange(0, n) r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5) err = abs(r).max() * finfo(float_).eps * n return r.sum(), err def test_vs_series(self): """Check Struve function versus its power series""" for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]: for z in [1, 10, 19, 21, 30]: value, err = self._series(v, z) assert_allclose(special.struve(v, z), value, rtol=0, atol=err), (v, z) def test_some_values(self): assert_allclose(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7) assert_allclose(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8) assert_allclose(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12) assert_allclose(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11) assert_equal(special.struve(-12, -41), -special.struve(-12, 41)) assert_equal(special.struve(+12, -41), -special.struve(+12, 41)) assert_equal(special.struve(-11, -41), +special.struve(-11, 41)) assert_equal(special.struve(+11, -41), +special.struve(+11, 41)) assert_(isnan(special.struve(-7.1, -1))) assert_(isnan(special.struve(-10.1, -1))) def test_regression_679(self): """Regression test for #679""" assert_allclose(special.struve(-1.0, 20 - 1e-8), special.struve(-1.0, 20 + 1e-8)) assert_allclose(special.struve(-2.0, 20 - 1e-8), special.struve(-2.0, 20 + 1e-8)) assert_allclose(special.struve(-4.3, 20 - 1e-8), special.struve(-4.3, 20 + 1e-8)) def test_chi2_smalldf(): assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110) def test_ch2_inf(): assert_equal(special.chdtr(0.7,np.inf), 1.0) def test_chi2c_smalldf(): assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110) def test_chi2_inv_smalldf(): assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3) def test_agm_simple(): rtol = 1e-13 # Gauss's constant assert_allclose(1/special.agm(1, np.sqrt(2)), 0.834626841674073186, rtol=rtol) # These values were computed using Wolfram Alpha, with the # function ArithmeticGeometricMean[a, b]. agm13 = 1.863616783244897 agm15 = 2.604008190530940 agm35 = 3.936235503649555 assert_allclose(special.agm([[1], [3]], [1, 3, 5]), [[1, agm13, agm15], [agm13, 3, agm35]], rtol=rtol) # Computed by the iteration formula using mpmath, # with mpmath.mp.prec = 1000: agm12 = 1.4567910310469068 assert_allclose(special.agm(1, 2), agm12, rtol=rtol) assert_allclose(special.agm(2, 1), agm12, rtol=rtol) assert_allclose(special.agm(-1, -2), -agm12, rtol=rtol) assert_allclose(special.agm(24, 6), 13.458171481725614, rtol=rtol) assert_allclose(special.agm(13, 123456789.5), 11111458.498599306, rtol=rtol) assert_allclose(special.agm(1e30, 1), 2.229223055945383e+28, rtol=rtol) assert_allclose(special.agm(1e-22, 1), 0.030182566420169886, rtol=rtol) assert_allclose(special.agm(1e150, 1e180), 2.229223055945383e+178, rtol=rtol) assert_allclose(special.agm(1e180, 1e-150), 2.0634722510162677e+177, rtol=rtol) assert_allclose(special.agm(1e-150, 1e-170), 3.3112619670463756e-152, rtol=rtol) fi = np.finfo(1.0) assert_allclose(special.agm(fi.tiny, fi.max), 1.9892072050015473e+305, rtol=rtol) assert_allclose(special.agm(0.75*fi.max, fi.max), 1.564904312298045e+308, rtol=rtol) assert_allclose(special.agm(fi.tiny, 3*fi.tiny), 4.1466849866735005e-308, rtol=rtol) # zero, nan and inf cases. assert_equal(special.agm(0, 0), 0) assert_equal(special.agm(99, 0), 0) assert_equal(special.agm(-1, 10), np.nan) assert_equal(special.agm(0, np.inf), np.nan) assert_equal(special.agm(np.inf, 0), np.nan) assert_equal(special.agm(0, -np.inf), np.nan) assert_equal(special.agm(-np.inf, 0), np.nan) assert_equal(special.agm(np.inf, -np.inf), np.nan) assert_equal(special.agm(-np.inf, np.inf), np.nan) assert_equal(special.agm(1, np.nan), np.nan) assert_equal(special.agm(np.nan, -1), np.nan) assert_equal(special.agm(1, np.inf), np.inf) assert_equal(special.agm(np.inf, 1), np.inf) assert_equal(special.agm(-1, -np.inf), -np.inf) assert_equal(special.agm(-np.inf, -1), -np.inf) def test_legacy(): # Legacy behavior: truncating arguments to integers with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3)) assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3)) assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3)) assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3)) assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3)) assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3)) assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3)) assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3)) assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3)) @with_special_errors def test_error_raising(): assert_raises(special.SpecialFunctionError, special.iv, 1, 1e99j) def test_xlogy(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x*np.log(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float) z2 = np.r_[z1, [(0, 1j), (1, 1j)]] w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13) w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1]) assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13) def test_xlog1py(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x * np.log1p(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0), (1, 1e-30)], dtype=float) w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13) def test_entr(): def xfunc(x): if x < 0: return -np.inf else: return -special.xlogy(x, x) values = (0, 0.5, 1.0, np.inf) signs = [-1, 1] arr = [] for sgn, v in itertools.product(signs, values): arr.append(sgn * v) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z) assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13) def test_kl_div(): def xfunc(x, y): if x < 0 or y < 0 or (y == 0 and x != 0): # extension of natural domain to preserve convexity return np.inf elif np.isposinf(x) or np.isposinf(y): # limits within the natural domain return np.inf elif x == 0: return y else: return special.xlogy(x, x/y) - x + y values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13) def test_rel_entr(): def xfunc(x, y): if x > 0 and y > 0: return special.xlogy(x, x/y) elif x == 0 and y >= 0: return 0 else: return np.inf values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13) def test_huber(): assert_equal(special.huber(-1, 1.5), np.inf) assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5)) assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2)) def xfunc(delta, r): if delta < 0: return np.inf elif np.abs(r) < delta: return 0.5 * np.square(r) else: return delta * (np.abs(r) - 0.5 * delta) z = np.random.randn(10, 2) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13) def test_pseudo_huber(): def xfunc(delta, r): if delta < 0: return np.inf elif (not delta) or (not r): return 0 else: return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1) z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]]) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13)
aeklant/scipy
scipy/special/tests/test_basic.py
scipy/odr/__init__.py
import threading import scipy._lib.decorator __all__ = ['ReentrancyError', 'ReentrancyLock', 'non_reentrant'] class ReentrancyError(RuntimeError): pass class ReentrancyLock(object): """ Threading lock that raises an exception for reentrant calls. Calls from different threads are serialized, and nested calls from the same thread result to an error. The object can be used as a context manager or to decorate functions via the decorate() method. """ def __init__(self, err_msg): self._rlock = threading.RLock() self._entered = False self._err_msg = err_msg def __enter__(self): self._rlock.acquire() if self._entered: self._rlock.release() raise ReentrancyError(self._err_msg) self._entered = True def __exit__(self, type, value, traceback): self._entered = False self._rlock.release() def decorate(self, func): def caller(func, *a, **kw): with self: return func(*a, **kw) return scipy._lib.decorator.decorate(func, caller) def non_reentrant(err_msg=None): """ Decorate a function with a threading lock and prevent reentrant calls. """ def decorator(func): msg = err_msg if msg is None: msg = "%s is not re-entrant" % func.__name__ lock = ReentrancyLock(msg) return lock.decorate(func) return decorator
# this program corresponds to special.py ### Means test is not done yet # E Means test is giving error (E) # F Means test is failing (F) # EF Means test is giving error and Failing #! Means test is segfaulting # 8 Means test runs forever ### test_besselpoly ### test_mathieu_a ### test_mathieu_even_coef ### test_mathieu_odd_coef ### test_modfresnelp ### test_modfresnelm # test_pbdv_seq ### test_pbvv_seq ### test_sph_harm import itertools import platform import numpy as np from numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp, log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, float_) import pytest from pytest import raises as assert_raises from numpy.testing import (assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_approx_equal, assert_, assert_allclose, assert_array_almost_equal_nulp, suppress_warnings) from scipy import special import scipy.special._ufuncs as cephes from scipy.special import ellipk from scipy.special._testutils import with_special_errors, \ assert_func_equal, FuncData import math class TestCephes(object): def test_airy(self): cephes.airy(0) def test_airye(self): cephes.airye(0) def test_binom(self): n = np.array([0.264, 4, 5.2, 17]) k = np.array([2, 0.4, 7, 3.3]) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389, -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846], [10.92, 2.22993515861399, -0.00585728, 10.468891352063146], [136, 3.5252179590758828, 19448, 1024.5526916174495]]) assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13) # Test branches in implementation np.random.seed(1234) n = np.r_[np.arange(-7, 30), 1000*np.random.rand(30) - 500] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_2(self): # Test branches in implementation np.random.seed(1234) n = np.r_[np.logspace(1, 300, 20)] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_exact(self): @np.vectorize def binom_int(n, k): n = int(n) k = int(k) num = int(1) den = int(1) for i in range(1, k+1): num *= i + n - k den *= i return float(num/den) np.random.seed(1234) n = np.arange(1, 15) k = np.arange(0, 15) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T nk = nk[nk[:,0] >= nk[:,1]] assert_func_equal(cephes.binom, binom_int(nk[:,0], nk[:,1]), nk, atol=0, rtol=0) def test_binom_nooverflow_8346(self): # Test (binom(n, k) doesn't overflow prematurely */ dataset = [ (1000, 500, 2.70288240945436551e+299), (1002, 501, 1.08007396880791225e+300), (1004, 502, 4.31599279169058121e+300), (1006, 503, 1.72468101616263781e+301), (1008, 504, 6.89188009236419153e+301), (1010, 505, 2.75402257948335448e+302), (1012, 506, 1.10052048531923757e+303), (1014, 507, 4.39774063758732849e+303), (1016, 508, 1.75736486108312519e+304), (1018, 509, 7.02255427788423734e+304), (1020, 510, 2.80626776829962255e+305), (1022, 511, 1.12140876377061240e+306), (1024, 512, 4.48125455209897109e+306), (1026, 513, 1.79075474304149900e+307), (1028, 514, 7.15605105487789676e+307) ] dataset = np.asarray(dataset) FuncData(cephes.binom, dataset, (0, 1), 2, rtol=1e-12).check() def test_bdtr(self): assert_equal(cephes.bdtr(1,1,0.5),1.0) def test_bdtri(self): assert_equal(cephes.bdtri(1,3,0.5),0.5) def test_bdtrc(self): assert_equal(cephes.bdtrc(1,3,0.5),0.5) def test_bdtrin(self): assert_equal(cephes.bdtrin(1,0,1),5.0) def test_bdtrik(self): cephes.bdtrik(1,3,0.5) def test_bei(self): assert_equal(cephes.bei(0),0.0) def test_beip(self): assert_equal(cephes.beip(0),0.0) def test_ber(self): assert_equal(cephes.ber(0),1.0) def test_berp(self): assert_equal(cephes.berp(0),0.0) def test_besselpoly(self): assert_equal(cephes.besselpoly(0,0,0),1.0) def test_beta(self): assert_equal(cephes.beta(1,1),1.0) assert_allclose(cephes.beta(-100.3, 1e-200), cephes.gamma(1e-200)) assert_allclose(cephes.beta(0.0342, 171), 24.070498359873497, rtol=1e-13, atol=0) def test_betainc(self): assert_equal(cephes.betainc(1,1,1),1.0) assert_allclose(cephes.betainc(0.0342, 171, 1e-10), 0.55269916901806648) def test_betaln(self): assert_equal(cephes.betaln(1,1),0.0) assert_allclose(cephes.betaln(-100.3, 1e-200), cephes.gammaln(1e-200)) assert_allclose(cephes.betaln(0.0342, 170), 3.1811881124242447, rtol=1e-14, atol=0) def test_betaincinv(self): assert_equal(cephes.betaincinv(1,1,1),1.0) assert_allclose(cephes.betaincinv(0.0342, 171, 0.25), 8.4231316935498957e-21, rtol=3e-12, atol=0) def test_beta_inf(self): assert_(np.isinf(special.beta(-1, 2))) def test_btdtr(self): assert_equal(cephes.btdtr(1,1,1),1.0) def test_btdtri(self): assert_equal(cephes.btdtri(1,1,1),1.0) def test_btdtria(self): assert_equal(cephes.btdtria(1,1,1),5.0) def test_btdtrib(self): assert_equal(cephes.btdtrib(1,1,1),5.0) def test_cbrt(self): assert_approx_equal(cephes.cbrt(1),1.0) def test_chdtr(self): assert_equal(cephes.chdtr(1,0),0.0) def test_chdtrc(self): assert_equal(cephes.chdtrc(1,0),1.0) def test_chdtri(self): assert_equal(cephes.chdtri(1,1),0.0) def test_chdtriv(self): assert_equal(cephes.chdtriv(0,0),5.0) def test_chndtr(self): assert_equal(cephes.chndtr(0,1,0),0.0) # Each row holds (x, nu, lam, expected_value) # These values were computed using Wolfram Alpha with # CDF[NoncentralChiSquareDistribution[nu, lam], x] values = np.array([ [25.00, 20.0, 400, 4.1210655112396197139e-57], [25.00, 8.00, 250, 2.3988026526832425878e-29], [0.001, 8.00, 40., 5.3761806201366039084e-24], [0.010, 8.00, 40., 5.45396231055999457039e-20], [20.00, 2.00, 107, 1.39390743555819597802e-9], [22.50, 2.00, 107, 7.11803307138105870671e-9], [25.00, 2.00, 107, 3.11041244829864897313e-8], [3.000, 2.00, 1.0, 0.62064365321954362734], [350.0, 300., 10., 0.93880128006276407710], [100.0, 13.5, 10., 0.99999999650104210949], [700.0, 20.0, 400, 0.99999999925680650105], [150.0, 13.5, 10., 0.99999999999999983046], [160.0, 13.5, 10., 0.99999999999999999518], # 1.0 ]) cdf = cephes.chndtr(values[:, 0], values[:, 1], values[:, 2]) assert_allclose(cdf, values[:, 3], rtol=1e-12) assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0) assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0) assert_(np.isnan(cephes.chndtr(np.nan, 1, 2))) assert_(np.isnan(cephes.chndtr(5, np.nan, 2))) assert_(np.isnan(cephes.chndtr(5, 1, np.nan))) def test_chndtridf(self): assert_equal(cephes.chndtridf(0,0,1),5.0) def test_chndtrinc(self): assert_equal(cephes.chndtrinc(0,1,0),5.0) def test_chndtrix(self): assert_equal(cephes.chndtrix(0,1,0),0.0) def test_cosdg(self): assert_equal(cephes.cosdg(0),1.0) def test_cosm1(self): assert_equal(cephes.cosm1(0),0.0) def test_cotdg(self): assert_almost_equal(cephes.cotdg(45),1.0) def test_dawsn(self): assert_equal(cephes.dawsn(0),0.0) assert_allclose(cephes.dawsn(1.23), 0.50053727749081767) def test_diric(self): # Test behavior near multiples of 2pi. Regression test for issue # described in gh-4001. n_odd = [1, 5, 25] x = np.array(2*np.pi + 5e-5).astype(np.float32) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7) x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) x = np.array(2*np.pi + 1e-15).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) if hasattr(np, 'float128'): # No float128 available in 32-bit numpy x = np.array(2*np.pi + 1e-12).astype(np.float128) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19) n_even = [2, 4, 24] x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15) # Test at some values not near a multiple of pi x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi) octave_result = [0.872677996249965, 0.539344662916632, 0.127322003750035, -0.206011329583298] assert_almost_equal(special.diric(x, 3), octave_result, decimal=15) def test_diric_broadcasting(self): x = np.arange(5) n = np.array([1, 3, 7]) assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size)) def test_ellipe(self): assert_equal(cephes.ellipe(1),1.0) def test_ellipeinc(self): assert_equal(cephes.ellipeinc(0,1),0.0) def test_ellipj(self): cephes.ellipj(0,1) def test_ellipk(self): assert_allclose(ellipk(0), pi/2) def test_ellipkinc(self): assert_equal(cephes.ellipkinc(0,0),0.0) def test_erf(self): assert_equal(cephes.erf(0), 0.0) def test_erf_symmetry(self): x = 5.905732037710919 assert_equal(cephes.erf(x) + cephes.erf(-x), 0.0) def test_erfc(self): assert_equal(cephes.erfc(0), 1.0) def test_exp10(self): assert_approx_equal(cephes.exp10(2),100.0) def test_exp2(self): assert_equal(cephes.exp2(2),4.0) def test_expm1(self): assert_equal(cephes.expm1(0),0.0) assert_equal(cephes.expm1(np.inf), np.inf) assert_equal(cephes.expm1(-np.inf), -1) assert_equal(cephes.expm1(np.nan), np.nan) def test_expm1_complex(self): expm1 = cephes.expm1 assert_equal(expm1(0 + 0j), 0 + 0j) assert_equal(expm1(complex(np.inf, 0)), complex(np.inf, 0)) assert_equal(expm1(complex(np.inf, 1)), complex(np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 2)), complex(-np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 4)), complex(-np.inf, -np.inf)) assert_equal(expm1(complex(np.inf, 5)), complex(np.inf, -np.inf)) assert_equal(expm1(complex(1, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(0, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.inf, np.inf)), complex(np.inf, np.nan)) assert_equal(expm1(complex(-np.inf, np.inf)), complex(-1, 0)) assert_equal(expm1(complex(-np.inf, np.nan)), complex(-1, 0)) assert_equal(expm1(complex(np.inf, np.nan)), complex(np.inf, np.nan)) assert_equal(expm1(complex(0, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(1, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, 1)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, np.nan)), complex(np.nan, np.nan)) @pytest.mark.xfail(reason='The real part of expm1(z) bad at these points') def test_expm1_complex_hard(self): # The real part of this function is difficult to evaluate when # z.real = -log(cos(z.imag)). y = np.array([0.1, 0.2, 0.3, 5, 11, 20]) x = -np.log(np.cos(y)) z = x + 1j*y # evaluate using mpmath.expm1 with dps=1000 expected = np.array([-5.5507901846769623e-17+0.10033467208545054j, 2.4289354732893695e-18+0.20271003550867248j, 4.5235500262585768e-17+0.30933624960962319j, 7.8234305217489006e-17-3.3805150062465863j, -1.3685191953697676e-16-225.95084645419513j, 8.7175620481291045e-17+2.2371609442247422j]) found = cephes.expm1(z) # this passes. assert_array_almost_equal_nulp(found.imag, expected.imag, 3) # this fails. assert_array_almost_equal_nulp(found.real, expected.real, 20) def test_fdtr(self): assert_equal(cephes.fdtr(1, 1, 0), 0.0) # Computed using Wolfram Alpha: CDF[FRatioDistribution[1e-6, 5], 10] assert_allclose(cephes.fdtr(1e-6, 5, 10), 0.9999940790193488, rtol=1e-12) def test_fdtrc(self): assert_equal(cephes.fdtrc(1, 1, 0), 1.0) # Computed using Wolfram Alpha: # 1 - CDF[FRatioDistribution[2, 1/10], 1e10] assert_allclose(cephes.fdtrc(2, 0.1, 1e10), 0.27223784621293512, rtol=1e-12) def test_fdtri(self): assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]), array([0.9937365, 1.00630298]), rtol=1e-6) # From Wolfram Alpha: # CDF[FRatioDistribution[1/10, 1], 3] = 0.8756751669632105666874... p = 0.8756751669632105666874 assert_allclose(cephes.fdtri(0.1, 1, p), 3, rtol=1e-12) @pytest.mark.xfail(reason='Returns nan on i686.') def test_fdtri_mysterious_failure(self): assert_allclose(cephes.fdtri(1, 1, 0.5), 1) def test_fdtridfd(self): assert_equal(cephes.fdtridfd(1,0,0),5.0) def test_fresnel(self): assert_equal(cephes.fresnel(0),(0.0,0.0)) def test_gamma(self): assert_equal(cephes.gamma(5),24.0) def test_gammainccinv(self): assert_equal(cephes.gammainccinv(5,1),0.0) def test_gammaln(self): cephes.gammaln(10) def test_gammasgn(self): vals = np.array([-4, -3.5, -2.3, 1, 4.2], np.float64) assert_array_equal(cephes.gammasgn(vals), np.sign(cephes.rgamma(vals))) def test_gdtr(self): assert_equal(cephes.gdtr(1,1,0),0.0) def test_gdtr_inf(self): assert_equal(cephes.gdtr(1,1,np.inf),1.0) def test_gdtrc(self): assert_equal(cephes.gdtrc(1,1,0),1.0) def test_gdtria(self): assert_equal(cephes.gdtria(0,1,1),0.0) def test_gdtrib(self): cephes.gdtrib(1,0,1) # assert_equal(cephes.gdtrib(1,0,1),5.0) def test_gdtrix(self): cephes.gdtrix(1,1,.1) def test_hankel1(self): cephes.hankel1(1,1) def test_hankel1e(self): cephes.hankel1e(1,1) def test_hankel2(self): cephes.hankel2(1,1) def test_hankel2e(self): cephes.hankel2e(1,1) def test_hyp1f1(self): assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) cephes.hyp1f1(1,1,1) def test_hyp2f1(self): assert_equal(cephes.hyp2f1(1,1,1,0),1.0) def test_i0(self): assert_equal(cephes.i0(0),1.0) def test_i0e(self): assert_equal(cephes.i0e(0),1.0) def test_i1(self): assert_equal(cephes.i1(0),0.0) def test_i1e(self): assert_equal(cephes.i1e(0),0.0) def test_it2i0k0(self): cephes.it2i0k0(1) def test_it2j0y0(self): cephes.it2j0y0(1) def test_it2struve0(self): cephes.it2struve0(1) def test_itairy(self): cephes.itairy(1) def test_iti0k0(self): assert_equal(cephes.iti0k0(0),(0.0,0.0)) def test_itj0y0(self): assert_equal(cephes.itj0y0(0),(0.0,0.0)) def test_itmodstruve0(self): assert_equal(cephes.itmodstruve0(0),0.0) def test_itstruve0(self): assert_equal(cephes.itstruve0(0),0.0) def test_iv(self): assert_equal(cephes.iv(1,0),0.0) def _check_ive(self): assert_equal(cephes.ive(1,0),0.0) def test_j0(self): assert_equal(cephes.j0(0),1.0) def test_j1(self): assert_equal(cephes.j1(0),0.0) def test_jn(self): assert_equal(cephes.jn(0,0),1.0) def test_jv(self): assert_equal(cephes.jv(0,0),1.0) def _check_jve(self): assert_equal(cephes.jve(0,0),1.0) def test_k0(self): cephes.k0(2) def test_k0e(self): cephes.k0e(2) def test_k1(self): cephes.k1(2) def test_k1e(self): cephes.k1e(2) def test_kei(self): cephes.kei(2) def test_keip(self): assert_equal(cephes.keip(0),0.0) def test_ker(self): cephes.ker(2) def test_kerp(self): cephes.kerp(2) def _check_kelvin(self): cephes.kelvin(2) def test_kn(self): cephes.kn(1,1) def test_kolmogi(self): assert_equal(cephes.kolmogi(1),0.0) assert_(np.isnan(cephes.kolmogi(np.nan))) def test_kolmogorov(self): assert_equal(cephes.kolmogorov(0), 1.0) def test_kolmogp(self): assert_equal(cephes._kolmogp(0), -0.0) def test_kolmogc(self): assert_equal(cephes._kolmogc(0), 0.0) def test_kolmogci(self): assert_equal(cephes._kolmogci(0), 0.0) assert_(np.isnan(cephes._kolmogci(np.nan))) def _check_kv(self): cephes.kv(1,1) def _check_kve(self): cephes.kve(1,1) def test_log1p(self): log1p = cephes.log1p assert_equal(log1p(0), 0.0) assert_equal(log1p(-1), -np.inf) assert_equal(log1p(-2), np.nan) assert_equal(log1p(np.inf), np.inf) def test_log1p_complex(self): log1p = cephes.log1p c = complex assert_equal(log1p(0 + 0j), 0 + 0j) assert_equal(log1p(c(-1, 0)), c(-np.inf, 0)) with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in multiply") assert_allclose(log1p(c(1, np.inf)), c(np.inf, np.pi/2)) assert_equal(log1p(c(1, np.nan)), c(np.nan, np.nan)) assert_allclose(log1p(c(-np.inf, 1)), c(np.inf, np.pi)) assert_equal(log1p(c(np.inf, 1)), c(np.inf, 0)) assert_allclose(log1p(c(-np.inf, np.inf)), c(np.inf, 3*np.pi/4)) assert_allclose(log1p(c(np.inf, np.inf)), c(np.inf, np.pi/4)) assert_equal(log1p(c(np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(-np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, np.inf)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, 1)), c(np.nan, np.nan)) assert_equal(log1p(c(np.nan, np.nan)), c(np.nan, np.nan)) def test_lpmv(self): assert_equal(cephes.lpmv(0,0,1),1.0) def test_mathieu_a(self): assert_equal(cephes.mathieu_a(1,0),1.0) def test_mathieu_b(self): assert_equal(cephes.mathieu_b(1,0),1.0) def test_mathieu_cem(self): assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) # Test AMS 20.2.27 @np.vectorize def ce_smallq(m, q, z): z *= np.pi/180 if m == 0: return 2**(-0.5) * (1 - .5*q*cos(2*z)) # + O(q^2) elif m == 1: return cos(z) - q/8 * cos(3*z) # + O(q^2) elif m == 2: return cos(2*z) - q*(cos(4*z)/12 - 1/4) # + O(q^2) else: return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(0, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0], ce_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_sem(self): assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) # Test AMS 20.2.27 @np.vectorize def se_smallq(m, q, z): z *= np.pi/180 if m == 1: return sin(z) - q/8 * sin(3*z) # + O(q^2) elif m == 2: return sin(2*z) - q*sin(4*z)/12 # + O(q^2) else: return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(1, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0], se_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_modcem1(self): assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) def test_mathieu_modcem2(self): cephes.mathieu_modcem2(1,1,1) # Test reflection relation AMS 20.6.19 m = np.arange(0, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modcem2(m, q, -z)[0] fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0] y2 = -cephes.mathieu_modcem2(m, q, z)[0] - 2*fr*cephes.mathieu_modcem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_modsem1(self): assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) def test_mathieu_modsem2(self): cephes.mathieu_modsem2(1,1,1) # Test reflection relation AMS 20.6.20 m = np.arange(1, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modsem2(m, q, -z)[0] fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1] y2 = cephes.mathieu_modsem2(m, q, z)[0] - 2*fr*cephes.mathieu_modsem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_overflow(self): # Check that these return NaNs instead of causing a SEGV assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan)) def test_mathieu_ticket_1847(self): # Regression test --- this call had some out-of-bounds access # and could return nan occasionally for k in range(60): v = cephes.mathieu_modsem2(2, 100, -1) # Values from ACM TOMS 804 (derivate by numerical differentiation) assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10) assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4) def test_modfresnelm(self): cephes.modfresnelm(0) def test_modfresnelp(self): cephes.modfresnelp(0) def _check_modstruve(self): assert_equal(cephes.modstruve(1,0),0.0) def test_nbdtr(self): assert_equal(cephes.nbdtr(1,1,1),1.0) def test_nbdtrc(self): assert_equal(cephes.nbdtrc(1,1,1),0.0) def test_nbdtri(self): assert_equal(cephes.nbdtri(1,1,1),1.0) def __check_nbdtrik(self): cephes.nbdtrik(1,.4,.5) def test_nbdtrin(self): assert_equal(cephes.nbdtrin(1,0,0),5.0) def test_ncfdtr(self): assert_equal(cephes.ncfdtr(1,1,1,0),0.0) def test_ncfdtri(self): assert_equal(cephes.ncfdtri(1, 1, 1, 0), 0.0) f = [0.5, 1, 1.5] p = cephes.ncfdtr(2, 3, 1.5, f) assert_allclose(cephes.ncfdtri(2, 3, 1.5, p), f) def test_ncfdtridfd(self): dfd = [1, 2, 3] p = cephes.ncfdtr(2, dfd, 0.25, 15) assert_allclose(cephes.ncfdtridfd(2, p, 0.25, 15), dfd) def test_ncfdtridfn(self): dfn = [0.1, 1, 2, 3, 1e4] p = cephes.ncfdtr(dfn, 2, 0.25, 15) assert_allclose(cephes.ncfdtridfn(p, 2, 0.25, 15), dfn, rtol=1e-5) def test_ncfdtrinc(self): nc = [0.5, 1.5, 2.0] p = cephes.ncfdtr(2, 3, nc, 15) assert_allclose(cephes.ncfdtrinc(2, 3, p, 15), nc) def test_nctdtr(self): assert_equal(cephes.nctdtr(1,0,0),0.5) assert_equal(cephes.nctdtr(9, 65536, 45), 0.0) assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5) assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.))) assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.) assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.))) assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.))) assert_(np.isnan(cephes.nctdtr(2., 1., np.nan))) def __check_nctdtridf(self): cephes.nctdtridf(1,0.5,0) def test_nctdtrinc(self): cephes.nctdtrinc(1,0,0) def test_nctdtrit(self): cephes.nctdtrit(.1,0.2,.5) def test_nrdtrimn(self): assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) def test_nrdtrisd(self): assert_allclose(cephes.nrdtrisd(0.5,0.5,0.5), 0.0, atol=0, rtol=0) def test_obl_ang1(self): cephes.obl_ang1(1,1,1,0) def test_obl_ang1_cv(self): result = cephes.obl_ang1_cv(1,1,1,1,0) assert_almost_equal(result[0],1.0) assert_almost_equal(result[1],0.0) def _check_obl_cv(self): assert_equal(cephes.obl_cv(1,1,0),2.0) def test_obl_rad1(self): cephes.obl_rad1(1,1,1,0) def test_obl_rad1_cv(self): cephes.obl_rad1_cv(1,1,1,1,0) def test_obl_rad2(self): cephes.obl_rad2(1,1,1,0) def test_obl_rad2_cv(self): cephes.obl_rad2_cv(1,1,1,1,0) def test_pbdv(self): assert_equal(cephes.pbdv(1,0),(0.0,1.0)) def test_pbvv(self): cephes.pbvv(1,0) def test_pbwa(self): cephes.pbwa(1,0) def test_pdtr(self): val = cephes.pdtr(0, 1) assert_almost_equal(val, np.exp(-1)) # Edge case: m = 0. val = cephes.pdtr([0, 1, 2], 0) assert_array_equal(val, [1, 1, 1]) def test_pdtrc(self): val = cephes.pdtrc(0, 1) assert_almost_equal(val, 1 - np.exp(-1)) # Edge case: m = 0. val = cephes.pdtrc([0, 1, 2], 0.0) assert_array_equal(val, [0, 0, 0]) def test_pdtri(self): with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") cephes.pdtri(0.5,0.5) def test_pdtrik(self): k = cephes.pdtrik(0.5, 1) assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5) # Edge case: m = 0 or very small. k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6]) assert_array_equal(k, np.zeros((3, 3))) def test_pro_ang1(self): cephes.pro_ang1(1,1,1,0) def test_pro_ang1_cv(self): assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), array((1.0,0.0))) def _check_pro_cv(self): assert_equal(cephes.pro_cv(1,1,0),2.0) def test_pro_rad1(self): cephes.pro_rad1(1,1,1,0.1) def test_pro_rad1_cv(self): cephes.pro_rad1_cv(1,1,1,1,0) def test_pro_rad2(self): cephes.pro_rad2(1,1,1,0) def test_pro_rad2_cv(self): cephes.pro_rad2_cv(1,1,1,1,0) def test_psi(self): cephes.psi(1) def test_radian(self): assert_equal(cephes.radian(0,0,0),0) def test_rgamma(self): assert_equal(cephes.rgamma(1),1.0) def test_round(self): assert_equal(cephes.round(3.4),3.0) assert_equal(cephes.round(-3.4),-3.0) assert_equal(cephes.round(3.6),4.0) assert_equal(cephes.round(-3.6),-4.0) assert_equal(cephes.round(3.5),4.0) assert_equal(cephes.round(-3.5),-4.0) def test_shichi(self): cephes.shichi(1) def test_sici(self): cephes.sici(1) s, c = cephes.sici(np.inf) assert_almost_equal(s, np.pi * 0.5) assert_almost_equal(c, 0) s, c = cephes.sici(-np.inf) assert_almost_equal(s, -np.pi * 0.5) assert_(np.isnan(c), "cosine integral(-inf) is not nan") def test_sindg(self): assert_equal(cephes.sindg(90),1.0) def test_smirnov(self): assert_equal(cephes.smirnov(1,.1),0.9) assert_(np.isnan(cephes.smirnov(1,np.nan))) def test_smirnovp(self): assert_equal(cephes._smirnovp(1, .1), -1) assert_equal(cephes._smirnovp(2, 0.75), -2*(0.25)**(2-1)) assert_equal(cephes._smirnovp(3, 0.75), -3*(0.25)**(3-1)) assert_(np.isnan(cephes._smirnovp(1, np.nan))) def test_smirnovc(self): assert_equal(cephes._smirnovc(1,.1),0.1) assert_(np.isnan(cephes._smirnovc(1,np.nan))) x10 = np.linspace(0, 1, 11, endpoint=True) assert_almost_equal(cephes._smirnovc(3, x10), 1-cephes.smirnov(3, x10)) x4 = np.linspace(0, 1, 5, endpoint=True) assert_almost_equal(cephes._smirnovc(4, x4), 1-cephes.smirnov(4, x4)) def test_smirnovi(self): assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) assert_(np.isnan(cephes.smirnovi(1,np.nan))) def test_smirnovci(self): assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.4)),0.4) assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.6)),0.6) assert_(np.isnan(cephes._smirnovci(1,np.nan))) def test_spence(self): assert_equal(cephes.spence(1),0.0) def test_stdtr(self): assert_equal(cephes.stdtr(1,0),0.5) assert_almost_equal(cephes.stdtr(1,1), 0.75) assert_almost_equal(cephes.stdtr(1,2), 0.852416382349) def test_stdtridf(self): cephes.stdtridf(0.7,1) def test_stdtrit(self): cephes.stdtrit(1,0.7) def test_struve(self): assert_equal(cephes.struve(0,0),0.0) def test_tandg(self): assert_equal(cephes.tandg(45),1.0) def test_tklmbda(self): assert_almost_equal(cephes.tklmbda(1,1),1.0) def test_y0(self): cephes.y0(1) def test_y1(self): cephes.y1(1) def test_yn(self): cephes.yn(1,1) def test_yv(self): cephes.yv(1,1) def _check_yve(self): cephes.yve(1,1) def test_wofz(self): z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.), complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.), complex(-0.0000000234545,1.1234), complex(-3.,5.1), complex(-53,30.1), complex(0.0,0.12345), complex(11,1), complex(-22,-2), complex(9,-28), complex(21,-33), complex(1e5,1e5), complex(1e14,1e14) ] w = [ complex(-3.78270245518980507452677445620103199303131110e-7, 0.000903861276433172057331093754199933411710053155), complex(0.1764906227004816847297495349730234591778719532788, -0.02146550539468457616788719893991501311573031095617), complex(0.2410250715772692146133539023007113781272362309451, 0.06087579663428089745895459735240964093522265589350), complex(0.30474420525691259245713884106959496013413834051768, -0.20821893820283162728743734725471561394145872072738), complex(7.317131068972378096865595229600561710140617977e34, 8.321873499714402777186848353320412813066170427e34), complex(0.0615698507236323685519612934241429530190806818395, -0.00676005783716575013073036218018565206070072304635), complex(0.3960793007699874918961319170187598400134746631, -5.593152259116644920546186222529802777409274656e-9), complex(0.08217199226739447943295069917990417630675021771804, -0.04701291087643609891018366143118110965272615832184), complex(0.00457246000350281640952328010227885008541748668738, -0.00804900791411691821818731763401840373998654987934), complex(0.8746342859608052666092782112565360755791467973338452, 0.), complex(0.00468190164965444174367477874864366058339647648741, 0.0510735563901306197993676329845149741675029197050), complex(-0.0023193175200187620902125853834909543869428763219, -0.025460054739731556004902057663500272721780776336), complex(9.11463368405637174660562096516414499772662584e304, 3.97101807145263333769664875189354358563218932e305), complex(-4.4927207857715598976165541011143706155432296e281, -2.8019591213423077494444700357168707775769028e281), complex(2.820947917809305132678577516325951485807107151e-6, 2.820947917668257736791638444590253942253354058e-6), complex(2.82094791773878143474039725787438662716372268e-15, 2.82094791773878143474039725773333923127678361e-15) ] assert_func_equal(cephes.wofz, w, z, rtol=1e-13) class TestAiry(object): def test_airy(self): # This tests the airy function to ensure 8 place accuracy in computation x = special.airy(.99) assert_array_almost_equal(x,array([0.13689066,-0.16050153,1.19815925,0.92046818]),8) x = special.airy(.41) assert_array_almost_equal(x,array([0.25238916,-.23480512,0.80686202,0.51053919]),8) x = special.airy(-.36) assert_array_almost_equal(x,array([0.44508477,-0.23186773,0.44939534,0.48105354]),8) def test_airye(self): a = special.airye(0.01) b = special.airy(0.01) b1 = [None]*4 for n in range(2): b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01)) for n in range(2,4): b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) assert_array_almost_equal(a,b1,6) def test_bi_zeros(self): bi = special.bi_zeros(2) bia = (array([-1.17371322, -3.2710930]), array([-2.29443968, -4.07315509]), array([-0.45494438, 0.39652284]), array([0.60195789, -0.76031014])) assert_array_almost_equal(bi,bia,4) bi = special.bi_zeros(5) assert_array_almost_equal(bi[0],array([-1.173713222709127, -3.271093302836352, -4.830737841662016, -6.169852128310251, -7.376762079367764]),11) assert_array_almost_equal(bi[1],array([-2.294439682614122, -4.073155089071828, -5.512395729663599, -6.781294445990305, -7.940178689168587]),10) assert_array_almost_equal(bi[2],array([-0.454944383639657, 0.396522836094465, -0.367969161486959, 0.349499116831805, -0.336026240133662]),11) assert_array_almost_equal(bi[3],array([0.601957887976239, -0.760310141492801, 0.836991012619261, -0.88947990142654, 0.929983638568022]),10) def test_ai_zeros(self): ai = special.ai_zeros(1) assert_array_almost_equal(ai,(array([-2.33810741]), array([-1.01879297]), array([0.5357]), array([0.7012])),4) def test_ai_zeros_big(self): z, zp, ai_zpx, aip_zx = special.ai_zeros(50000) ai_z, aip_z, _, _ = special.airy(z) ai_zp, aip_zp, _, _ = special.airy(zp) ai_envelope = 1/abs(z)**(1./4) aip_envelope = abs(zp)**(1./4) # Check values assert_allclose(ai_zpx, ai_zp, rtol=1e-10) assert_allclose(aip_zx, aip_z, rtol=1e-10) # Check they are zeros assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0) assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.1 assert_allclose(z[:6], [-2.3381074105, -4.0879494441, -5.5205598281, -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10) assert_allclose(zp[:6], [-1.0187929716, -3.2481975822, -4.8200992112, -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10) def test_bi_zeros_big(self): z, zp, bi_zpx, bip_zx = special.bi_zeros(50000) _, _, bi_z, bip_z = special.airy(z) _, _, bi_zp, bip_zp = special.airy(zp) bi_envelope = 1/abs(z)**(1./4) bip_envelope = abs(zp)**(1./4) # Check values assert_allclose(bi_zpx, bi_zp, rtol=1e-10) assert_allclose(bip_zx, bip_z, rtol=1e-10) # Check they are zeros assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0) assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.2 assert_allclose(z[:6], [-1.1737132227, -3.2710933028, -4.8307378417, -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10) assert_allclose(zp[:6], [-2.2944396826, -4.0731550891, -5.5123957297, -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10) class TestAssocLaguerre(object): def test_assoc_laguerre(self): a1 = special.genlaguerre(11,1) a2 = special.assoc_laguerre(.2,11,1) assert_array_almost_equal(a2,a1(.2),8) a2 = special.assoc_laguerre(1,11,1) assert_array_almost_equal(a2,a1(1),8) class TestBesselpoly(object): def test_besselpoly(self): pass class TestKelvin(object): def test_bei(self): mbei = special.bei(2) assert_almost_equal(mbei, 0.9722916273066613,5) # this may not be exact def test_beip(self): mbeip = special.beip(2) assert_almost_equal(mbeip,0.91701361338403631,5) # this may not be exact def test_ber(self): mber = special.ber(2) assert_almost_equal(mber,0.75173418271380821,5) # this may not be exact def test_berp(self): mberp = special.berp(2) assert_almost_equal(mberp,-0.49306712470943909,5) # this may not be exact def test_bei_zeros(self): # Abramowitz & Stegun, Table 9.12 bi = special.bei_zeros(5) assert_array_almost_equal(bi,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) def test_beip_zeros(self): bip = special.beip_zeros(5) assert_array_almost_equal(bip,array([3.772673304934953, 8.280987849760042, 12.742147523633703, 17.193431752512542, 21.641143941167325]),8) def test_ber_zeros(self): ber = special.ber_zeros(5) assert_array_almost_equal(ber,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) def test_berp_zeros(self): brp = special.berp_zeros(5) assert_array_almost_equal(brp,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) def test_kelvin(self): mkelv = special.kelvin(2) assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j, special.ker(2) + special.kei(2)*1j, special.berp(2) + special.beip(2)*1j, special.kerp(2) + special.keip(2)*1j),8) def test_kei(self): mkei = special.kei(2) assert_almost_equal(mkei,-0.20240006776470432,5) def test_keip(self): mkeip = special.keip(2) assert_almost_equal(mkeip,0.21980790991960536,5) def test_ker(self): mker = special.ker(2) assert_almost_equal(mker,-0.041664513991509472,5) def test_kerp(self): mkerp = special.kerp(2) assert_almost_equal(mkerp,-0.10660096588105264,5) def test_kei_zeros(self): kei = special.kei_zeros(5) assert_array_almost_equal(kei,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) def test_keip_zeros(self): keip = special.keip_zeros(5) assert_array_almost_equal(keip,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) # numbers come from 9.9 of A&S pg. 381 def test_kelvin_zeros(self): tmp = special.kelvin_zeros(5) berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp assert_array_almost_equal(berz,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) assert_array_almost_equal(beiz,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) assert_array_almost_equal(kerz,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44382]),4) assert_array_almost_equal(keiz,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) assert_array_almost_equal(berpz,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) assert_array_almost_equal(beipz,array([3.77267, # table from 1927 had 3.77320 # but this is more accurate 8.28099, 12.74215, 17.19343, 21.64114]),4) assert_array_almost_equal(kerpz,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) assert_array_almost_equal(keipz,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) def test_ker_zeros(self): ker = special.ker_zeros(5) assert_array_almost_equal(ker,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44381]),4) def test_kerp_zeros(self): kerp = special.kerp_zeros(5) assert_array_almost_equal(kerp,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) class TestBernoulli(object): def test_bernoulli(self): brn = special.bernoulli(5) assert_array_almost_equal(brn,array([1.0000, -0.5000, 0.1667, 0.0000, -0.0333, 0.0000]),4) class TestBeta(object): def test_beta(self): bet = special.beta(2,4) betg = (special.gamma(2)*special.gamma(4))/special.gamma(6) assert_almost_equal(bet,betg,8) def test_betaln(self): betln = special.betaln(2,4) bet = log(abs(special.beta(2,4))) assert_almost_equal(betln,bet,8) def test_betainc(self): btinc = special.betainc(1,1,.2) assert_almost_equal(btinc,0.2,8) def test_betaincinv(self): y = special.betaincinv(2,4,.5) comp = special.betainc(2,4,y) assert_almost_equal(comp,.5,5) class TestCombinatorics(object): def test_comb(self): assert_array_almost_equal(special.comb([10, 10], [3, 4]), [120., 210.]) assert_almost_equal(special.comb(10, 3), 120.) assert_equal(special.comb(10, 3, exact=True), 120) assert_equal(special.comb(10, 3, exact=True, repetition=True), 220) assert_allclose([special.comb(20, k, exact=True) for k in range(21)], special.comb(20, list(range(21))), atol=1e-15) ii = np.iinfo(int).max + 1 assert_equal(special.comb(ii, ii-1, exact=True), ii) expected = 100891344545564193334812497256 assert_equal(special.comb(100, 50, exact=True), expected) def test_comb_with_np_int64(self): n = 70 k = 30 np_n = np.int64(n) np_k = np.int64(k) assert_equal(special.comb(np_n, np_k, exact=True), special.comb(n, k, exact=True)) def test_comb_zeros(self): assert_equal(special.comb(2, 3, exact=True), 0) assert_equal(special.comb(-1, 3, exact=True), 0) assert_equal(special.comb(2, -1, exact=True), 0) assert_equal(special.comb(2, -1, exact=False), 0) assert_array_almost_equal(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 120.]) def test_perm(self): assert_array_almost_equal(special.perm([10, 10], [3, 4]), [720., 5040.]) assert_almost_equal(special.perm(10, 3), 720.) assert_equal(special.perm(10, 3, exact=True), 720) def test_perm_zeros(self): assert_equal(special.perm(2, 3, exact=True), 0) assert_equal(special.perm(-1, 3, exact=True), 0) assert_equal(special.perm(2, -1, exact=True), 0) assert_equal(special.perm(2, -1, exact=False), 0) assert_array_almost_equal(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 720.]) class TestTrigonometric(object): def test_cbrt(self): cb = special.cbrt(27) cbrl = 27**(1.0/3.0) assert_approx_equal(cb,cbrl) def test_cbrtmore(self): cb1 = special.cbrt(27.9) cbrl1 = 27.9**(1.0/3.0) assert_almost_equal(cb1,cbrl1,8) def test_cosdg(self): cdg = special.cosdg(90) cdgrl = cos(pi/2.0) assert_almost_equal(cdg,cdgrl,8) def test_cosdgmore(self): cdgm = special.cosdg(30) cdgmrl = cos(pi/6.0) assert_almost_equal(cdgm,cdgmrl,8) def test_cosm1(self): cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10)) csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) assert_array_almost_equal(cs,csrl,8) def test_cotdg(self): ct = special.cotdg(30) ctrl = tan(pi/6.0)**(-1) assert_almost_equal(ct,ctrl,8) def test_cotdgmore(self): ct1 = special.cotdg(45) ctrl1 = tan(pi/4.0)**(-1) assert_almost_equal(ct1,ctrl1,8) def test_specialpoints(self): assert_almost_equal(special.cotdg(45), 1.0, 14) assert_almost_equal(special.cotdg(-45), -1.0, 14) assert_almost_equal(special.cotdg(90), 0.0, 14) assert_almost_equal(special.cotdg(-90), 0.0, 14) assert_almost_equal(special.cotdg(135), -1.0, 14) assert_almost_equal(special.cotdg(-135), 1.0, 14) assert_almost_equal(special.cotdg(225), 1.0, 14) assert_almost_equal(special.cotdg(-225), -1.0, 14) assert_almost_equal(special.cotdg(270), 0.0, 14) assert_almost_equal(special.cotdg(-270), 0.0, 14) assert_almost_equal(special.cotdg(315), -1.0, 14) assert_almost_equal(special.cotdg(-315), 1.0, 14) assert_almost_equal(special.cotdg(765), 1.0, 14) def test_sinc(self): # the sinc implementation and more extensive sinc tests are in numpy assert_array_equal(special.sinc([0]), 1) assert_equal(special.sinc(0.0), 1.0) def test_sindg(self): sn = special.sindg(90) assert_equal(sn,1.0) def test_sindgmore(self): snm = special.sindg(30) snmrl = sin(pi/6.0) assert_almost_equal(snm,snmrl,8) snm1 = special.sindg(45) snmrl1 = sin(pi/4.0) assert_almost_equal(snm1,snmrl1,8) class TestTandg(object): def test_tandg(self): tn = special.tandg(30) tnrl = tan(pi/6.0) assert_almost_equal(tn,tnrl,8) def test_tandgmore(self): tnm = special.tandg(45) tnmrl = tan(pi/4.0) assert_almost_equal(tnm,tnmrl,8) tnm1 = special.tandg(60) tnmrl1 = tan(pi/3.0) assert_almost_equal(tnm1,tnmrl1,8) def test_specialpoints(self): assert_almost_equal(special.tandg(0), 0.0, 14) assert_almost_equal(special.tandg(45), 1.0, 14) assert_almost_equal(special.tandg(-45), -1.0, 14) assert_almost_equal(special.tandg(135), -1.0, 14) assert_almost_equal(special.tandg(-135), 1.0, 14) assert_almost_equal(special.tandg(180), 0.0, 14) assert_almost_equal(special.tandg(-180), 0.0, 14) assert_almost_equal(special.tandg(225), 1.0, 14) assert_almost_equal(special.tandg(-225), -1.0, 14) assert_almost_equal(special.tandg(315), -1.0, 14) assert_almost_equal(special.tandg(-315), 1.0, 14) class TestEllip(object): def test_ellipj_nan(self): """Regression test for #912.""" special.ellipj(0.5, np.nan) def test_ellipj(self): el = special.ellipj(0.2,0) rel = [sin(0.2),cos(0.2),1.0,0.20] assert_array_almost_equal(el,rel,13) def test_ellipk(self): elk = special.ellipk(.2) assert_almost_equal(elk,1.659623598610528,11) assert_equal(special.ellipkm1(0.0), np.inf) assert_equal(special.ellipkm1(1.0), pi/2) assert_equal(special.ellipkm1(np.inf), 0.0) assert_equal(special.ellipkm1(np.nan), np.nan) assert_equal(special.ellipkm1(-1), np.nan) assert_allclose(special.ellipk(-10), 0.7908718902387385) def test_ellipkinc(self): elkinc = special.ellipkinc(pi/2,.2) elk = special.ellipk(0.2) assert_almost_equal(elkinc,elk,15) alpha = 20*pi/180 phi = 45*pi/180 m = sin(alpha)**2 elkinc = special.ellipkinc(phi,m) assert_almost_equal(elkinc,0.79398143,8) # From pg. 614 of A & S assert_equal(special.ellipkinc(pi/2, 0.0), pi/2) assert_equal(special.ellipkinc(pi/2, 1.0), np.inf) assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0) assert_equal(special.ellipkinc(pi/2, np.nan), np.nan) assert_equal(special.ellipkinc(pi/2, 2), np.nan) assert_equal(special.ellipkinc(0, 0.5), 0.0) assert_equal(special.ellipkinc(np.inf, 0.5), np.inf) assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipkinc(np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.nan, 0.5), np.nan) assert_equal(special.ellipkinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14) assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946) def test_ellipkinc_2(self): # Regression test for gh-3550 # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipkinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 1.0259330100195334), 1) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipkinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 5.1296650500976675), 2) def test_ellipkinc_singular(self): # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2) xlog = np.logspace(-300, -17, 25) xlin = np.linspace(1e-17, 0.1, 25) xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False) assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)), rtol=1e14) assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)), rtol=1e14) assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)), rtol=1e14) assert_equal(special.ellipkinc(np.pi/2, 1), np.inf) assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)), rtol=1e14) assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf) def test_ellipe(self): ele = special.ellipe(.2) assert_almost_equal(ele,1.4890350580958529,8) assert_equal(special.ellipe(0.0), pi/2) assert_equal(special.ellipe(1.0), 1.0) assert_equal(special.ellipe(-np.inf), np.inf) assert_equal(special.ellipe(np.nan), np.nan) assert_equal(special.ellipe(2), np.nan) assert_allclose(special.ellipe(-10), 3.6391380384177689) def test_ellipeinc(self): eleinc = special.ellipeinc(pi/2,.2) ele = special.ellipe(0.2) assert_almost_equal(eleinc,ele,14) # pg 617 of A & S alpha, phi = 52*pi/180,35*pi/180 m = sin(alpha)**2 eleinc = special.ellipeinc(phi,m) assert_almost_equal(eleinc, 0.58823065, 8) assert_equal(special.ellipeinc(pi/2, 0.0), pi/2) assert_equal(special.ellipeinc(pi/2, 1.0), 1.0) assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf) assert_equal(special.ellipeinc(pi/2, np.nan), np.nan) assert_equal(special.ellipeinc(pi/2, 2), np.nan) assert_equal(special.ellipeinc(0, 0.5), 0.0) assert_equal(special.ellipeinc(np.inf, 0.5), np.inf) assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf) assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf) assert_equal(special.ellipeinc(np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(np.nan, 0.5), np.nan) assert_equal(special.ellipeinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876) def test_ellipeinc_2(self): # Regression test for gh-3550 # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipeinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 0.84442884574781019), 2) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipeinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 3.3471442287390509), 4) class TestErf(object): def test_erf(self): er = special.erf(.25) assert_almost_equal(er,0.2763263902,8) def test_erf_zeros(self): erz = special.erf_zeros(5) erzr = array([1.45061616+1.88094300j, 2.24465928+2.61657514j, 2.83974105+3.17562810j, 3.33546074+3.64617438j, 3.76900557+4.06069723j]) assert_array_almost_equal(erz,erzr,4) def _check_variant_func(self, func, other_func, rtol, atol=0): np.random.seed(1234) n = 10000 x = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) y = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) z = x + 1j*y old_errors = np.seterr(all='ignore') try: w = other_func(z) w_real = other_func(x).real mask = np.isfinite(w) w = w[mask] z = z[mask] mask = np.isfinite(w_real) w_real = w_real[mask] x = x[mask] # test both real and complex variants assert_func_equal(func, w, z, rtol=rtol, atol=atol) assert_func_equal(func, w_real, x, rtol=rtol, atol=atol) finally: np.seterr(**old_errors) def test_erfc_consistent(self): self._check_variant_func( cephes.erfc, lambda z: 1 - cephes.erf(z), rtol=1e-12, atol=1e-14 # <- the test function loses precision ) def test_erfcx_consistent(self): self._check_variant_func( cephes.erfcx, lambda z: np.exp(z*z) * cephes.erfc(z), rtol=1e-12 ) def test_erfi_consistent(self): self._check_variant_func( cephes.erfi, lambda z: -1j * cephes.erf(1j*z), rtol=1e-12 ) def test_dawsn_consistent(self): self._check_variant_func( cephes.dawsn, lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z), rtol=1e-12 ) def test_erf_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -1, 1] assert_allclose(special.erf(vals), expected, rtol=1e-15) def test_erfc_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, 2, 0] assert_allclose(special.erfc(vals), expected, rtol=1e-15) def test_erfcx_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, np.inf, 0] assert_allclose(special.erfcx(vals), expected, rtol=1e-15) def test_erfi_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -np.inf, np.inf] assert_allclose(special.erfi(vals), expected, rtol=1e-15) def test_dawsn_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -0.0, 0.0] assert_allclose(special.dawsn(vals), expected, rtol=1e-15) def test_wofz_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan + np.nan * 1.j, 0.-0.j, 0.+0.j] assert_allclose(special.wofz(vals), expected, rtol=1e-15) class TestEuler(object): def test_euler(self): eu0 = special.euler(0) eu1 = special.euler(1) eu2 = special.euler(2) # just checking segfaults assert_allclose(eu0, [1], rtol=1e-15) assert_allclose(eu1, [1, 0], rtol=1e-15) assert_allclose(eu2, [1, 0, -1], rtol=1e-15) eu24 = special.euler(24) mathworld = [1,1,5,61,1385,50521,2702765,199360981, 19391512145,2404879675441, 370371188237525,69348874393137901, 15514534163557086905] correct = zeros((25,),'d') for k in range(0,13): if (k % 2): correct[2*k] = -float(mathworld[k]) else: correct[2*k] = float(mathworld[k]) olderr = np.seterr(all='ignore') try: err = nan_to_num((eu24-correct)/correct) errmax = max(err) finally: np.seterr(**olderr) assert_almost_equal(errmax, 0.0, 14) class TestExp(object): def test_exp2(self): ex = special.exp2(2) exrl = 2**2 assert_equal(ex,exrl) def test_exp2more(self): exm = special.exp2(2.5) exmrl = 2**(2.5) assert_almost_equal(exm,exmrl,8) def test_exp10(self): ex = special.exp10(2) exrl = 10**2 assert_approx_equal(ex,exrl) def test_exp10more(self): exm = special.exp10(2.5) exmrl = 10**(2.5) assert_almost_equal(exm,exmrl,8) def test_expm1(self): ex = (special.expm1(2),special.expm1(3),special.expm1(4)) exrl = (exp(2)-1,exp(3)-1,exp(4)-1) assert_array_almost_equal(ex,exrl,8) def test_expm1more(self): ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2)) exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) assert_array_almost_equal(ex1,exrl1,8) class TestFactorialFunctions(object): def test_factorial(self): # Some known values, float math assert_array_almost_equal(special.factorial(0), 1) assert_array_almost_equal(special.factorial(1), 1) assert_array_almost_equal(special.factorial(2), 2) assert_array_almost_equal([6., 24., 120.], special.factorial([3, 4, 5], exact=False)) assert_array_almost_equal(special.factorial([[5, 3], [4, 3]]), [[120, 6], [24, 6]]) # Some known values, integer math assert_equal(special.factorial(0, exact=True), 1) assert_equal(special.factorial(1, exact=True), 1) assert_equal(special.factorial(2, exact=True), 2) assert_equal(special.factorial(5, exact=True), 120) assert_equal(special.factorial(15, exact=True), 1307674368000) # ndarray shape is maintained assert_equal(special.factorial([7, 4, 15, 10], exact=True), [5040, 24, 1307674368000, 3628800]) assert_equal(special.factorial([[5, 3], [4, 3]], True), [[120, 6], [24, 6]]) # object arrays assert_equal(special.factorial(np.arange(-3, 22), True), special.factorial(np.arange(-3, 22), False)) # int64 array assert_equal(special.factorial(np.arange(-3, 15), True), special.factorial(np.arange(-3, 15), False)) # int32 array assert_equal(special.factorial(np.arange(-3, 5), True), special.factorial(np.arange(-3, 5), False)) # Consistent output for n < 0 for exact in (True, False): assert_array_equal(0, special.factorial(-3, exact)) assert_array_equal([1, 2, 0, 0], special.factorial([1, 2, -5, -4], exact)) for n in range(0, 22): # Compare all with math.factorial correct = math.factorial(n) assert_array_equal(correct, special.factorial(n, True)) assert_array_equal(correct, special.factorial([n], True)[0]) assert_allclose(float(correct), special.factorial(n, False)) assert_allclose(float(correct), special.factorial([n], False)[0]) # Compare exact=True vs False, scalar vs array assert_array_equal(special.factorial(n, True), special.factorial(n, False)) assert_array_equal(special.factorial([n], True), special.factorial([n], False)) @pytest.mark.parametrize('x, exact', [ (1, True), (1, False), (np.array(1), True), (np.array(1), False), ]) def test_factorial_0d_return_type(self, x, exact): assert np.isscalar(special.factorial(x, exact=exact)) def test_factorial2(self): assert_array_almost_equal([105., 384., 945.], special.factorial2([7, 8, 9], exact=False)) assert_equal(special.factorial2(7, exact=True), 105) def test_factorialk(self): assert_equal(special.factorialk(5, 1, exact=True), 120) assert_equal(special.factorialk(5, 3, exact=True), 10) @pytest.mark.parametrize('x, exact', [ (np.nan, True), (np.nan, False), (np.array([np.nan]), True), (np.array([np.nan]), False), ]) def test_nan_inputs(self, x, exact): result = special.factorial(x, exact=exact) assert_(np.isnan(result)) def test_mixed_nan_inputs(self): x = np.array([np.nan, 1, 2, 3, np.nan]) result = special.factorial(x, exact=True) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) result = special.factorial(x, exact=False) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) class TestFresnel(object): def test_fresnel(self): frs = array(special.fresnel(.5)) assert_array_almost_equal(frs,array([0.064732432859999287, 0.49234422587144644]),8) def test_fresnel_inf1(self): frs = special.fresnel(np.inf) assert_equal(frs, (0.5, 0.5)) def test_fresnel_inf2(self): frs = special.fresnel(-np.inf) assert_equal(frs, (-0.5, -0.5)) # values from pg 329 Table 7.11 of A & S # slightly corrected in 4th decimal place def test_fresnel_zeros(self): szo, czo = special.fresnel_zeros(5) assert_array_almost_equal(szo, array([2.0093+0.2885j, 2.8335+0.2443j, 3.4675+0.2185j, 4.0026+0.2009j, 4.4742+0.1877j]),3) assert_array_almost_equal(czo, array([1.7437+0.3057j, 2.6515+0.2529j, 3.3204+0.2240j, 3.8757+0.2047j, 4.3611+0.1907j]),3) vals1 = special.fresnel(szo)[0] vals2 = special.fresnel(czo)[1] assert_array_almost_equal(vals1,0,14) assert_array_almost_equal(vals2,0,14) def test_fresnelc_zeros(self): szo, czo = special.fresnel_zeros(6) frc = special.fresnelc_zeros(6) assert_array_almost_equal(frc,czo,12) def test_fresnels_zeros(self): szo, czo = special.fresnel_zeros(5) frs = special.fresnels_zeros(5) assert_array_almost_equal(frs,szo,12) class TestGamma(object): def test_gamma(self): gam = special.gamma(5) assert_equal(gam,24.0) def test_gammaln(self): gamln = special.gammaln(3) lngam = log(special.gamma(3)) assert_almost_equal(gamln,lngam,8) def test_gammainccinv(self): gccinv = special.gammainccinv(.5,.5) gcinv = special.gammaincinv(.5,.5) assert_almost_equal(gccinv,gcinv,8) @with_special_errors def test_gammaincinv(self): y = special.gammaincinv(.4,.4) x = special.gammainc(.4,y) assert_almost_equal(x,0.4,1) y = special.gammainc(10, 0.05) x = special.gammaincinv(10, 2.5715803516000736e-20) assert_almost_equal(0.05, x, decimal=10) assert_almost_equal(y, 2.5715803516000736e-20, decimal=10) x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18) assert_almost_equal(11.0, x, decimal=10) @with_special_errors def test_975(self): # Regression test for ticket #975 -- switch point in algorithm # check that things work OK at the point, immediately next floats # around it, and a bit further away pts = [0.25, np.nextafter(0.25, 0), 0.25 - 1e-12, np.nextafter(0.25, 1), 0.25 + 1e-12] for xp in pts: y = special.gammaincinv(.4, xp) x = special.gammainc(0.4, y) assert_allclose(x, xp, rtol=1e-12) def test_rgamma(self): rgam = special.rgamma(8) rlgam = 1/special.gamma(8) assert_almost_equal(rgam,rlgam,8) def test_infinity(self): assert_(np.isinf(special.gamma(-1))) assert_equal(special.rgamma(-1), 0) class TestHankel(object): def test_negv1(self): assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14) def test_hankel1(self): hank1 = special.hankel1(1,.1) hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j) assert_almost_equal(hank1,hankrl,8) def test_negv1e(self): assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14) def test_hankel1e(self): hank1e = special.hankel1e(1,.1) hankrle = special.hankel1(1,.1)*exp(-.1j) assert_almost_equal(hank1e,hankrle,8) def test_negv2(self): assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14) def test_hankel2(self): hank2 = special.hankel2(1,.1) hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j) assert_almost_equal(hank2,hankrl2,8) def test_neg2e(self): assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14) def test_hankl2e(self): hank2e = special.hankel2e(1,.1) hankrl2e = special.hankel2e(1,.1) assert_almost_equal(hank2e,hankrl2e,8) class TestHyper(object): def test_h1vp(self): h1 = special.h1vp(1,.1) h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j) assert_almost_equal(h1,h1real,8) def test_h2vp(self): h2 = special.h2vp(1,.1) h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j) assert_almost_equal(h2,h2real,8) def test_hyp0f1(self): # scalar input assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12) assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15) # float input, expected values match mpmath x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5]) expected = np.array([0.58493659229143, 0.70566805723127, 1.0, 1.37789689539747, 1.60373685288480]) assert_allclose(x, expected, rtol=1e-12) # complex input x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j) assert_allclose(x, expected.astype(complex), rtol=1e-12) # test broadcasting x1 = [0.5, 1.5, 2.5] x2 = [0, 1, 0.5] x = special.hyp0f1(x1, x2) expected = [1.0, 1.8134302039235093, 1.21482702689997] assert_allclose(x, expected, rtol=1e-12) x = special.hyp0f1(np.row_stack([x1] * 2), x2) assert_allclose(x, np.row_stack([expected] * 2), rtol=1e-12) assert_raises(ValueError, special.hyp0f1, np.row_stack([x1] * 3), [0, 1]) def test_hyp0f1_gh5764(self): # Just checks the point that failed; there's a more systematic # test in test_mpmath res = special.hyp0f1(0.8, 0.5 + 0.5*1J) # The expected value was generated using mpmath assert_almost_equal(res, 1.6139719776441115 + 1J*0.80893054061790665) def test_hyp1f1(self): hyp1 = special.hyp1f1(.1,.1,.3) assert_almost_equal(hyp1, 1.3498588075760032,7) # test contributed by Moritz Deger (2008-05-29) # https://github.com/scipy/scipy/issues/1186 (Trac #659) # reference data obtained from mathematica [ a, b, x, m(a,b,x)]: # produced with test_hyp1f1.nb ref_data = array([[-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04], [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00], [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05], [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08], [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24], [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21], [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13], [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13], [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02], [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10], [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01], [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21], [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20], [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07], [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03], [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02], [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11], [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03], [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17], [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01], [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00], [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00], [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23], [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01], [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04], [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08], [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01], [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07], [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03], [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09], [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06], [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00], [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01], [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02], [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02], [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02], [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00], [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09], [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01], [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00], [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02], [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05], [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05], [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02], [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02], [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13], [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05], [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12], [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01], [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16], [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37], [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06], [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02], [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12], [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27], [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04], [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06], [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07], [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03], [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07], [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27], [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12], [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32], [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04], [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01], [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02], [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19], [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09], [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31], [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01], [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02], [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08], [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09], [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33], [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01], [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29], [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01], [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29], [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02], [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00], [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08], [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01], [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01], [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01], [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13], [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11], [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02], [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02], [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01], [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31], [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04], [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25], [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01], [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00], [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02], [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05], [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02], [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01], [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01], [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00]]) for a,b,c,expected in ref_data: result = special.hyp1f1(a,b,c) assert_(abs(expected - result)/expected < 1e-4) def test_hyp1f1_gh2957(self): hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933) hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934) assert_almost_equal(hyp1, hyp2, 12) def test_hyp1f1_gh2282(self): hyp = special.hyp1f1(0.5, 1.5, -1000) assert_almost_equal(hyp, 0.028024956081989643, 12) def test_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], [3, 4, 8, 1, special.gamma(8)*special.gamma(8-4-3)/special.gamma(8-3)/special.gamma(8-4)], [3, 2, 3-2+1, -1, 1./2**3*sqrt(pi) * special.gamma(1+3-2)/special.gamma(1+0.5*3-2)/special.gamma(0.5+0.5*3)], [5, 2, 5-2+1, -1, 1./2**5*sqrt(pi) * special.gamma(1+5-2)/special.gamma(1+0.5*5-2)/special.gamma(0.5+0.5*5)], [4, 0.5+4, 1.5-2*4, -1./3, (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4)/special.gamma(3./2)/special.gamma(4./3-2*4)], # and some others # ticket #424 [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484], # negative integer a or b, with c-a-b integer and x > 0.9 [-2,3,1,0.95,0.715], [2,-3,1,0.95,-0.007], [-6,3,1,0.95,0.0000810625], [2,-5,1,0.95,-0.000029375], # huge negative integers (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24), (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18), ] for i, (a, b, c, x, v) in enumerate(values): cv = special.hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_hyperu(self): val1 = special.hyperu(1,0.1,100) assert_almost_equal(val1,0.0098153,7) a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] a,b = asarray(a), asarray(b) z = 0.5 hypu = special.hyperu(a,b,z) hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) / (special.gamma(1+a-b)*special.gamma(b)) - z**(1-b)*special.hyp1f1(1+a-b,2-b,z) / (special.gamma(a)*special.gamma(2-b))) assert_array_almost_equal(hypu,hprl,12) def test_hyperu_gh2287(self): assert_almost_equal(special.hyperu(1, 1.5, 20.2), 0.048360918656699191, 12) class TestBessel(object): def test_itj0y0(self): it0 = array(special.itj0y0(.2)) assert_array_almost_equal(it0,array([0.19933433254006822, -0.34570883800412566]),8) def test_it2j0y0(self): it2 = array(special.it2j0y0(.2)) assert_array_almost_equal(it2,array([0.0049937546274601858, -0.43423067011231614]),8) def test_negv_iv(self): assert_equal(special.iv(3,2), special.iv(-3,2)) def test_j0(self): oz = special.j0(.1) ozr = special.jn(0,.1) assert_almost_equal(oz,ozr,8) def test_j1(self): o1 = special.j1(.1) o1r = special.jn(1,.1) assert_almost_equal(o1,o1r,8) def test_jn(self): jnnr = special.jn(1,.2) assert_almost_equal(jnnr,0.099500832639235995,8) def test_negv_jv(self): assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14) def test_jv(self): values = [[0, 0.1, 0.99750156206604002], [2./3, 1e-8, 0.3239028506761532e-5], [2./3, 1e-10, 0.1503423854873779e-6], [3.1, 1e-10, 0.1711956265409013e-32], [2./3, 4.0, -0.2325440850267039], ] for i, (v, x, y) in enumerate(values): yc = special.jv(v, x) assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) def test_negv_jve(self): assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14) def test_jve(self): jvexp = special.jve(1,.2) assert_almost_equal(jvexp,0.099500832639235995,8) jvexp1 = special.jve(1,.2+1j) z = .2+1j jvexpr = special.jv(1,z)*exp(-abs(z.imag)) assert_almost_equal(jvexp1,jvexpr,8) def test_jn_zeros(self): jn0 = special.jn_zeros(0,5) jn1 = special.jn_zeros(1,5) assert_array_almost_equal(jn0,array([2.4048255577, 5.5200781103, 8.6537279129, 11.7915344391, 14.9309177086]),4) assert_array_almost_equal(jn1,array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]),4) jn102 = special.jn_zeros(102,5) assert_allclose(jn102, array([110.89174935992040343, 117.83464175788308398, 123.70194191713507279, 129.02417238949092824, 134.00114761868422559]), rtol=1e-13) jn301 = special.jn_zeros(301,5) assert_allclose(jn301, array([313.59097866698830153, 323.21549776096288280, 331.22338738656748796, 338.39676338872084500, 345.03284233056064157]), rtol=1e-13) def test_jn_zeros_slow(self): jn0 = special.jn_zeros(0, 300) assert_allclose(jn0[260-1], 816.02884495068867280, rtol=1e-13) assert_allclose(jn0[280-1], 878.86068707124422606, rtol=1e-13) assert_allclose(jn0[300-1], 941.69253065317954064, rtol=1e-13) jn10 = special.jn_zeros(10, 300) assert_allclose(jn10[260-1], 831.67668514305631151, rtol=1e-13) assert_allclose(jn10[280-1], 894.51275095371316931, rtol=1e-13) assert_allclose(jn10[300-1], 957.34826370866539775, rtol=1e-13) jn3010 = special.jn_zeros(3010,5) assert_allclose(jn3010, array([3036.86590780927, 3057.06598526482, 3073.66360690272, 3088.37736494778, 3101.86438139042]), rtol=1e-8) def test_jnjnp_zeros(self): jn = special.jn def jnp(n, x): return (jn(n-1,x) - jn(n+1,x))/2 for nt in range(1, 30): z, n, m, t = special.jnjnp_zeros(nt) for zz, nn, tt in zip(z, n, t): if tt == 0: assert_allclose(jn(nn, zz), 0, atol=1e-6) elif tt == 1: assert_allclose(jnp(nn, zz), 0, atol=1e-6) else: raise AssertionError("Invalid t return for nt=%d" % nt) def test_jnp_zeros(self): jnp = special.jnp_zeros(1,5) assert_array_almost_equal(jnp, array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]),4) jnp = special.jnp_zeros(443,5) assert_allclose(special.jvp(443, jnp), 0, atol=1e-15) def test_jnyn_zeros(self): jnz = special.jnyn_zeros(1,5) assert_array_almost_equal(jnz,(array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]), array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]), array([2.19714, 5.42968, 8.59601, 11.74915, 14.89744]), array([3.68302, 6.94150, 10.12340, 13.28576, 16.44006])),5) def test_jvp(self): jvprim = special.jvp(2,2) jv0 = (special.jv(1,2)-special.jv(3,2))/2 assert_almost_equal(jvprim,jv0,10) def test_k0(self): ozk = special.k0(.1) ozkr = special.kv(0,.1) assert_almost_equal(ozk,ozkr,8) def test_k0e(self): ozke = special.k0e(.1) ozker = special.kve(0,.1) assert_almost_equal(ozke,ozker,8) def test_k1(self): o1k = special.k1(.1) o1kr = special.kv(1,.1) assert_almost_equal(o1k,o1kr,8) def test_k1e(self): o1ke = special.k1e(.1) o1ker = special.kve(1,.1) assert_almost_equal(o1ke,o1ker,8) def test_jacobi(self): a = 5*np.random.random() - 1 b = 5*np.random.random() - 1 P0 = special.jacobi(0,a,b) P1 = special.jacobi(1,a,b) P2 = special.jacobi(2,a,b) P3 = special.jacobi(3,a,b) assert_array_almost_equal(P0.c,[1],13) assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13) cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)] p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]] assert_array_almost_equal(P2.c,array(p2c)/8.0,13) cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3), 12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)] p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] assert_array_almost_equal(P3.c,array(p3c)/48.0,13) def test_kn(self): kn1 = special.kn(0,.2) assert_almost_equal(kn1,1.7527038555281462,8) def test_negv_kv(self): assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2)) def test_kv0(self): kv0 = special.kv(0,.2) assert_almost_equal(kv0, 1.7527038555281462, 10) def test_kv1(self): kv1 = special.kv(1,0.2) assert_almost_equal(kv1, 4.775972543220472, 10) def test_kv2(self): kv2 = special.kv(2,0.2) assert_almost_equal(kv2, 49.51242928773287, 10) def test_kn_largeorder(self): assert_allclose(special.kn(32, 1), 1.7516596664574289e+43) def test_kv_largearg(self): assert_equal(special.kv(0, 1e19), 0) def test_negv_kve(self): assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2)) def test_kve(self): kve1 = special.kve(0,.2) kv1 = special.kv(0,.2)*exp(.2) assert_almost_equal(kve1,kv1,8) z = .2+1j kve2 = special.kve(0,z) kv2 = special.kv(0,z)*exp(z) assert_almost_equal(kve2,kv2,8) def test_kvp_v0n1(self): z = 2.2 assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10) def test_kvp_n1(self): v = 3. z = 2.2 xc = -special.kv(v+1,z) + v/z*special.kv(v,z) x = special.kvp(v,z, n=1) assert_almost_equal(xc, x, 10) # this function (kvp) is broken def test_kvp_n2(self): v = 3. z = 2.2 xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z x = special.kvp(v, z, n=2) assert_almost_equal(xc, x, 10) def test_y0(self): oz = special.y0(.1) ozr = special.yn(0,.1) assert_almost_equal(oz,ozr,8) def test_y1(self): o1 = special.y1(.1) o1r = special.yn(1,.1) assert_almost_equal(o1,o1r,8) def test_y0_zeros(self): yo,ypo = special.y0_zeros(2) zo,zpo = special.y0_zeros(2,complex=1) all = r_[yo,zo] allval = r_[ypo,zpo] assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11) assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11) def test_y1_zeros(self): y1 = special.y1_zeros(1) assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) def test_y1p_zeros(self): y1p = special.y1p_zeros(1,complex=1) assert_array_almost_equal(y1p,(array([0.5768+0.904j]), array([-0.7635+0.5892j])),3) def test_yn_zeros(self): an = special.yn_zeros(4,2) assert_array_almost_equal(an,array([5.64515, 9.36162]),5) an = special.yn_zeros(443,5) assert_allclose(an, [450.13573091578090314, 463.05692376675001542, 472.80651546418663566, 481.27353184725625838, 488.98055964441374646], rtol=1e-15) def test_ynp_zeros(self): ao = special.ynp_zeros(0,2) assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6) ao = special.ynp_zeros(43,5) assert_allclose(special.yvp(43, ao), 0, atol=1e-15) ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-9) def test_ynp_zeros_large_order(self): ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-14) def test_yn(self): yn2n = special.yn(1,.2) assert_almost_equal(yn2n,-3.3238249881118471,8) def test_negv_yv(self): assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14) def test_yv(self): yv2 = special.yv(1,.2) assert_almost_equal(yv2,-3.3238249881118471,8) def test_negv_yve(self): assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14) def test_yve(self): yve2 = special.yve(1,.2) assert_almost_equal(yve2,-3.3238249881118471,8) yve2r = special.yv(1,.2+1j)*exp(-1) yve22 = special.yve(1,.2+1j) assert_almost_equal(yve22,yve2r,8) def test_yvp(self): yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0 yvp1 = special.yvp(2,.2) assert_array_almost_equal(yvp1,yvpr,10) def _cephes_vs_amos_points(self): """Yield points at which to compare Cephes implementation to AMOS""" # check several points, including large-amplitude ones for v in [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301]: for z in [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300, 10003]: yield v, z # check half-integers; these are problematic points at least # for cephes/iv for v in 0.5 + arange(-60, 60): yield v, 3.5 def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None): for v, z in self._cephes_vs_amos_points(): if skip is not None and skip(v, z): continue c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z) if np.isinf(c1): assert_(np.abs(c2) >= 1e300, (v, z)) elif np.isnan(c1): assert_(c2.imag != 0, (v, z)) else: assert_allclose(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol) if v == int(v): assert_allclose(c3, c2, err_msg=(v, z), rtol=rtol, atol=atol) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_jv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_yv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305) def test_yv_cephes_vs_amos_only_small_orders(self): skipper = lambda v, z: (abs(v) > 50) self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305, skip=skipper) def test_iv_cephes_vs_amos(self): olderr = np.seterr(all='ignore') try: self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305) finally: np.seterr(**olderr) @pytest.mark.slow def test_iv_cephes_vs_amos_mass_test(self): N = 1000000 np.random.seed(1) v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N) x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N) imsk = (np.random.randint(8, size=N) == 0) v[imsk] = v[imsk].astype(int) old_err = np.seterr(all='ignore') try: c1 = special.iv(v, x) c2 = special.iv(v, x+0j) # deal with differences in the inf and zero cutoffs c1[abs(c1) > 1e300] = np.inf c2[abs(c2) > 1e300] = np.inf c1[abs(c1) < 1e-300] = 0 c2[abs(c2) < 1e-300] = 0 dc = abs(c1/c2 - 1) dc[np.isnan(dc)] = 0 finally: np.seterr(**old_err) k = np.argmax(dc) # Most error apparently comes from AMOS and not our implementation; # there are some problems near integer orders there assert_(dc[k] < 2e-7, (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j))) def test_kv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305) self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305) def test_ticket_623(self): assert_allclose(special.jv(3, 4), 0.43017147387562193) assert_allclose(special.jv(301, 1300), 0.0183487151115275) assert_allclose(special.jv(301, 1296.0682), -0.0224174325312048) def test_ticket_853(self): """Negative-order Bessels""" # cephes assert_allclose(special.jv(-1, 1), -0.4400505857449335) assert_allclose(special.jv(-2, 1), 0.1149034849319005) assert_allclose(special.yv(-1, 1), 0.7812128213002887) assert_allclose(special.yv(-2, 1), -1.650682606816255) assert_allclose(special.iv(-1, 1), 0.5651591039924851) assert_allclose(special.iv(-2, 1), 0.1357476697670383) assert_allclose(special.kv(-1, 1), 0.6019072301972347) assert_allclose(special.kv(-2, 1), 1.624838898635178) assert_allclose(special.jv(-0.5, 1), 0.43109886801837607952) assert_allclose(special.yv(-0.5, 1), 0.6713967071418031) assert_allclose(special.iv(-0.5, 1), 1.231200214592967) assert_allclose(special.kv(-0.5, 1), 0.4610685044478945) # amos assert_allclose(special.jv(-1, 1+0j), -0.4400505857449335) assert_allclose(special.jv(-2, 1+0j), 0.1149034849319005) assert_allclose(special.yv(-1, 1+0j), 0.7812128213002887) assert_allclose(special.yv(-2, 1+0j), -1.650682606816255) assert_allclose(special.iv(-1, 1+0j), 0.5651591039924851) assert_allclose(special.iv(-2, 1+0j), 0.1357476697670383) assert_allclose(special.kv(-1, 1+0j), 0.6019072301972347) assert_allclose(special.kv(-2, 1+0j), 1.624838898635178) assert_allclose(special.jv(-0.5, 1+0j), 0.43109886801837607952) assert_allclose(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j) assert_allclose(special.yv(-0.5, 1+0j), 0.6713967071418031) assert_allclose(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j) assert_allclose(special.iv(-0.5, 1+0j), 1.231200214592967) assert_allclose(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j) assert_allclose(special.kv(-0.5, 1+0j), 0.4610685044478945) assert_allclose(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j) assert_allclose(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3)) assert_allclose(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j)) assert_allclose(special.hankel1(-0.5, 1+1j), special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j)) assert_allclose(special.hankel2(-0.5, 1+1j), special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j)) def test_ticket_854(self): """Real-valued Bessel domains""" assert_(isnan(special.jv(0.5, -1))) assert_(isnan(special.iv(0.5, -1))) assert_(isnan(special.yv(0.5, -1))) assert_(isnan(special.yv(1, -1))) assert_(isnan(special.kv(0.5, -1))) assert_(isnan(special.kv(1, -1))) assert_(isnan(special.jve(0.5, -1))) assert_(isnan(special.ive(0.5, -1))) assert_(isnan(special.yve(0.5, -1))) assert_(isnan(special.yve(1, -1))) assert_(isnan(special.kve(0.5, -1))) assert_(isnan(special.kve(1, -1))) assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1)) assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1)) def test_gh_7909(self): assert_(special.kv(1.5, 0) == np.inf) assert_(special.kve(1.5, 0) == np.inf) def test_ticket_503(self): """Real-valued Bessel I overflow""" assert_allclose(special.iv(1, 700), 1.528500390233901e302) assert_allclose(special.iv(1000, 1120), 1.301564549405821e301) def test_iv_hyperg_poles(self): assert_allclose(special.iv(-0.5, 1), 1.231200214592967) def iv_series(self, v, z, n=200): k = arange(0, n).astype(float_) r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1) r[isnan(r)] = inf r = exp(r) err = abs(r).max() * finfo(float_).eps * n + abs(r[-1])*10 return r.sum(), err def test_i0_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(0, z) assert_allclose(special.i0(z), value, atol=err, err_msg=z) def test_i1_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(1, z) assert_allclose(special.i1(z), value, atol=err, err_msg=z) def test_iv_series(self): for v in [-20., -10., -1., 0., 1., 12.49, 120.]: for z in [1., 10., 200.5, -1+2j]: value, err = self.iv_series(v, z) assert_allclose(special.iv(v, z), value, atol=err, err_msg=(v, z)) def test_i0(self): values = [[0.0, 1.0], [1e-10, 1.0], [0.1, 0.9071009258], [0.5, 0.6450352706], [1.0, 0.4657596077], [2.5, 0.2700464416], [5.0, 0.1835408126], [20.0, 0.0897803119], ] for i, (x, v) in enumerate(values): cv = special.i0(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i0e(self): oize = special.i0e(.1) oizer = special.ive(0,.1) assert_almost_equal(oize,oizer,8) def test_i1(self): values = [[0.0, 0.0], [1e-10, 0.4999999999500000e-10], [0.1, 0.0452984468], [0.5, 0.1564208032], [1.0, 0.2079104154], [5.0, 0.1639722669], [20.0, 0.0875062222], ] for i, (x, v) in enumerate(values): cv = special.i1(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i1e(self): oi1e = special.i1e(.1) oi1er = special.ive(1,.1) assert_almost_equal(oi1e,oi1er,8) def test_iti0k0(self): iti0 = array(special.iti0k0(5)) assert_array_almost_equal(iti0,array([31.848667776169801, 1.5673873907283657]),5) def test_it2i0k0(self): it2k = special.it2i0k0(.1) assert_array_almost_equal(it2k,array([0.0012503906973464409, 3.3309450354686687]),6) def test_iv(self): iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(iv1,0.90710092578230106,10) def test_negv_ive(self): assert_equal(special.ive(3,2), special.ive(-3,2)) def test_ive(self): ive1 = special.ive(0,.1) iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(ive1,iv1,10) def test_ivp0(self): assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10) def test_ivp(self): y = (special.iv(0,2) + special.iv(2,2))/2 x = special.ivp(1,2) assert_almost_equal(x,y,10) class TestLaguerre(object): def test_laguerre(self): lag0 = special.laguerre(0) lag1 = special.laguerre(1) lag2 = special.laguerre(2) lag3 = special.laguerre(3) lag4 = special.laguerre(4) lag5 = special.laguerre(5) assert_array_almost_equal(lag0.c,[1],13) assert_array_almost_equal(lag1.c,[-1,1],13) assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13) assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13) assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) def test_genlaguerre(self): k = 5*np.random.random() - 0.9 lag0 = special.genlaguerre(0,k) lag1 = special.genlaguerre(1,k) lag2 = special.genlaguerre(2,k) lag3 = special.genlaguerre(3,k) assert_equal(lag0.c,[1]) assert_equal(lag1.c,[-1,k+1]) assert_almost_equal(lag2.c,array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0) assert_almost_equal(lag3.c,array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0) # Base polynomials come from Abrahmowitz and Stegan class TestLegendre(object): def test_legendre(self): leg0 = special.legendre(0) leg1 = special.legendre(1) leg2 = special.legendre(2) leg3 = special.legendre(3) leg4 = special.legendre(4) leg5 = special.legendre(5) assert_equal(leg0.c, [1]) assert_equal(leg1.c, [1,0]) assert_almost_equal(leg2.c, array([3,0,-1])/2.0, decimal=13) assert_almost_equal(leg3.c, array([5,0,-3,0])/2.0) assert_almost_equal(leg4.c, array([35,0,-30,0,3])/8.0) assert_almost_equal(leg5.c, array([63,0,-70,0,15,0])/8.0) class TestLambda(object): def test_lmbda(self): lam = special.lmbda(1,.1) lamr = (array([special.jn(0,.1), 2*special.jn(1,.1)/.1]), array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])) assert_array_almost_equal(lam,lamr,8) class TestLog1p(object): def test_log1p(self): l1p = (special.log1p(10), special.log1p(11), special.log1p(12)) l1prl = (log(11), log(12), log(13)) assert_array_almost_equal(l1p,l1prl,8) def test_log1pmore(self): l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2)) l1pmrl = (log(2),log(2.1),log(2.2)) assert_array_almost_equal(l1pm,l1pmrl,8) class TestLegendreFunctions(object): def test_clpmn(self): z = 0.5+0.3j clp = special.clpmn(2, 2, z, 3) assert_array_almost_equal(clp, (array([[1.0000, z, 0.5*(3*z*z-1)], [0.0000, sqrt(z*z-1), 3*z*sqrt(z*z-1)], [0.0000, 0.0000, 3*(z*z-1)]]), array([[0.0000, 1.0000, 3*z], [0.0000, z/sqrt(z*z-1), 3*(2*z*z-1)/sqrt(z*z-1)], [0.0000, 0.0000, 6*z]])), 7) def test_clpmn_close_to_real_2(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x), special.lpmv(m, n, x)]), 7) def test_clpmn_close_to_real_3(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi), special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]), 7) def test_clpmn_across_unit_circle(self): eps = 1e-7 m = 1 n = 1 x = 1j for type in [2, 3]: assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n], special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6) def test_inf(self): for z in (1, -1): for n in range(4): for m in range(1, n): lp = special.clpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) lp = special.lpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) def test_deriv_clpmn(self): # data inside and outside of the unit circle zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j, 1+1j, -1+1j, -1-1j, 1-1j] m = 2 n = 3 for type in [2, 3]: for z in zvals: for h in [1e-3, 1e-3j]: approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0] - special.clpmn(m, n, z-0.5*h, type)[0])/h assert_allclose(special.clpmn(m, n, z, type)[1], approx_derivative, rtol=1e-4) def test_lpmn(self): lp = special.lpmn(0,2,.5) assert_array_almost_equal(lp,(array([[1.00000, 0.50000, -0.12500]]), array([[0.00000, 1.00000, 1.50000]])),4) def test_lpn(self): lpnf = special.lpn(2,.5) assert_array_almost_equal(lpnf,(array([1.00000, 0.50000, -0.12500]), array([0.00000, 1.00000, 1.50000])),4) def test_lpmv(self): lp = special.lpmv(0,2,.5) assert_almost_equal(lp,-0.125,7) lp = special.lpmv(0,40,.001) assert_almost_equal(lp,0.1252678976534484,7) # XXX: this is outside the domain of the current implementation, # so ensure it returns a NaN rather than a wrong answer. olderr = np.seterr(all='ignore') try: lp = special.lpmv(-1,-1,.001) finally: np.seterr(**olderr) assert_(lp != 0 or np.isnan(lp)) def test_lqmn(self): lqmnf = special.lqmn(0,2,.5) lqf = special.lqn(2,.5) assert_array_almost_equal(lqmnf[0][0],lqf[0],4) assert_array_almost_equal(lqmnf[1][0],lqf[1],4) def test_lqmn_gt1(self): """algorithm for real arguments changes at 1.0001 test against analytical result for m=2, n=1 """ x0 = 1.0001 delta = 0.00002 for x in (x0-delta, x0+delta): lq = special.lqmn(2, 1, x)[0][-1, -1] expected = 2/(x*x-1) assert_almost_equal(lq, expected) def test_lqmn_shape(self): a, b = special.lqmn(4, 4, 1.1) assert_equal(a.shape, (5, 5)) assert_equal(b.shape, (5, 5)) a, b = special.lqmn(4, 0, 1.1) assert_equal(a.shape, (5, 1)) assert_equal(b.shape, (5, 1)) def test_lqn(self): lqf = special.lqn(2,.5) assert_array_almost_equal(lqf,(array([0.5493, -0.7253, -0.8187]), array([1.3333, 1.216, -0.8427])),4) class TestMathieu(object): def test_mathieu_a(self): pass def test_mathieu_even_coef(self): special.mathieu_even_coef(2,5) # Q not defined broken and cannot figure out proper reporting order def test_mathieu_odd_coef(self): # same problem as above pass class TestFresnelIntegral(object): def test_modfresnelp(self): pass def test_modfresnelm(self): pass class TestOblCvSeq(object): def test_obl_cv_seq(self): obl = special.obl_cv_seq(0,3,1) assert_array_almost_equal(obl,array([-0.348602, 1.393206, 5.486800, 11.492120]),5) class TestParabolicCylinder(object): def test_pbdn_seq(self): pb = special.pbdn_seq(1,.1) assert_array_almost_equal(pb,(array([0.9975, 0.0998]), array([-0.0499, 0.9925])),4) def test_pbdv(self): special.pbdv(1,.2) 1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0] def test_pbdv_seq(self): pbn = special.pbdn_seq(1,.1) pbv = special.pbdv_seq(1,.1) assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) def test_pbdv_points(self): # simple case eta = np.linspace(-10, 10, 5) z = 2**(eta/2)*np.sqrt(np.pi)/special.gamma(.5-.5*eta) assert_allclose(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14) # some points assert_allclose(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12) assert_allclose(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12) def test_pbdv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbdv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) def test_pbvv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbvv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) class TestPolygamma(object): # from Table 6.2 (pg. 271) of A&S def test_polygamma(self): poly2 = special.polygamma(2,1) poly3 = special.polygamma(3,1) assert_almost_equal(poly2,-2.4041138063,10) assert_almost_equal(poly3,6.4939394023,10) # Test polygamma(0, x) == psi(x) x = [2, 3, 1.1e14] assert_almost_equal(special.polygamma(0, x), special.psi(x)) # Test broadcasting n = [0, 1, 2] x = [0.5, 1.5, 2.5] expected = [-1.9635100260214238, 0.93480220054467933, -0.23620405164172739] assert_almost_equal(special.polygamma(n, x), expected) expected = np.row_stack([expected]*2) assert_almost_equal(special.polygamma(n, np.row_stack([x]*2)), expected) assert_almost_equal(special.polygamma(np.row_stack([n]*2), x), expected) class TestProCvSeq(object): def test_pro_cv_seq(self): prol = special.pro_cv_seq(0,3,1) assert_array_almost_equal(prol,array([0.319000, 2.593084, 6.533471, 12.514462]),5) class TestPsi(object): def test_psi(self): ps = special.psi(1) assert_almost_equal(ps,-0.57721566490153287,8) class TestRadian(object): def test_radian(self): rad = special.radian(90,0,0) assert_almost_equal(rad,pi/2.0,5) def test_radianmore(self): rad1 = special.radian(90,1,60) assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) class TestRiccati(object): def test_riccati_jn(self): N, x = 2, 0.2 S = np.empty((N, N)) for n in range(N): j = special.spherical_jn(n, x) jp = special.spherical_jn(n, x, derivative=True) S[0,n] = x*j S[1,n] = x*jp + j assert_array_almost_equal(S, special.riccati_jn(n, x), 8) def test_riccati_yn(self): N, x = 2, 0.2 C = np.empty((N, N)) for n in range(N): y = special.spherical_yn(n, x) yp = special.spherical_yn(n, x, derivative=True) C[0,n] = x*y C[1,n] = x*yp + y assert_array_almost_equal(C, special.riccati_yn(n, x), 8) class TestRound(object): def test_round(self): rnd = list(map(int,(special.round(10.1),special.round(10.4),special.round(10.5),special.round(10.6)))) # Note: According to the documentation, scipy.special.round is # supposed to round to the nearest even number if the fractional # part is exactly 0.5. On some platforms, this does not appear # to work and thus this test may fail. However, this unit test is # correctly written. rndrl = (10,10,10,11) assert_array_equal(rnd,rndrl) def test_sph_harm(): # Tests derived from tables in # https://en.wikipedia.org/wiki/Table_of_spherical_harmonics sh = special.sph_harm pi = np.pi exp = np.exp sqrt = np.sqrt sin = np.sin cos = np.cos assert_array_almost_equal(sh(0,0,0,0), 0.5/sqrt(pi)) assert_array_almost_equal(sh(-2,2,0.,pi/4), 0.25*sqrt(15./(2.*pi)) * (sin(pi/4))**2.) assert_array_almost_equal(sh(-2,2,0.,pi/2), 0.25*sqrt(15./(2.*pi))) assert_array_almost_equal(sh(2,2,pi,pi/2), 0.25*sqrt(15/(2.*pi)) * exp(0+2.*pi*1j)*sin(pi/2.)**2.) assert_array_almost_equal(sh(2,4,pi/4.,pi/3.), (3./8.)*sqrt(5./(2.*pi)) * exp(0+2.*pi/4.*1j) * sin(pi/3.)**2. * (7.*cos(pi/3.)**2.-1)) assert_array_almost_equal(sh(4,4,pi/8.,pi/6.), (3./16.)*sqrt(35./(2.*pi)) * exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.) def test_sph_harm_ufunc_loop_selection(): # see https://github.com/scipy/scipy/issues/4895 dt = np.dtype(np.complex128) assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt) assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt) assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt) assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt) assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt) assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt) class TestStruve(object): def _series(self, v, z, n=100): """Compute Struve function & error estimate from its power series.""" k = arange(0, n) r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5) err = abs(r).max() * finfo(float_).eps * n return r.sum(), err def test_vs_series(self): """Check Struve function versus its power series""" for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]: for z in [1, 10, 19, 21, 30]: value, err = self._series(v, z) assert_allclose(special.struve(v, z), value, rtol=0, atol=err), (v, z) def test_some_values(self): assert_allclose(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7) assert_allclose(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8) assert_allclose(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12) assert_allclose(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11) assert_equal(special.struve(-12, -41), -special.struve(-12, 41)) assert_equal(special.struve(+12, -41), -special.struve(+12, 41)) assert_equal(special.struve(-11, -41), +special.struve(-11, 41)) assert_equal(special.struve(+11, -41), +special.struve(+11, 41)) assert_(isnan(special.struve(-7.1, -1))) assert_(isnan(special.struve(-10.1, -1))) def test_regression_679(self): """Regression test for #679""" assert_allclose(special.struve(-1.0, 20 - 1e-8), special.struve(-1.0, 20 + 1e-8)) assert_allclose(special.struve(-2.0, 20 - 1e-8), special.struve(-2.0, 20 + 1e-8)) assert_allclose(special.struve(-4.3, 20 - 1e-8), special.struve(-4.3, 20 + 1e-8)) def test_chi2_smalldf(): assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110) def test_ch2_inf(): assert_equal(special.chdtr(0.7,np.inf), 1.0) def test_chi2c_smalldf(): assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110) def test_chi2_inv_smalldf(): assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3) def test_agm_simple(): rtol = 1e-13 # Gauss's constant assert_allclose(1/special.agm(1, np.sqrt(2)), 0.834626841674073186, rtol=rtol) # These values were computed using Wolfram Alpha, with the # function ArithmeticGeometricMean[a, b]. agm13 = 1.863616783244897 agm15 = 2.604008190530940 agm35 = 3.936235503649555 assert_allclose(special.agm([[1], [3]], [1, 3, 5]), [[1, agm13, agm15], [agm13, 3, agm35]], rtol=rtol) # Computed by the iteration formula using mpmath, # with mpmath.mp.prec = 1000: agm12 = 1.4567910310469068 assert_allclose(special.agm(1, 2), agm12, rtol=rtol) assert_allclose(special.agm(2, 1), agm12, rtol=rtol) assert_allclose(special.agm(-1, -2), -agm12, rtol=rtol) assert_allclose(special.agm(24, 6), 13.458171481725614, rtol=rtol) assert_allclose(special.agm(13, 123456789.5), 11111458.498599306, rtol=rtol) assert_allclose(special.agm(1e30, 1), 2.229223055945383e+28, rtol=rtol) assert_allclose(special.agm(1e-22, 1), 0.030182566420169886, rtol=rtol) assert_allclose(special.agm(1e150, 1e180), 2.229223055945383e+178, rtol=rtol) assert_allclose(special.agm(1e180, 1e-150), 2.0634722510162677e+177, rtol=rtol) assert_allclose(special.agm(1e-150, 1e-170), 3.3112619670463756e-152, rtol=rtol) fi = np.finfo(1.0) assert_allclose(special.agm(fi.tiny, fi.max), 1.9892072050015473e+305, rtol=rtol) assert_allclose(special.agm(0.75*fi.max, fi.max), 1.564904312298045e+308, rtol=rtol) assert_allclose(special.agm(fi.tiny, 3*fi.tiny), 4.1466849866735005e-308, rtol=rtol) # zero, nan and inf cases. assert_equal(special.agm(0, 0), 0) assert_equal(special.agm(99, 0), 0) assert_equal(special.agm(-1, 10), np.nan) assert_equal(special.agm(0, np.inf), np.nan) assert_equal(special.agm(np.inf, 0), np.nan) assert_equal(special.agm(0, -np.inf), np.nan) assert_equal(special.agm(-np.inf, 0), np.nan) assert_equal(special.agm(np.inf, -np.inf), np.nan) assert_equal(special.agm(-np.inf, np.inf), np.nan) assert_equal(special.agm(1, np.nan), np.nan) assert_equal(special.agm(np.nan, -1), np.nan) assert_equal(special.agm(1, np.inf), np.inf) assert_equal(special.agm(np.inf, 1), np.inf) assert_equal(special.agm(-1, -np.inf), -np.inf) assert_equal(special.agm(-np.inf, -1), -np.inf) def test_legacy(): # Legacy behavior: truncating arguments to integers with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3)) assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3)) assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3)) assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3)) assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3)) assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3)) assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3)) assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3)) assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3)) @with_special_errors def test_error_raising(): assert_raises(special.SpecialFunctionError, special.iv, 1, 1e99j) def test_xlogy(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x*np.log(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float) z2 = np.r_[z1, [(0, 1j), (1, 1j)]] w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13) w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1]) assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13) def test_xlog1py(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x * np.log1p(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0), (1, 1e-30)], dtype=float) w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13) def test_entr(): def xfunc(x): if x < 0: return -np.inf else: return -special.xlogy(x, x) values = (0, 0.5, 1.0, np.inf) signs = [-1, 1] arr = [] for sgn, v in itertools.product(signs, values): arr.append(sgn * v) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z) assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13) def test_kl_div(): def xfunc(x, y): if x < 0 or y < 0 or (y == 0 and x != 0): # extension of natural domain to preserve convexity return np.inf elif np.isposinf(x) or np.isposinf(y): # limits within the natural domain return np.inf elif x == 0: return y else: return special.xlogy(x, x/y) - x + y values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13) def test_rel_entr(): def xfunc(x, y): if x > 0 and y > 0: return special.xlogy(x, x/y) elif x == 0 and y >= 0: return 0 else: return np.inf values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13) def test_huber(): assert_equal(special.huber(-1, 1.5), np.inf) assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5)) assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2)) def xfunc(delta, r): if delta < 0: return np.inf elif np.abs(r) < delta: return 0.5 * np.square(r) else: return delta * (np.abs(r) - 0.5 * delta) z = np.random.randn(10, 2) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13) def test_pseudo_huber(): def xfunc(delta, r): if delta < 0: return np.inf elif (not delta) or (not r): return 0 else: return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1) z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]]) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13)
aeklant/scipy
scipy/special/tests/test_basic.py
scipy/_lib/_threadsafety.py
import numpy as np from numpy import cos, sin, pi from numpy.testing import (assert_equal, assert_almost_equal, assert_allclose, assert_, suppress_warnings) from scipy.integrate import (quadrature, romberg, romb, newton_cotes, cumtrapz, quad, simps, fixed_quad) from scipy.integrate.quadrature import AccuracyWarning class TestFixedQuad(object): def test_scalar(self): n = 4 func = lambda x: x**(2*n - 1) expected = 1/(2*n) got, _ = fixed_quad(func, 0, 1, n=n) # quadrature exact for this input assert_allclose(got, expected, rtol=1e-12) def test_vector(self): n = 4 p = np.arange(1, 2*n) func = lambda x: x**p[:,None] expected = 1/(p + 1) got, _ = fixed_quad(func, 0, 1, n=n) assert_allclose(got, expected, rtol=1e-12) class TestQuadrature(object): def quad(self, x, a, b, args): raise NotImplementedError def test_quadrature(self): # Typical function with two extra arguments: def myfunc(x, n, z): # Bessel function integrand return cos(n*x-z*sin(x))/pi val, err = quadrature(myfunc, 0, pi, (2, 1.8)) table_val = 0.30614353532540296487 assert_almost_equal(val, table_val, decimal=7) def test_quadrature_rtol(self): def myfunc(x, n, z): # Bessel function integrand return 1e90 * cos(n*x-z*sin(x))/pi val, err = quadrature(myfunc, 0, pi, (2, 1.8), rtol=1e-10) table_val = 1e90 * 0.30614353532540296487 assert_allclose(val, table_val, rtol=1e-10) def test_quadrature_miniter(self): # Typical function with two extra arguments: def myfunc(x, n, z): # Bessel function integrand return cos(n*x-z*sin(x))/pi table_val = 0.30614353532540296487 for miniter in [5, 52]: val, err = quadrature(myfunc, 0, pi, (2, 1.8), miniter=miniter) assert_almost_equal(val, table_val, decimal=7) assert_(err < 1.0) def test_quadrature_single_args(self): def myfunc(x, n): return 1e90 * cos(n*x-1.8*sin(x))/pi val, err = quadrature(myfunc, 0, pi, args=2, rtol=1e-10) table_val = 1e90 * 0.30614353532540296487 assert_allclose(val, table_val, rtol=1e-10) def test_romberg(self): # Typical function with two extra arguments: def myfunc(x, n, z): # Bessel function integrand return cos(n*x-z*sin(x))/pi val = romberg(myfunc, 0, pi, args=(2, 1.8)) table_val = 0.30614353532540296487 assert_almost_equal(val, table_val, decimal=7) def test_romberg_rtol(self): # Typical function with two extra arguments: def myfunc(x, n, z): # Bessel function integrand return 1e19*cos(n*x-z*sin(x))/pi val = romberg(myfunc, 0, pi, args=(2, 1.8), rtol=1e-10) table_val = 1e19*0.30614353532540296487 assert_allclose(val, table_val, rtol=1e-10) def test_romb(self): assert_equal(romb(np.arange(17)), 128) def test_romb_gh_3731(self): # Check that romb makes maximal use of data points x = np.arange(2**4+1) y = np.cos(0.2*x) val = romb(y) val2, err = quad(lambda x: np.cos(0.2*x), x.min(), x.max()) assert_allclose(val, val2, rtol=1e-8, atol=0) # should be equal to romb with 2**k+1 samples with suppress_warnings() as sup: sup.filter(AccuracyWarning, "divmax .4. exceeded") val3 = romberg(lambda x: np.cos(0.2*x), x.min(), x.max(), divmax=4) assert_allclose(val, val3, rtol=1e-12, atol=0) def test_non_dtype(self): # Check that we work fine with functions returning float import math valmath = romberg(math.sin, 0, 1) expected_val = 0.45969769413185085 assert_almost_equal(valmath, expected_val, decimal=7) def test_newton_cotes(self): """Test the first few degrees, for evenly spaced points.""" n = 1 wts, errcoff = newton_cotes(n, 1) assert_equal(wts, n*np.array([0.5, 0.5])) assert_almost_equal(errcoff, -n**3/12.0) n = 2 wts, errcoff = newton_cotes(n, 1) assert_almost_equal(wts, n*np.array([1.0, 4.0, 1.0])/6.0) assert_almost_equal(errcoff, -n**5/2880.0) n = 3 wts, errcoff = newton_cotes(n, 1) assert_almost_equal(wts, n*np.array([1.0, 3.0, 3.0, 1.0])/8.0) assert_almost_equal(errcoff, -n**5/6480.0) n = 4 wts, errcoff = newton_cotes(n, 1) assert_almost_equal(wts, n*np.array([7.0, 32.0, 12.0, 32.0, 7.0])/90.0) assert_almost_equal(errcoff, -n**7/1935360.0) def test_newton_cotes2(self): """Test newton_cotes with points that are not evenly spaced.""" x = np.array([0.0, 1.5, 2.0]) y = x**2 wts, errcoff = newton_cotes(x) exact_integral = 8.0/3 numeric_integral = np.dot(wts, y) assert_almost_equal(numeric_integral, exact_integral) x = np.array([0.0, 1.4, 2.1, 3.0]) y = x**2 wts, errcoff = newton_cotes(x) exact_integral = 9.0 numeric_integral = np.dot(wts, y) assert_almost_equal(numeric_integral, exact_integral) def test_simps(self): y = np.arange(17) assert_equal(simps(y), 128) assert_equal(simps(y, dx=0.5), 64) assert_equal(simps(y, x=np.linspace(0, 4, 17)), 32) y = np.arange(4) x = 2**y assert_equal(simps(y, x=x, even='avg'), 13.875) assert_equal(simps(y, x=x, even='first'), 13.75) assert_equal(simps(y, x=x, even='last'), 14) class TestCumtrapz(object): def test_1d(self): x = np.linspace(-2, 2, num=5) y = x y_int = cumtrapz(y, x, initial=0) y_expected = [0., -1.5, -2., -1.5, 0.] assert_allclose(y_int, y_expected) y_int = cumtrapz(y, x, initial=None) assert_allclose(y_int, y_expected[1:]) def test_y_nd_x_nd(self): x = np.arange(3 * 2 * 4).reshape(3, 2, 4) y = x y_int = cumtrapz(y, x, initial=0) y_expected = np.array([[[0., 0.5, 2., 4.5], [0., 4.5, 10., 16.5]], [[0., 8.5, 18., 28.5], [0., 12.5, 26., 40.5]], [[0., 16.5, 34., 52.5], [0., 20.5, 42., 64.5]]]) assert_allclose(y_int, y_expected) # Try with all axes shapes = [(2, 2, 4), (3, 1, 4), (3, 2, 3)] for axis, shape in zip([0, 1, 2], shapes): y_int = cumtrapz(y, x, initial=3.45, axis=axis) assert_equal(y_int.shape, (3, 2, 4)) y_int = cumtrapz(y, x, initial=None, axis=axis) assert_equal(y_int.shape, shape) def test_y_nd_x_1d(self): y = np.arange(3 * 2 * 4).reshape(3, 2, 4) x = np.arange(4)**2 # Try with all axes ys_expected = ( np.array([[[4., 5., 6., 7.], [8., 9., 10., 11.]], [[40., 44., 48., 52.], [56., 60., 64., 68.]]]), np.array([[[2., 3., 4., 5.]], [[10., 11., 12., 13.]], [[18., 19., 20., 21.]]]), np.array([[[0.5, 5., 17.5], [4.5, 21., 53.5]], [[8.5, 37., 89.5], [12.5, 53., 125.5]], [[16.5, 69., 161.5], [20.5, 85., 197.5]]])) for axis, y_expected in zip([0, 1, 2], ys_expected): y_int = cumtrapz(y, x=x[:y.shape[axis]], axis=axis, initial=None) assert_allclose(y_int, y_expected) def test_x_none(self): y = np.linspace(-2, 2, num=5) y_int = cumtrapz(y) y_expected = [-1.5, -2., -1.5, 0.] assert_allclose(y_int, y_expected) y_int = cumtrapz(y, initial=1.23) y_expected = [1.23, -1.5, -2., -1.5, 0.] assert_allclose(y_int, y_expected) y_int = cumtrapz(y, dx=3) y_expected = [-4.5, -6., -4.5, 0.] assert_allclose(y_int, y_expected) y_int = cumtrapz(y, dx=3, initial=1.23) y_expected = [1.23, -4.5, -6., -4.5, 0.] assert_allclose(y_int, y_expected)
# this program corresponds to special.py ### Means test is not done yet # E Means test is giving error (E) # F Means test is failing (F) # EF Means test is giving error and Failing #! Means test is segfaulting # 8 Means test runs forever ### test_besselpoly ### test_mathieu_a ### test_mathieu_even_coef ### test_mathieu_odd_coef ### test_modfresnelp ### test_modfresnelm # test_pbdv_seq ### test_pbvv_seq ### test_sph_harm import itertools import platform import numpy as np from numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp, log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, float_) import pytest from pytest import raises as assert_raises from numpy.testing import (assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_approx_equal, assert_, assert_allclose, assert_array_almost_equal_nulp, suppress_warnings) from scipy import special import scipy.special._ufuncs as cephes from scipy.special import ellipk from scipy.special._testutils import with_special_errors, \ assert_func_equal, FuncData import math class TestCephes(object): def test_airy(self): cephes.airy(0) def test_airye(self): cephes.airye(0) def test_binom(self): n = np.array([0.264, 4, 5.2, 17]) k = np.array([2, 0.4, 7, 3.3]) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389, -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846], [10.92, 2.22993515861399, -0.00585728, 10.468891352063146], [136, 3.5252179590758828, 19448, 1024.5526916174495]]) assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13) # Test branches in implementation np.random.seed(1234) n = np.r_[np.arange(-7, 30), 1000*np.random.rand(30) - 500] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_2(self): # Test branches in implementation np.random.seed(1234) n = np.r_[np.logspace(1, 300, 20)] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_exact(self): @np.vectorize def binom_int(n, k): n = int(n) k = int(k) num = int(1) den = int(1) for i in range(1, k+1): num *= i + n - k den *= i return float(num/den) np.random.seed(1234) n = np.arange(1, 15) k = np.arange(0, 15) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T nk = nk[nk[:,0] >= nk[:,1]] assert_func_equal(cephes.binom, binom_int(nk[:,0], nk[:,1]), nk, atol=0, rtol=0) def test_binom_nooverflow_8346(self): # Test (binom(n, k) doesn't overflow prematurely */ dataset = [ (1000, 500, 2.70288240945436551e+299), (1002, 501, 1.08007396880791225e+300), (1004, 502, 4.31599279169058121e+300), (1006, 503, 1.72468101616263781e+301), (1008, 504, 6.89188009236419153e+301), (1010, 505, 2.75402257948335448e+302), (1012, 506, 1.10052048531923757e+303), (1014, 507, 4.39774063758732849e+303), (1016, 508, 1.75736486108312519e+304), (1018, 509, 7.02255427788423734e+304), (1020, 510, 2.80626776829962255e+305), (1022, 511, 1.12140876377061240e+306), (1024, 512, 4.48125455209897109e+306), (1026, 513, 1.79075474304149900e+307), (1028, 514, 7.15605105487789676e+307) ] dataset = np.asarray(dataset) FuncData(cephes.binom, dataset, (0, 1), 2, rtol=1e-12).check() def test_bdtr(self): assert_equal(cephes.bdtr(1,1,0.5),1.0) def test_bdtri(self): assert_equal(cephes.bdtri(1,3,0.5),0.5) def test_bdtrc(self): assert_equal(cephes.bdtrc(1,3,0.5),0.5) def test_bdtrin(self): assert_equal(cephes.bdtrin(1,0,1),5.0) def test_bdtrik(self): cephes.bdtrik(1,3,0.5) def test_bei(self): assert_equal(cephes.bei(0),0.0) def test_beip(self): assert_equal(cephes.beip(0),0.0) def test_ber(self): assert_equal(cephes.ber(0),1.0) def test_berp(self): assert_equal(cephes.berp(0),0.0) def test_besselpoly(self): assert_equal(cephes.besselpoly(0,0,0),1.0) def test_beta(self): assert_equal(cephes.beta(1,1),1.0) assert_allclose(cephes.beta(-100.3, 1e-200), cephes.gamma(1e-200)) assert_allclose(cephes.beta(0.0342, 171), 24.070498359873497, rtol=1e-13, atol=0) def test_betainc(self): assert_equal(cephes.betainc(1,1,1),1.0) assert_allclose(cephes.betainc(0.0342, 171, 1e-10), 0.55269916901806648) def test_betaln(self): assert_equal(cephes.betaln(1,1),0.0) assert_allclose(cephes.betaln(-100.3, 1e-200), cephes.gammaln(1e-200)) assert_allclose(cephes.betaln(0.0342, 170), 3.1811881124242447, rtol=1e-14, atol=0) def test_betaincinv(self): assert_equal(cephes.betaincinv(1,1,1),1.0) assert_allclose(cephes.betaincinv(0.0342, 171, 0.25), 8.4231316935498957e-21, rtol=3e-12, atol=0) def test_beta_inf(self): assert_(np.isinf(special.beta(-1, 2))) def test_btdtr(self): assert_equal(cephes.btdtr(1,1,1),1.0) def test_btdtri(self): assert_equal(cephes.btdtri(1,1,1),1.0) def test_btdtria(self): assert_equal(cephes.btdtria(1,1,1),5.0) def test_btdtrib(self): assert_equal(cephes.btdtrib(1,1,1),5.0) def test_cbrt(self): assert_approx_equal(cephes.cbrt(1),1.0) def test_chdtr(self): assert_equal(cephes.chdtr(1,0),0.0) def test_chdtrc(self): assert_equal(cephes.chdtrc(1,0),1.0) def test_chdtri(self): assert_equal(cephes.chdtri(1,1),0.0) def test_chdtriv(self): assert_equal(cephes.chdtriv(0,0),5.0) def test_chndtr(self): assert_equal(cephes.chndtr(0,1,0),0.0) # Each row holds (x, nu, lam, expected_value) # These values were computed using Wolfram Alpha with # CDF[NoncentralChiSquareDistribution[nu, lam], x] values = np.array([ [25.00, 20.0, 400, 4.1210655112396197139e-57], [25.00, 8.00, 250, 2.3988026526832425878e-29], [0.001, 8.00, 40., 5.3761806201366039084e-24], [0.010, 8.00, 40., 5.45396231055999457039e-20], [20.00, 2.00, 107, 1.39390743555819597802e-9], [22.50, 2.00, 107, 7.11803307138105870671e-9], [25.00, 2.00, 107, 3.11041244829864897313e-8], [3.000, 2.00, 1.0, 0.62064365321954362734], [350.0, 300., 10., 0.93880128006276407710], [100.0, 13.5, 10., 0.99999999650104210949], [700.0, 20.0, 400, 0.99999999925680650105], [150.0, 13.5, 10., 0.99999999999999983046], [160.0, 13.5, 10., 0.99999999999999999518], # 1.0 ]) cdf = cephes.chndtr(values[:, 0], values[:, 1], values[:, 2]) assert_allclose(cdf, values[:, 3], rtol=1e-12) assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0) assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0) assert_(np.isnan(cephes.chndtr(np.nan, 1, 2))) assert_(np.isnan(cephes.chndtr(5, np.nan, 2))) assert_(np.isnan(cephes.chndtr(5, 1, np.nan))) def test_chndtridf(self): assert_equal(cephes.chndtridf(0,0,1),5.0) def test_chndtrinc(self): assert_equal(cephes.chndtrinc(0,1,0),5.0) def test_chndtrix(self): assert_equal(cephes.chndtrix(0,1,0),0.0) def test_cosdg(self): assert_equal(cephes.cosdg(0),1.0) def test_cosm1(self): assert_equal(cephes.cosm1(0),0.0) def test_cotdg(self): assert_almost_equal(cephes.cotdg(45),1.0) def test_dawsn(self): assert_equal(cephes.dawsn(0),0.0) assert_allclose(cephes.dawsn(1.23), 0.50053727749081767) def test_diric(self): # Test behavior near multiples of 2pi. Regression test for issue # described in gh-4001. n_odd = [1, 5, 25] x = np.array(2*np.pi + 5e-5).astype(np.float32) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7) x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) x = np.array(2*np.pi + 1e-15).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) if hasattr(np, 'float128'): # No float128 available in 32-bit numpy x = np.array(2*np.pi + 1e-12).astype(np.float128) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19) n_even = [2, 4, 24] x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15) # Test at some values not near a multiple of pi x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi) octave_result = [0.872677996249965, 0.539344662916632, 0.127322003750035, -0.206011329583298] assert_almost_equal(special.diric(x, 3), octave_result, decimal=15) def test_diric_broadcasting(self): x = np.arange(5) n = np.array([1, 3, 7]) assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size)) def test_ellipe(self): assert_equal(cephes.ellipe(1),1.0) def test_ellipeinc(self): assert_equal(cephes.ellipeinc(0,1),0.0) def test_ellipj(self): cephes.ellipj(0,1) def test_ellipk(self): assert_allclose(ellipk(0), pi/2) def test_ellipkinc(self): assert_equal(cephes.ellipkinc(0,0),0.0) def test_erf(self): assert_equal(cephes.erf(0), 0.0) def test_erf_symmetry(self): x = 5.905732037710919 assert_equal(cephes.erf(x) + cephes.erf(-x), 0.0) def test_erfc(self): assert_equal(cephes.erfc(0), 1.0) def test_exp10(self): assert_approx_equal(cephes.exp10(2),100.0) def test_exp2(self): assert_equal(cephes.exp2(2),4.0) def test_expm1(self): assert_equal(cephes.expm1(0),0.0) assert_equal(cephes.expm1(np.inf), np.inf) assert_equal(cephes.expm1(-np.inf), -1) assert_equal(cephes.expm1(np.nan), np.nan) def test_expm1_complex(self): expm1 = cephes.expm1 assert_equal(expm1(0 + 0j), 0 + 0j) assert_equal(expm1(complex(np.inf, 0)), complex(np.inf, 0)) assert_equal(expm1(complex(np.inf, 1)), complex(np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 2)), complex(-np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 4)), complex(-np.inf, -np.inf)) assert_equal(expm1(complex(np.inf, 5)), complex(np.inf, -np.inf)) assert_equal(expm1(complex(1, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(0, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.inf, np.inf)), complex(np.inf, np.nan)) assert_equal(expm1(complex(-np.inf, np.inf)), complex(-1, 0)) assert_equal(expm1(complex(-np.inf, np.nan)), complex(-1, 0)) assert_equal(expm1(complex(np.inf, np.nan)), complex(np.inf, np.nan)) assert_equal(expm1(complex(0, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(1, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, 1)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, np.nan)), complex(np.nan, np.nan)) @pytest.mark.xfail(reason='The real part of expm1(z) bad at these points') def test_expm1_complex_hard(self): # The real part of this function is difficult to evaluate when # z.real = -log(cos(z.imag)). y = np.array([0.1, 0.2, 0.3, 5, 11, 20]) x = -np.log(np.cos(y)) z = x + 1j*y # evaluate using mpmath.expm1 with dps=1000 expected = np.array([-5.5507901846769623e-17+0.10033467208545054j, 2.4289354732893695e-18+0.20271003550867248j, 4.5235500262585768e-17+0.30933624960962319j, 7.8234305217489006e-17-3.3805150062465863j, -1.3685191953697676e-16-225.95084645419513j, 8.7175620481291045e-17+2.2371609442247422j]) found = cephes.expm1(z) # this passes. assert_array_almost_equal_nulp(found.imag, expected.imag, 3) # this fails. assert_array_almost_equal_nulp(found.real, expected.real, 20) def test_fdtr(self): assert_equal(cephes.fdtr(1, 1, 0), 0.0) # Computed using Wolfram Alpha: CDF[FRatioDistribution[1e-6, 5], 10] assert_allclose(cephes.fdtr(1e-6, 5, 10), 0.9999940790193488, rtol=1e-12) def test_fdtrc(self): assert_equal(cephes.fdtrc(1, 1, 0), 1.0) # Computed using Wolfram Alpha: # 1 - CDF[FRatioDistribution[2, 1/10], 1e10] assert_allclose(cephes.fdtrc(2, 0.1, 1e10), 0.27223784621293512, rtol=1e-12) def test_fdtri(self): assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]), array([0.9937365, 1.00630298]), rtol=1e-6) # From Wolfram Alpha: # CDF[FRatioDistribution[1/10, 1], 3] = 0.8756751669632105666874... p = 0.8756751669632105666874 assert_allclose(cephes.fdtri(0.1, 1, p), 3, rtol=1e-12) @pytest.mark.xfail(reason='Returns nan on i686.') def test_fdtri_mysterious_failure(self): assert_allclose(cephes.fdtri(1, 1, 0.5), 1) def test_fdtridfd(self): assert_equal(cephes.fdtridfd(1,0,0),5.0) def test_fresnel(self): assert_equal(cephes.fresnel(0),(0.0,0.0)) def test_gamma(self): assert_equal(cephes.gamma(5),24.0) def test_gammainccinv(self): assert_equal(cephes.gammainccinv(5,1),0.0) def test_gammaln(self): cephes.gammaln(10) def test_gammasgn(self): vals = np.array([-4, -3.5, -2.3, 1, 4.2], np.float64) assert_array_equal(cephes.gammasgn(vals), np.sign(cephes.rgamma(vals))) def test_gdtr(self): assert_equal(cephes.gdtr(1,1,0),0.0) def test_gdtr_inf(self): assert_equal(cephes.gdtr(1,1,np.inf),1.0) def test_gdtrc(self): assert_equal(cephes.gdtrc(1,1,0),1.0) def test_gdtria(self): assert_equal(cephes.gdtria(0,1,1),0.0) def test_gdtrib(self): cephes.gdtrib(1,0,1) # assert_equal(cephes.gdtrib(1,0,1),5.0) def test_gdtrix(self): cephes.gdtrix(1,1,.1) def test_hankel1(self): cephes.hankel1(1,1) def test_hankel1e(self): cephes.hankel1e(1,1) def test_hankel2(self): cephes.hankel2(1,1) def test_hankel2e(self): cephes.hankel2e(1,1) def test_hyp1f1(self): assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) cephes.hyp1f1(1,1,1) def test_hyp2f1(self): assert_equal(cephes.hyp2f1(1,1,1,0),1.0) def test_i0(self): assert_equal(cephes.i0(0),1.0) def test_i0e(self): assert_equal(cephes.i0e(0),1.0) def test_i1(self): assert_equal(cephes.i1(0),0.0) def test_i1e(self): assert_equal(cephes.i1e(0),0.0) def test_it2i0k0(self): cephes.it2i0k0(1) def test_it2j0y0(self): cephes.it2j0y0(1) def test_it2struve0(self): cephes.it2struve0(1) def test_itairy(self): cephes.itairy(1) def test_iti0k0(self): assert_equal(cephes.iti0k0(0),(0.0,0.0)) def test_itj0y0(self): assert_equal(cephes.itj0y0(0),(0.0,0.0)) def test_itmodstruve0(self): assert_equal(cephes.itmodstruve0(0),0.0) def test_itstruve0(self): assert_equal(cephes.itstruve0(0),0.0) def test_iv(self): assert_equal(cephes.iv(1,0),0.0) def _check_ive(self): assert_equal(cephes.ive(1,0),0.0) def test_j0(self): assert_equal(cephes.j0(0),1.0) def test_j1(self): assert_equal(cephes.j1(0),0.0) def test_jn(self): assert_equal(cephes.jn(0,0),1.0) def test_jv(self): assert_equal(cephes.jv(0,0),1.0) def _check_jve(self): assert_equal(cephes.jve(0,0),1.0) def test_k0(self): cephes.k0(2) def test_k0e(self): cephes.k0e(2) def test_k1(self): cephes.k1(2) def test_k1e(self): cephes.k1e(2) def test_kei(self): cephes.kei(2) def test_keip(self): assert_equal(cephes.keip(0),0.0) def test_ker(self): cephes.ker(2) def test_kerp(self): cephes.kerp(2) def _check_kelvin(self): cephes.kelvin(2) def test_kn(self): cephes.kn(1,1) def test_kolmogi(self): assert_equal(cephes.kolmogi(1),0.0) assert_(np.isnan(cephes.kolmogi(np.nan))) def test_kolmogorov(self): assert_equal(cephes.kolmogorov(0), 1.0) def test_kolmogp(self): assert_equal(cephes._kolmogp(0), -0.0) def test_kolmogc(self): assert_equal(cephes._kolmogc(0), 0.0) def test_kolmogci(self): assert_equal(cephes._kolmogci(0), 0.0) assert_(np.isnan(cephes._kolmogci(np.nan))) def _check_kv(self): cephes.kv(1,1) def _check_kve(self): cephes.kve(1,1) def test_log1p(self): log1p = cephes.log1p assert_equal(log1p(0), 0.0) assert_equal(log1p(-1), -np.inf) assert_equal(log1p(-2), np.nan) assert_equal(log1p(np.inf), np.inf) def test_log1p_complex(self): log1p = cephes.log1p c = complex assert_equal(log1p(0 + 0j), 0 + 0j) assert_equal(log1p(c(-1, 0)), c(-np.inf, 0)) with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in multiply") assert_allclose(log1p(c(1, np.inf)), c(np.inf, np.pi/2)) assert_equal(log1p(c(1, np.nan)), c(np.nan, np.nan)) assert_allclose(log1p(c(-np.inf, 1)), c(np.inf, np.pi)) assert_equal(log1p(c(np.inf, 1)), c(np.inf, 0)) assert_allclose(log1p(c(-np.inf, np.inf)), c(np.inf, 3*np.pi/4)) assert_allclose(log1p(c(np.inf, np.inf)), c(np.inf, np.pi/4)) assert_equal(log1p(c(np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(-np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, np.inf)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, 1)), c(np.nan, np.nan)) assert_equal(log1p(c(np.nan, np.nan)), c(np.nan, np.nan)) def test_lpmv(self): assert_equal(cephes.lpmv(0,0,1),1.0) def test_mathieu_a(self): assert_equal(cephes.mathieu_a(1,0),1.0) def test_mathieu_b(self): assert_equal(cephes.mathieu_b(1,0),1.0) def test_mathieu_cem(self): assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) # Test AMS 20.2.27 @np.vectorize def ce_smallq(m, q, z): z *= np.pi/180 if m == 0: return 2**(-0.5) * (1 - .5*q*cos(2*z)) # + O(q^2) elif m == 1: return cos(z) - q/8 * cos(3*z) # + O(q^2) elif m == 2: return cos(2*z) - q*(cos(4*z)/12 - 1/4) # + O(q^2) else: return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(0, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0], ce_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_sem(self): assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) # Test AMS 20.2.27 @np.vectorize def se_smallq(m, q, z): z *= np.pi/180 if m == 1: return sin(z) - q/8 * sin(3*z) # + O(q^2) elif m == 2: return sin(2*z) - q*sin(4*z)/12 # + O(q^2) else: return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(1, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0], se_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_modcem1(self): assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) def test_mathieu_modcem2(self): cephes.mathieu_modcem2(1,1,1) # Test reflection relation AMS 20.6.19 m = np.arange(0, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modcem2(m, q, -z)[0] fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0] y2 = -cephes.mathieu_modcem2(m, q, z)[0] - 2*fr*cephes.mathieu_modcem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_modsem1(self): assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) def test_mathieu_modsem2(self): cephes.mathieu_modsem2(1,1,1) # Test reflection relation AMS 20.6.20 m = np.arange(1, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modsem2(m, q, -z)[0] fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1] y2 = cephes.mathieu_modsem2(m, q, z)[0] - 2*fr*cephes.mathieu_modsem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_overflow(self): # Check that these return NaNs instead of causing a SEGV assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan)) def test_mathieu_ticket_1847(self): # Regression test --- this call had some out-of-bounds access # and could return nan occasionally for k in range(60): v = cephes.mathieu_modsem2(2, 100, -1) # Values from ACM TOMS 804 (derivate by numerical differentiation) assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10) assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4) def test_modfresnelm(self): cephes.modfresnelm(0) def test_modfresnelp(self): cephes.modfresnelp(0) def _check_modstruve(self): assert_equal(cephes.modstruve(1,0),0.0) def test_nbdtr(self): assert_equal(cephes.nbdtr(1,1,1),1.0) def test_nbdtrc(self): assert_equal(cephes.nbdtrc(1,1,1),0.0) def test_nbdtri(self): assert_equal(cephes.nbdtri(1,1,1),1.0) def __check_nbdtrik(self): cephes.nbdtrik(1,.4,.5) def test_nbdtrin(self): assert_equal(cephes.nbdtrin(1,0,0),5.0) def test_ncfdtr(self): assert_equal(cephes.ncfdtr(1,1,1,0),0.0) def test_ncfdtri(self): assert_equal(cephes.ncfdtri(1, 1, 1, 0), 0.0) f = [0.5, 1, 1.5] p = cephes.ncfdtr(2, 3, 1.5, f) assert_allclose(cephes.ncfdtri(2, 3, 1.5, p), f) def test_ncfdtridfd(self): dfd = [1, 2, 3] p = cephes.ncfdtr(2, dfd, 0.25, 15) assert_allclose(cephes.ncfdtridfd(2, p, 0.25, 15), dfd) def test_ncfdtridfn(self): dfn = [0.1, 1, 2, 3, 1e4] p = cephes.ncfdtr(dfn, 2, 0.25, 15) assert_allclose(cephes.ncfdtridfn(p, 2, 0.25, 15), dfn, rtol=1e-5) def test_ncfdtrinc(self): nc = [0.5, 1.5, 2.0] p = cephes.ncfdtr(2, 3, nc, 15) assert_allclose(cephes.ncfdtrinc(2, 3, p, 15), nc) def test_nctdtr(self): assert_equal(cephes.nctdtr(1,0,0),0.5) assert_equal(cephes.nctdtr(9, 65536, 45), 0.0) assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5) assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.))) assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.) assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.))) assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.))) assert_(np.isnan(cephes.nctdtr(2., 1., np.nan))) def __check_nctdtridf(self): cephes.nctdtridf(1,0.5,0) def test_nctdtrinc(self): cephes.nctdtrinc(1,0,0) def test_nctdtrit(self): cephes.nctdtrit(.1,0.2,.5) def test_nrdtrimn(self): assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) def test_nrdtrisd(self): assert_allclose(cephes.nrdtrisd(0.5,0.5,0.5), 0.0, atol=0, rtol=0) def test_obl_ang1(self): cephes.obl_ang1(1,1,1,0) def test_obl_ang1_cv(self): result = cephes.obl_ang1_cv(1,1,1,1,0) assert_almost_equal(result[0],1.0) assert_almost_equal(result[1],0.0) def _check_obl_cv(self): assert_equal(cephes.obl_cv(1,1,0),2.0) def test_obl_rad1(self): cephes.obl_rad1(1,1,1,0) def test_obl_rad1_cv(self): cephes.obl_rad1_cv(1,1,1,1,0) def test_obl_rad2(self): cephes.obl_rad2(1,1,1,0) def test_obl_rad2_cv(self): cephes.obl_rad2_cv(1,1,1,1,0) def test_pbdv(self): assert_equal(cephes.pbdv(1,0),(0.0,1.0)) def test_pbvv(self): cephes.pbvv(1,0) def test_pbwa(self): cephes.pbwa(1,0) def test_pdtr(self): val = cephes.pdtr(0, 1) assert_almost_equal(val, np.exp(-1)) # Edge case: m = 0. val = cephes.pdtr([0, 1, 2], 0) assert_array_equal(val, [1, 1, 1]) def test_pdtrc(self): val = cephes.pdtrc(0, 1) assert_almost_equal(val, 1 - np.exp(-1)) # Edge case: m = 0. val = cephes.pdtrc([0, 1, 2], 0.0) assert_array_equal(val, [0, 0, 0]) def test_pdtri(self): with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") cephes.pdtri(0.5,0.5) def test_pdtrik(self): k = cephes.pdtrik(0.5, 1) assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5) # Edge case: m = 0 or very small. k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6]) assert_array_equal(k, np.zeros((3, 3))) def test_pro_ang1(self): cephes.pro_ang1(1,1,1,0) def test_pro_ang1_cv(self): assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), array((1.0,0.0))) def _check_pro_cv(self): assert_equal(cephes.pro_cv(1,1,0),2.0) def test_pro_rad1(self): cephes.pro_rad1(1,1,1,0.1) def test_pro_rad1_cv(self): cephes.pro_rad1_cv(1,1,1,1,0) def test_pro_rad2(self): cephes.pro_rad2(1,1,1,0) def test_pro_rad2_cv(self): cephes.pro_rad2_cv(1,1,1,1,0) def test_psi(self): cephes.psi(1) def test_radian(self): assert_equal(cephes.radian(0,0,0),0) def test_rgamma(self): assert_equal(cephes.rgamma(1),1.0) def test_round(self): assert_equal(cephes.round(3.4),3.0) assert_equal(cephes.round(-3.4),-3.0) assert_equal(cephes.round(3.6),4.0) assert_equal(cephes.round(-3.6),-4.0) assert_equal(cephes.round(3.5),4.0) assert_equal(cephes.round(-3.5),-4.0) def test_shichi(self): cephes.shichi(1) def test_sici(self): cephes.sici(1) s, c = cephes.sici(np.inf) assert_almost_equal(s, np.pi * 0.5) assert_almost_equal(c, 0) s, c = cephes.sici(-np.inf) assert_almost_equal(s, -np.pi * 0.5) assert_(np.isnan(c), "cosine integral(-inf) is not nan") def test_sindg(self): assert_equal(cephes.sindg(90),1.0) def test_smirnov(self): assert_equal(cephes.smirnov(1,.1),0.9) assert_(np.isnan(cephes.smirnov(1,np.nan))) def test_smirnovp(self): assert_equal(cephes._smirnovp(1, .1), -1) assert_equal(cephes._smirnovp(2, 0.75), -2*(0.25)**(2-1)) assert_equal(cephes._smirnovp(3, 0.75), -3*(0.25)**(3-1)) assert_(np.isnan(cephes._smirnovp(1, np.nan))) def test_smirnovc(self): assert_equal(cephes._smirnovc(1,.1),0.1) assert_(np.isnan(cephes._smirnovc(1,np.nan))) x10 = np.linspace(0, 1, 11, endpoint=True) assert_almost_equal(cephes._smirnovc(3, x10), 1-cephes.smirnov(3, x10)) x4 = np.linspace(0, 1, 5, endpoint=True) assert_almost_equal(cephes._smirnovc(4, x4), 1-cephes.smirnov(4, x4)) def test_smirnovi(self): assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) assert_(np.isnan(cephes.smirnovi(1,np.nan))) def test_smirnovci(self): assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.4)),0.4) assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.6)),0.6) assert_(np.isnan(cephes._smirnovci(1,np.nan))) def test_spence(self): assert_equal(cephes.spence(1),0.0) def test_stdtr(self): assert_equal(cephes.stdtr(1,0),0.5) assert_almost_equal(cephes.stdtr(1,1), 0.75) assert_almost_equal(cephes.stdtr(1,2), 0.852416382349) def test_stdtridf(self): cephes.stdtridf(0.7,1) def test_stdtrit(self): cephes.stdtrit(1,0.7) def test_struve(self): assert_equal(cephes.struve(0,0),0.0) def test_tandg(self): assert_equal(cephes.tandg(45),1.0) def test_tklmbda(self): assert_almost_equal(cephes.tklmbda(1,1),1.0) def test_y0(self): cephes.y0(1) def test_y1(self): cephes.y1(1) def test_yn(self): cephes.yn(1,1) def test_yv(self): cephes.yv(1,1) def _check_yve(self): cephes.yve(1,1) def test_wofz(self): z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.), complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.), complex(-0.0000000234545,1.1234), complex(-3.,5.1), complex(-53,30.1), complex(0.0,0.12345), complex(11,1), complex(-22,-2), complex(9,-28), complex(21,-33), complex(1e5,1e5), complex(1e14,1e14) ] w = [ complex(-3.78270245518980507452677445620103199303131110e-7, 0.000903861276433172057331093754199933411710053155), complex(0.1764906227004816847297495349730234591778719532788, -0.02146550539468457616788719893991501311573031095617), complex(0.2410250715772692146133539023007113781272362309451, 0.06087579663428089745895459735240964093522265589350), complex(0.30474420525691259245713884106959496013413834051768, -0.20821893820283162728743734725471561394145872072738), complex(7.317131068972378096865595229600561710140617977e34, 8.321873499714402777186848353320412813066170427e34), complex(0.0615698507236323685519612934241429530190806818395, -0.00676005783716575013073036218018565206070072304635), complex(0.3960793007699874918961319170187598400134746631, -5.593152259116644920546186222529802777409274656e-9), complex(0.08217199226739447943295069917990417630675021771804, -0.04701291087643609891018366143118110965272615832184), complex(0.00457246000350281640952328010227885008541748668738, -0.00804900791411691821818731763401840373998654987934), complex(0.8746342859608052666092782112565360755791467973338452, 0.), complex(0.00468190164965444174367477874864366058339647648741, 0.0510735563901306197993676329845149741675029197050), complex(-0.0023193175200187620902125853834909543869428763219, -0.025460054739731556004902057663500272721780776336), complex(9.11463368405637174660562096516414499772662584e304, 3.97101807145263333769664875189354358563218932e305), complex(-4.4927207857715598976165541011143706155432296e281, -2.8019591213423077494444700357168707775769028e281), complex(2.820947917809305132678577516325951485807107151e-6, 2.820947917668257736791638444590253942253354058e-6), complex(2.82094791773878143474039725787438662716372268e-15, 2.82094791773878143474039725773333923127678361e-15) ] assert_func_equal(cephes.wofz, w, z, rtol=1e-13) class TestAiry(object): def test_airy(self): # This tests the airy function to ensure 8 place accuracy in computation x = special.airy(.99) assert_array_almost_equal(x,array([0.13689066,-0.16050153,1.19815925,0.92046818]),8) x = special.airy(.41) assert_array_almost_equal(x,array([0.25238916,-.23480512,0.80686202,0.51053919]),8) x = special.airy(-.36) assert_array_almost_equal(x,array([0.44508477,-0.23186773,0.44939534,0.48105354]),8) def test_airye(self): a = special.airye(0.01) b = special.airy(0.01) b1 = [None]*4 for n in range(2): b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01)) for n in range(2,4): b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) assert_array_almost_equal(a,b1,6) def test_bi_zeros(self): bi = special.bi_zeros(2) bia = (array([-1.17371322, -3.2710930]), array([-2.29443968, -4.07315509]), array([-0.45494438, 0.39652284]), array([0.60195789, -0.76031014])) assert_array_almost_equal(bi,bia,4) bi = special.bi_zeros(5) assert_array_almost_equal(bi[0],array([-1.173713222709127, -3.271093302836352, -4.830737841662016, -6.169852128310251, -7.376762079367764]),11) assert_array_almost_equal(bi[1],array([-2.294439682614122, -4.073155089071828, -5.512395729663599, -6.781294445990305, -7.940178689168587]),10) assert_array_almost_equal(bi[2],array([-0.454944383639657, 0.396522836094465, -0.367969161486959, 0.349499116831805, -0.336026240133662]),11) assert_array_almost_equal(bi[3],array([0.601957887976239, -0.760310141492801, 0.836991012619261, -0.88947990142654, 0.929983638568022]),10) def test_ai_zeros(self): ai = special.ai_zeros(1) assert_array_almost_equal(ai,(array([-2.33810741]), array([-1.01879297]), array([0.5357]), array([0.7012])),4) def test_ai_zeros_big(self): z, zp, ai_zpx, aip_zx = special.ai_zeros(50000) ai_z, aip_z, _, _ = special.airy(z) ai_zp, aip_zp, _, _ = special.airy(zp) ai_envelope = 1/abs(z)**(1./4) aip_envelope = abs(zp)**(1./4) # Check values assert_allclose(ai_zpx, ai_zp, rtol=1e-10) assert_allclose(aip_zx, aip_z, rtol=1e-10) # Check they are zeros assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0) assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.1 assert_allclose(z[:6], [-2.3381074105, -4.0879494441, -5.5205598281, -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10) assert_allclose(zp[:6], [-1.0187929716, -3.2481975822, -4.8200992112, -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10) def test_bi_zeros_big(self): z, zp, bi_zpx, bip_zx = special.bi_zeros(50000) _, _, bi_z, bip_z = special.airy(z) _, _, bi_zp, bip_zp = special.airy(zp) bi_envelope = 1/abs(z)**(1./4) bip_envelope = abs(zp)**(1./4) # Check values assert_allclose(bi_zpx, bi_zp, rtol=1e-10) assert_allclose(bip_zx, bip_z, rtol=1e-10) # Check they are zeros assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0) assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.2 assert_allclose(z[:6], [-1.1737132227, -3.2710933028, -4.8307378417, -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10) assert_allclose(zp[:6], [-2.2944396826, -4.0731550891, -5.5123957297, -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10) class TestAssocLaguerre(object): def test_assoc_laguerre(self): a1 = special.genlaguerre(11,1) a2 = special.assoc_laguerre(.2,11,1) assert_array_almost_equal(a2,a1(.2),8) a2 = special.assoc_laguerre(1,11,1) assert_array_almost_equal(a2,a1(1),8) class TestBesselpoly(object): def test_besselpoly(self): pass class TestKelvin(object): def test_bei(self): mbei = special.bei(2) assert_almost_equal(mbei, 0.9722916273066613,5) # this may not be exact def test_beip(self): mbeip = special.beip(2) assert_almost_equal(mbeip,0.91701361338403631,5) # this may not be exact def test_ber(self): mber = special.ber(2) assert_almost_equal(mber,0.75173418271380821,5) # this may not be exact def test_berp(self): mberp = special.berp(2) assert_almost_equal(mberp,-0.49306712470943909,5) # this may not be exact def test_bei_zeros(self): # Abramowitz & Stegun, Table 9.12 bi = special.bei_zeros(5) assert_array_almost_equal(bi,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) def test_beip_zeros(self): bip = special.beip_zeros(5) assert_array_almost_equal(bip,array([3.772673304934953, 8.280987849760042, 12.742147523633703, 17.193431752512542, 21.641143941167325]),8) def test_ber_zeros(self): ber = special.ber_zeros(5) assert_array_almost_equal(ber,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) def test_berp_zeros(self): brp = special.berp_zeros(5) assert_array_almost_equal(brp,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) def test_kelvin(self): mkelv = special.kelvin(2) assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j, special.ker(2) + special.kei(2)*1j, special.berp(2) + special.beip(2)*1j, special.kerp(2) + special.keip(2)*1j),8) def test_kei(self): mkei = special.kei(2) assert_almost_equal(mkei,-0.20240006776470432,5) def test_keip(self): mkeip = special.keip(2) assert_almost_equal(mkeip,0.21980790991960536,5) def test_ker(self): mker = special.ker(2) assert_almost_equal(mker,-0.041664513991509472,5) def test_kerp(self): mkerp = special.kerp(2) assert_almost_equal(mkerp,-0.10660096588105264,5) def test_kei_zeros(self): kei = special.kei_zeros(5) assert_array_almost_equal(kei,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) def test_keip_zeros(self): keip = special.keip_zeros(5) assert_array_almost_equal(keip,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) # numbers come from 9.9 of A&S pg. 381 def test_kelvin_zeros(self): tmp = special.kelvin_zeros(5) berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp assert_array_almost_equal(berz,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) assert_array_almost_equal(beiz,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) assert_array_almost_equal(kerz,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44382]),4) assert_array_almost_equal(keiz,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) assert_array_almost_equal(berpz,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) assert_array_almost_equal(beipz,array([3.77267, # table from 1927 had 3.77320 # but this is more accurate 8.28099, 12.74215, 17.19343, 21.64114]),4) assert_array_almost_equal(kerpz,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) assert_array_almost_equal(keipz,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) def test_ker_zeros(self): ker = special.ker_zeros(5) assert_array_almost_equal(ker,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44381]),4) def test_kerp_zeros(self): kerp = special.kerp_zeros(5) assert_array_almost_equal(kerp,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) class TestBernoulli(object): def test_bernoulli(self): brn = special.bernoulli(5) assert_array_almost_equal(brn,array([1.0000, -0.5000, 0.1667, 0.0000, -0.0333, 0.0000]),4) class TestBeta(object): def test_beta(self): bet = special.beta(2,4) betg = (special.gamma(2)*special.gamma(4))/special.gamma(6) assert_almost_equal(bet,betg,8) def test_betaln(self): betln = special.betaln(2,4) bet = log(abs(special.beta(2,4))) assert_almost_equal(betln,bet,8) def test_betainc(self): btinc = special.betainc(1,1,.2) assert_almost_equal(btinc,0.2,8) def test_betaincinv(self): y = special.betaincinv(2,4,.5) comp = special.betainc(2,4,y) assert_almost_equal(comp,.5,5) class TestCombinatorics(object): def test_comb(self): assert_array_almost_equal(special.comb([10, 10], [3, 4]), [120., 210.]) assert_almost_equal(special.comb(10, 3), 120.) assert_equal(special.comb(10, 3, exact=True), 120) assert_equal(special.comb(10, 3, exact=True, repetition=True), 220) assert_allclose([special.comb(20, k, exact=True) for k in range(21)], special.comb(20, list(range(21))), atol=1e-15) ii = np.iinfo(int).max + 1 assert_equal(special.comb(ii, ii-1, exact=True), ii) expected = 100891344545564193334812497256 assert_equal(special.comb(100, 50, exact=True), expected) def test_comb_with_np_int64(self): n = 70 k = 30 np_n = np.int64(n) np_k = np.int64(k) assert_equal(special.comb(np_n, np_k, exact=True), special.comb(n, k, exact=True)) def test_comb_zeros(self): assert_equal(special.comb(2, 3, exact=True), 0) assert_equal(special.comb(-1, 3, exact=True), 0) assert_equal(special.comb(2, -1, exact=True), 0) assert_equal(special.comb(2, -1, exact=False), 0) assert_array_almost_equal(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 120.]) def test_perm(self): assert_array_almost_equal(special.perm([10, 10], [3, 4]), [720., 5040.]) assert_almost_equal(special.perm(10, 3), 720.) assert_equal(special.perm(10, 3, exact=True), 720) def test_perm_zeros(self): assert_equal(special.perm(2, 3, exact=True), 0) assert_equal(special.perm(-1, 3, exact=True), 0) assert_equal(special.perm(2, -1, exact=True), 0) assert_equal(special.perm(2, -1, exact=False), 0) assert_array_almost_equal(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 720.]) class TestTrigonometric(object): def test_cbrt(self): cb = special.cbrt(27) cbrl = 27**(1.0/3.0) assert_approx_equal(cb,cbrl) def test_cbrtmore(self): cb1 = special.cbrt(27.9) cbrl1 = 27.9**(1.0/3.0) assert_almost_equal(cb1,cbrl1,8) def test_cosdg(self): cdg = special.cosdg(90) cdgrl = cos(pi/2.0) assert_almost_equal(cdg,cdgrl,8) def test_cosdgmore(self): cdgm = special.cosdg(30) cdgmrl = cos(pi/6.0) assert_almost_equal(cdgm,cdgmrl,8) def test_cosm1(self): cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10)) csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) assert_array_almost_equal(cs,csrl,8) def test_cotdg(self): ct = special.cotdg(30) ctrl = tan(pi/6.0)**(-1) assert_almost_equal(ct,ctrl,8) def test_cotdgmore(self): ct1 = special.cotdg(45) ctrl1 = tan(pi/4.0)**(-1) assert_almost_equal(ct1,ctrl1,8) def test_specialpoints(self): assert_almost_equal(special.cotdg(45), 1.0, 14) assert_almost_equal(special.cotdg(-45), -1.0, 14) assert_almost_equal(special.cotdg(90), 0.0, 14) assert_almost_equal(special.cotdg(-90), 0.0, 14) assert_almost_equal(special.cotdg(135), -1.0, 14) assert_almost_equal(special.cotdg(-135), 1.0, 14) assert_almost_equal(special.cotdg(225), 1.0, 14) assert_almost_equal(special.cotdg(-225), -1.0, 14) assert_almost_equal(special.cotdg(270), 0.0, 14) assert_almost_equal(special.cotdg(-270), 0.0, 14) assert_almost_equal(special.cotdg(315), -1.0, 14) assert_almost_equal(special.cotdg(-315), 1.0, 14) assert_almost_equal(special.cotdg(765), 1.0, 14) def test_sinc(self): # the sinc implementation and more extensive sinc tests are in numpy assert_array_equal(special.sinc([0]), 1) assert_equal(special.sinc(0.0), 1.0) def test_sindg(self): sn = special.sindg(90) assert_equal(sn,1.0) def test_sindgmore(self): snm = special.sindg(30) snmrl = sin(pi/6.0) assert_almost_equal(snm,snmrl,8) snm1 = special.sindg(45) snmrl1 = sin(pi/4.0) assert_almost_equal(snm1,snmrl1,8) class TestTandg(object): def test_tandg(self): tn = special.tandg(30) tnrl = tan(pi/6.0) assert_almost_equal(tn,tnrl,8) def test_tandgmore(self): tnm = special.tandg(45) tnmrl = tan(pi/4.0) assert_almost_equal(tnm,tnmrl,8) tnm1 = special.tandg(60) tnmrl1 = tan(pi/3.0) assert_almost_equal(tnm1,tnmrl1,8) def test_specialpoints(self): assert_almost_equal(special.tandg(0), 0.0, 14) assert_almost_equal(special.tandg(45), 1.0, 14) assert_almost_equal(special.tandg(-45), -1.0, 14) assert_almost_equal(special.tandg(135), -1.0, 14) assert_almost_equal(special.tandg(-135), 1.0, 14) assert_almost_equal(special.tandg(180), 0.0, 14) assert_almost_equal(special.tandg(-180), 0.0, 14) assert_almost_equal(special.tandg(225), 1.0, 14) assert_almost_equal(special.tandg(-225), -1.0, 14) assert_almost_equal(special.tandg(315), -1.0, 14) assert_almost_equal(special.tandg(-315), 1.0, 14) class TestEllip(object): def test_ellipj_nan(self): """Regression test for #912.""" special.ellipj(0.5, np.nan) def test_ellipj(self): el = special.ellipj(0.2,0) rel = [sin(0.2),cos(0.2),1.0,0.20] assert_array_almost_equal(el,rel,13) def test_ellipk(self): elk = special.ellipk(.2) assert_almost_equal(elk,1.659623598610528,11) assert_equal(special.ellipkm1(0.0), np.inf) assert_equal(special.ellipkm1(1.0), pi/2) assert_equal(special.ellipkm1(np.inf), 0.0) assert_equal(special.ellipkm1(np.nan), np.nan) assert_equal(special.ellipkm1(-1), np.nan) assert_allclose(special.ellipk(-10), 0.7908718902387385) def test_ellipkinc(self): elkinc = special.ellipkinc(pi/2,.2) elk = special.ellipk(0.2) assert_almost_equal(elkinc,elk,15) alpha = 20*pi/180 phi = 45*pi/180 m = sin(alpha)**2 elkinc = special.ellipkinc(phi,m) assert_almost_equal(elkinc,0.79398143,8) # From pg. 614 of A & S assert_equal(special.ellipkinc(pi/2, 0.0), pi/2) assert_equal(special.ellipkinc(pi/2, 1.0), np.inf) assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0) assert_equal(special.ellipkinc(pi/2, np.nan), np.nan) assert_equal(special.ellipkinc(pi/2, 2), np.nan) assert_equal(special.ellipkinc(0, 0.5), 0.0) assert_equal(special.ellipkinc(np.inf, 0.5), np.inf) assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipkinc(np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.nan, 0.5), np.nan) assert_equal(special.ellipkinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14) assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946) def test_ellipkinc_2(self): # Regression test for gh-3550 # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipkinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 1.0259330100195334), 1) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipkinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 5.1296650500976675), 2) def test_ellipkinc_singular(self): # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2) xlog = np.logspace(-300, -17, 25) xlin = np.linspace(1e-17, 0.1, 25) xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False) assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)), rtol=1e14) assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)), rtol=1e14) assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)), rtol=1e14) assert_equal(special.ellipkinc(np.pi/2, 1), np.inf) assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)), rtol=1e14) assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf) def test_ellipe(self): ele = special.ellipe(.2) assert_almost_equal(ele,1.4890350580958529,8) assert_equal(special.ellipe(0.0), pi/2) assert_equal(special.ellipe(1.0), 1.0) assert_equal(special.ellipe(-np.inf), np.inf) assert_equal(special.ellipe(np.nan), np.nan) assert_equal(special.ellipe(2), np.nan) assert_allclose(special.ellipe(-10), 3.6391380384177689) def test_ellipeinc(self): eleinc = special.ellipeinc(pi/2,.2) ele = special.ellipe(0.2) assert_almost_equal(eleinc,ele,14) # pg 617 of A & S alpha, phi = 52*pi/180,35*pi/180 m = sin(alpha)**2 eleinc = special.ellipeinc(phi,m) assert_almost_equal(eleinc, 0.58823065, 8) assert_equal(special.ellipeinc(pi/2, 0.0), pi/2) assert_equal(special.ellipeinc(pi/2, 1.0), 1.0) assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf) assert_equal(special.ellipeinc(pi/2, np.nan), np.nan) assert_equal(special.ellipeinc(pi/2, 2), np.nan) assert_equal(special.ellipeinc(0, 0.5), 0.0) assert_equal(special.ellipeinc(np.inf, 0.5), np.inf) assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf) assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf) assert_equal(special.ellipeinc(np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(np.nan, 0.5), np.nan) assert_equal(special.ellipeinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876) def test_ellipeinc_2(self): # Regression test for gh-3550 # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipeinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 0.84442884574781019), 2) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipeinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 3.3471442287390509), 4) class TestErf(object): def test_erf(self): er = special.erf(.25) assert_almost_equal(er,0.2763263902,8) def test_erf_zeros(self): erz = special.erf_zeros(5) erzr = array([1.45061616+1.88094300j, 2.24465928+2.61657514j, 2.83974105+3.17562810j, 3.33546074+3.64617438j, 3.76900557+4.06069723j]) assert_array_almost_equal(erz,erzr,4) def _check_variant_func(self, func, other_func, rtol, atol=0): np.random.seed(1234) n = 10000 x = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) y = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) z = x + 1j*y old_errors = np.seterr(all='ignore') try: w = other_func(z) w_real = other_func(x).real mask = np.isfinite(w) w = w[mask] z = z[mask] mask = np.isfinite(w_real) w_real = w_real[mask] x = x[mask] # test both real and complex variants assert_func_equal(func, w, z, rtol=rtol, atol=atol) assert_func_equal(func, w_real, x, rtol=rtol, atol=atol) finally: np.seterr(**old_errors) def test_erfc_consistent(self): self._check_variant_func( cephes.erfc, lambda z: 1 - cephes.erf(z), rtol=1e-12, atol=1e-14 # <- the test function loses precision ) def test_erfcx_consistent(self): self._check_variant_func( cephes.erfcx, lambda z: np.exp(z*z) * cephes.erfc(z), rtol=1e-12 ) def test_erfi_consistent(self): self._check_variant_func( cephes.erfi, lambda z: -1j * cephes.erf(1j*z), rtol=1e-12 ) def test_dawsn_consistent(self): self._check_variant_func( cephes.dawsn, lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z), rtol=1e-12 ) def test_erf_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -1, 1] assert_allclose(special.erf(vals), expected, rtol=1e-15) def test_erfc_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, 2, 0] assert_allclose(special.erfc(vals), expected, rtol=1e-15) def test_erfcx_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, np.inf, 0] assert_allclose(special.erfcx(vals), expected, rtol=1e-15) def test_erfi_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -np.inf, np.inf] assert_allclose(special.erfi(vals), expected, rtol=1e-15) def test_dawsn_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -0.0, 0.0] assert_allclose(special.dawsn(vals), expected, rtol=1e-15) def test_wofz_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan + np.nan * 1.j, 0.-0.j, 0.+0.j] assert_allclose(special.wofz(vals), expected, rtol=1e-15) class TestEuler(object): def test_euler(self): eu0 = special.euler(0) eu1 = special.euler(1) eu2 = special.euler(2) # just checking segfaults assert_allclose(eu0, [1], rtol=1e-15) assert_allclose(eu1, [1, 0], rtol=1e-15) assert_allclose(eu2, [1, 0, -1], rtol=1e-15) eu24 = special.euler(24) mathworld = [1,1,5,61,1385,50521,2702765,199360981, 19391512145,2404879675441, 370371188237525,69348874393137901, 15514534163557086905] correct = zeros((25,),'d') for k in range(0,13): if (k % 2): correct[2*k] = -float(mathworld[k]) else: correct[2*k] = float(mathworld[k]) olderr = np.seterr(all='ignore') try: err = nan_to_num((eu24-correct)/correct) errmax = max(err) finally: np.seterr(**olderr) assert_almost_equal(errmax, 0.0, 14) class TestExp(object): def test_exp2(self): ex = special.exp2(2) exrl = 2**2 assert_equal(ex,exrl) def test_exp2more(self): exm = special.exp2(2.5) exmrl = 2**(2.5) assert_almost_equal(exm,exmrl,8) def test_exp10(self): ex = special.exp10(2) exrl = 10**2 assert_approx_equal(ex,exrl) def test_exp10more(self): exm = special.exp10(2.5) exmrl = 10**(2.5) assert_almost_equal(exm,exmrl,8) def test_expm1(self): ex = (special.expm1(2),special.expm1(3),special.expm1(4)) exrl = (exp(2)-1,exp(3)-1,exp(4)-1) assert_array_almost_equal(ex,exrl,8) def test_expm1more(self): ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2)) exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) assert_array_almost_equal(ex1,exrl1,8) class TestFactorialFunctions(object): def test_factorial(self): # Some known values, float math assert_array_almost_equal(special.factorial(0), 1) assert_array_almost_equal(special.factorial(1), 1) assert_array_almost_equal(special.factorial(2), 2) assert_array_almost_equal([6., 24., 120.], special.factorial([3, 4, 5], exact=False)) assert_array_almost_equal(special.factorial([[5, 3], [4, 3]]), [[120, 6], [24, 6]]) # Some known values, integer math assert_equal(special.factorial(0, exact=True), 1) assert_equal(special.factorial(1, exact=True), 1) assert_equal(special.factorial(2, exact=True), 2) assert_equal(special.factorial(5, exact=True), 120) assert_equal(special.factorial(15, exact=True), 1307674368000) # ndarray shape is maintained assert_equal(special.factorial([7, 4, 15, 10], exact=True), [5040, 24, 1307674368000, 3628800]) assert_equal(special.factorial([[5, 3], [4, 3]], True), [[120, 6], [24, 6]]) # object arrays assert_equal(special.factorial(np.arange(-3, 22), True), special.factorial(np.arange(-3, 22), False)) # int64 array assert_equal(special.factorial(np.arange(-3, 15), True), special.factorial(np.arange(-3, 15), False)) # int32 array assert_equal(special.factorial(np.arange(-3, 5), True), special.factorial(np.arange(-3, 5), False)) # Consistent output for n < 0 for exact in (True, False): assert_array_equal(0, special.factorial(-3, exact)) assert_array_equal([1, 2, 0, 0], special.factorial([1, 2, -5, -4], exact)) for n in range(0, 22): # Compare all with math.factorial correct = math.factorial(n) assert_array_equal(correct, special.factorial(n, True)) assert_array_equal(correct, special.factorial([n], True)[0]) assert_allclose(float(correct), special.factorial(n, False)) assert_allclose(float(correct), special.factorial([n], False)[0]) # Compare exact=True vs False, scalar vs array assert_array_equal(special.factorial(n, True), special.factorial(n, False)) assert_array_equal(special.factorial([n], True), special.factorial([n], False)) @pytest.mark.parametrize('x, exact', [ (1, True), (1, False), (np.array(1), True), (np.array(1), False), ]) def test_factorial_0d_return_type(self, x, exact): assert np.isscalar(special.factorial(x, exact=exact)) def test_factorial2(self): assert_array_almost_equal([105., 384., 945.], special.factorial2([7, 8, 9], exact=False)) assert_equal(special.factorial2(7, exact=True), 105) def test_factorialk(self): assert_equal(special.factorialk(5, 1, exact=True), 120) assert_equal(special.factorialk(5, 3, exact=True), 10) @pytest.mark.parametrize('x, exact', [ (np.nan, True), (np.nan, False), (np.array([np.nan]), True), (np.array([np.nan]), False), ]) def test_nan_inputs(self, x, exact): result = special.factorial(x, exact=exact) assert_(np.isnan(result)) def test_mixed_nan_inputs(self): x = np.array([np.nan, 1, 2, 3, np.nan]) result = special.factorial(x, exact=True) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) result = special.factorial(x, exact=False) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) class TestFresnel(object): def test_fresnel(self): frs = array(special.fresnel(.5)) assert_array_almost_equal(frs,array([0.064732432859999287, 0.49234422587144644]),8) def test_fresnel_inf1(self): frs = special.fresnel(np.inf) assert_equal(frs, (0.5, 0.5)) def test_fresnel_inf2(self): frs = special.fresnel(-np.inf) assert_equal(frs, (-0.5, -0.5)) # values from pg 329 Table 7.11 of A & S # slightly corrected in 4th decimal place def test_fresnel_zeros(self): szo, czo = special.fresnel_zeros(5) assert_array_almost_equal(szo, array([2.0093+0.2885j, 2.8335+0.2443j, 3.4675+0.2185j, 4.0026+0.2009j, 4.4742+0.1877j]),3) assert_array_almost_equal(czo, array([1.7437+0.3057j, 2.6515+0.2529j, 3.3204+0.2240j, 3.8757+0.2047j, 4.3611+0.1907j]),3) vals1 = special.fresnel(szo)[0] vals2 = special.fresnel(czo)[1] assert_array_almost_equal(vals1,0,14) assert_array_almost_equal(vals2,0,14) def test_fresnelc_zeros(self): szo, czo = special.fresnel_zeros(6) frc = special.fresnelc_zeros(6) assert_array_almost_equal(frc,czo,12) def test_fresnels_zeros(self): szo, czo = special.fresnel_zeros(5) frs = special.fresnels_zeros(5) assert_array_almost_equal(frs,szo,12) class TestGamma(object): def test_gamma(self): gam = special.gamma(5) assert_equal(gam,24.0) def test_gammaln(self): gamln = special.gammaln(3) lngam = log(special.gamma(3)) assert_almost_equal(gamln,lngam,8) def test_gammainccinv(self): gccinv = special.gammainccinv(.5,.5) gcinv = special.gammaincinv(.5,.5) assert_almost_equal(gccinv,gcinv,8) @with_special_errors def test_gammaincinv(self): y = special.gammaincinv(.4,.4) x = special.gammainc(.4,y) assert_almost_equal(x,0.4,1) y = special.gammainc(10, 0.05) x = special.gammaincinv(10, 2.5715803516000736e-20) assert_almost_equal(0.05, x, decimal=10) assert_almost_equal(y, 2.5715803516000736e-20, decimal=10) x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18) assert_almost_equal(11.0, x, decimal=10) @with_special_errors def test_975(self): # Regression test for ticket #975 -- switch point in algorithm # check that things work OK at the point, immediately next floats # around it, and a bit further away pts = [0.25, np.nextafter(0.25, 0), 0.25 - 1e-12, np.nextafter(0.25, 1), 0.25 + 1e-12] for xp in pts: y = special.gammaincinv(.4, xp) x = special.gammainc(0.4, y) assert_allclose(x, xp, rtol=1e-12) def test_rgamma(self): rgam = special.rgamma(8) rlgam = 1/special.gamma(8) assert_almost_equal(rgam,rlgam,8) def test_infinity(self): assert_(np.isinf(special.gamma(-1))) assert_equal(special.rgamma(-1), 0) class TestHankel(object): def test_negv1(self): assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14) def test_hankel1(self): hank1 = special.hankel1(1,.1) hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j) assert_almost_equal(hank1,hankrl,8) def test_negv1e(self): assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14) def test_hankel1e(self): hank1e = special.hankel1e(1,.1) hankrle = special.hankel1(1,.1)*exp(-.1j) assert_almost_equal(hank1e,hankrle,8) def test_negv2(self): assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14) def test_hankel2(self): hank2 = special.hankel2(1,.1) hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j) assert_almost_equal(hank2,hankrl2,8) def test_neg2e(self): assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14) def test_hankl2e(self): hank2e = special.hankel2e(1,.1) hankrl2e = special.hankel2e(1,.1) assert_almost_equal(hank2e,hankrl2e,8) class TestHyper(object): def test_h1vp(self): h1 = special.h1vp(1,.1) h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j) assert_almost_equal(h1,h1real,8) def test_h2vp(self): h2 = special.h2vp(1,.1) h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j) assert_almost_equal(h2,h2real,8) def test_hyp0f1(self): # scalar input assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12) assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15) # float input, expected values match mpmath x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5]) expected = np.array([0.58493659229143, 0.70566805723127, 1.0, 1.37789689539747, 1.60373685288480]) assert_allclose(x, expected, rtol=1e-12) # complex input x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j) assert_allclose(x, expected.astype(complex), rtol=1e-12) # test broadcasting x1 = [0.5, 1.5, 2.5] x2 = [0, 1, 0.5] x = special.hyp0f1(x1, x2) expected = [1.0, 1.8134302039235093, 1.21482702689997] assert_allclose(x, expected, rtol=1e-12) x = special.hyp0f1(np.row_stack([x1] * 2), x2) assert_allclose(x, np.row_stack([expected] * 2), rtol=1e-12) assert_raises(ValueError, special.hyp0f1, np.row_stack([x1] * 3), [0, 1]) def test_hyp0f1_gh5764(self): # Just checks the point that failed; there's a more systematic # test in test_mpmath res = special.hyp0f1(0.8, 0.5 + 0.5*1J) # The expected value was generated using mpmath assert_almost_equal(res, 1.6139719776441115 + 1J*0.80893054061790665) def test_hyp1f1(self): hyp1 = special.hyp1f1(.1,.1,.3) assert_almost_equal(hyp1, 1.3498588075760032,7) # test contributed by Moritz Deger (2008-05-29) # https://github.com/scipy/scipy/issues/1186 (Trac #659) # reference data obtained from mathematica [ a, b, x, m(a,b,x)]: # produced with test_hyp1f1.nb ref_data = array([[-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04], [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00], [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05], [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08], [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24], [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21], [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13], [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13], [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02], [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10], [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01], [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21], [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20], [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07], [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03], [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02], [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11], [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03], [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17], [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01], [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00], [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00], [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23], [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01], [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04], [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08], [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01], [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07], [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03], [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09], [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06], [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00], [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01], [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02], [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02], [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02], [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00], [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09], [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01], [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00], [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02], [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05], [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05], [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02], [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02], [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13], [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05], [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12], [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01], [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16], [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37], [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06], [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02], [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12], [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27], [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04], [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06], [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07], [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03], [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07], [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27], [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12], [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32], [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04], [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01], [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02], [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19], [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09], [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31], [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01], [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02], [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08], [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09], [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33], [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01], [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29], [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01], [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29], [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02], [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00], [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08], [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01], [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01], [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01], [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13], [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11], [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02], [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02], [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01], [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31], [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04], [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25], [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01], [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00], [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02], [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05], [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02], [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01], [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01], [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00]]) for a,b,c,expected in ref_data: result = special.hyp1f1(a,b,c) assert_(abs(expected - result)/expected < 1e-4) def test_hyp1f1_gh2957(self): hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933) hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934) assert_almost_equal(hyp1, hyp2, 12) def test_hyp1f1_gh2282(self): hyp = special.hyp1f1(0.5, 1.5, -1000) assert_almost_equal(hyp, 0.028024956081989643, 12) def test_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], [3, 4, 8, 1, special.gamma(8)*special.gamma(8-4-3)/special.gamma(8-3)/special.gamma(8-4)], [3, 2, 3-2+1, -1, 1./2**3*sqrt(pi) * special.gamma(1+3-2)/special.gamma(1+0.5*3-2)/special.gamma(0.5+0.5*3)], [5, 2, 5-2+1, -1, 1./2**5*sqrt(pi) * special.gamma(1+5-2)/special.gamma(1+0.5*5-2)/special.gamma(0.5+0.5*5)], [4, 0.5+4, 1.5-2*4, -1./3, (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4)/special.gamma(3./2)/special.gamma(4./3-2*4)], # and some others # ticket #424 [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484], # negative integer a or b, with c-a-b integer and x > 0.9 [-2,3,1,0.95,0.715], [2,-3,1,0.95,-0.007], [-6,3,1,0.95,0.0000810625], [2,-5,1,0.95,-0.000029375], # huge negative integers (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24), (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18), ] for i, (a, b, c, x, v) in enumerate(values): cv = special.hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_hyperu(self): val1 = special.hyperu(1,0.1,100) assert_almost_equal(val1,0.0098153,7) a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] a,b = asarray(a), asarray(b) z = 0.5 hypu = special.hyperu(a,b,z) hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) / (special.gamma(1+a-b)*special.gamma(b)) - z**(1-b)*special.hyp1f1(1+a-b,2-b,z) / (special.gamma(a)*special.gamma(2-b))) assert_array_almost_equal(hypu,hprl,12) def test_hyperu_gh2287(self): assert_almost_equal(special.hyperu(1, 1.5, 20.2), 0.048360918656699191, 12) class TestBessel(object): def test_itj0y0(self): it0 = array(special.itj0y0(.2)) assert_array_almost_equal(it0,array([0.19933433254006822, -0.34570883800412566]),8) def test_it2j0y0(self): it2 = array(special.it2j0y0(.2)) assert_array_almost_equal(it2,array([0.0049937546274601858, -0.43423067011231614]),8) def test_negv_iv(self): assert_equal(special.iv(3,2), special.iv(-3,2)) def test_j0(self): oz = special.j0(.1) ozr = special.jn(0,.1) assert_almost_equal(oz,ozr,8) def test_j1(self): o1 = special.j1(.1) o1r = special.jn(1,.1) assert_almost_equal(o1,o1r,8) def test_jn(self): jnnr = special.jn(1,.2) assert_almost_equal(jnnr,0.099500832639235995,8) def test_negv_jv(self): assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14) def test_jv(self): values = [[0, 0.1, 0.99750156206604002], [2./3, 1e-8, 0.3239028506761532e-5], [2./3, 1e-10, 0.1503423854873779e-6], [3.1, 1e-10, 0.1711956265409013e-32], [2./3, 4.0, -0.2325440850267039], ] for i, (v, x, y) in enumerate(values): yc = special.jv(v, x) assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) def test_negv_jve(self): assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14) def test_jve(self): jvexp = special.jve(1,.2) assert_almost_equal(jvexp,0.099500832639235995,8) jvexp1 = special.jve(1,.2+1j) z = .2+1j jvexpr = special.jv(1,z)*exp(-abs(z.imag)) assert_almost_equal(jvexp1,jvexpr,8) def test_jn_zeros(self): jn0 = special.jn_zeros(0,5) jn1 = special.jn_zeros(1,5) assert_array_almost_equal(jn0,array([2.4048255577, 5.5200781103, 8.6537279129, 11.7915344391, 14.9309177086]),4) assert_array_almost_equal(jn1,array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]),4) jn102 = special.jn_zeros(102,5) assert_allclose(jn102, array([110.89174935992040343, 117.83464175788308398, 123.70194191713507279, 129.02417238949092824, 134.00114761868422559]), rtol=1e-13) jn301 = special.jn_zeros(301,5) assert_allclose(jn301, array([313.59097866698830153, 323.21549776096288280, 331.22338738656748796, 338.39676338872084500, 345.03284233056064157]), rtol=1e-13) def test_jn_zeros_slow(self): jn0 = special.jn_zeros(0, 300) assert_allclose(jn0[260-1], 816.02884495068867280, rtol=1e-13) assert_allclose(jn0[280-1], 878.86068707124422606, rtol=1e-13) assert_allclose(jn0[300-1], 941.69253065317954064, rtol=1e-13) jn10 = special.jn_zeros(10, 300) assert_allclose(jn10[260-1], 831.67668514305631151, rtol=1e-13) assert_allclose(jn10[280-1], 894.51275095371316931, rtol=1e-13) assert_allclose(jn10[300-1], 957.34826370866539775, rtol=1e-13) jn3010 = special.jn_zeros(3010,5) assert_allclose(jn3010, array([3036.86590780927, 3057.06598526482, 3073.66360690272, 3088.37736494778, 3101.86438139042]), rtol=1e-8) def test_jnjnp_zeros(self): jn = special.jn def jnp(n, x): return (jn(n-1,x) - jn(n+1,x))/2 for nt in range(1, 30): z, n, m, t = special.jnjnp_zeros(nt) for zz, nn, tt in zip(z, n, t): if tt == 0: assert_allclose(jn(nn, zz), 0, atol=1e-6) elif tt == 1: assert_allclose(jnp(nn, zz), 0, atol=1e-6) else: raise AssertionError("Invalid t return for nt=%d" % nt) def test_jnp_zeros(self): jnp = special.jnp_zeros(1,5) assert_array_almost_equal(jnp, array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]),4) jnp = special.jnp_zeros(443,5) assert_allclose(special.jvp(443, jnp), 0, atol=1e-15) def test_jnyn_zeros(self): jnz = special.jnyn_zeros(1,5) assert_array_almost_equal(jnz,(array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]), array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]), array([2.19714, 5.42968, 8.59601, 11.74915, 14.89744]), array([3.68302, 6.94150, 10.12340, 13.28576, 16.44006])),5) def test_jvp(self): jvprim = special.jvp(2,2) jv0 = (special.jv(1,2)-special.jv(3,2))/2 assert_almost_equal(jvprim,jv0,10) def test_k0(self): ozk = special.k0(.1) ozkr = special.kv(0,.1) assert_almost_equal(ozk,ozkr,8) def test_k0e(self): ozke = special.k0e(.1) ozker = special.kve(0,.1) assert_almost_equal(ozke,ozker,8) def test_k1(self): o1k = special.k1(.1) o1kr = special.kv(1,.1) assert_almost_equal(o1k,o1kr,8) def test_k1e(self): o1ke = special.k1e(.1) o1ker = special.kve(1,.1) assert_almost_equal(o1ke,o1ker,8) def test_jacobi(self): a = 5*np.random.random() - 1 b = 5*np.random.random() - 1 P0 = special.jacobi(0,a,b) P1 = special.jacobi(1,a,b) P2 = special.jacobi(2,a,b) P3 = special.jacobi(3,a,b) assert_array_almost_equal(P0.c,[1],13) assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13) cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)] p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]] assert_array_almost_equal(P2.c,array(p2c)/8.0,13) cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3), 12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)] p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] assert_array_almost_equal(P3.c,array(p3c)/48.0,13) def test_kn(self): kn1 = special.kn(0,.2) assert_almost_equal(kn1,1.7527038555281462,8) def test_negv_kv(self): assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2)) def test_kv0(self): kv0 = special.kv(0,.2) assert_almost_equal(kv0, 1.7527038555281462, 10) def test_kv1(self): kv1 = special.kv(1,0.2) assert_almost_equal(kv1, 4.775972543220472, 10) def test_kv2(self): kv2 = special.kv(2,0.2) assert_almost_equal(kv2, 49.51242928773287, 10) def test_kn_largeorder(self): assert_allclose(special.kn(32, 1), 1.7516596664574289e+43) def test_kv_largearg(self): assert_equal(special.kv(0, 1e19), 0) def test_negv_kve(self): assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2)) def test_kve(self): kve1 = special.kve(0,.2) kv1 = special.kv(0,.2)*exp(.2) assert_almost_equal(kve1,kv1,8) z = .2+1j kve2 = special.kve(0,z) kv2 = special.kv(0,z)*exp(z) assert_almost_equal(kve2,kv2,8) def test_kvp_v0n1(self): z = 2.2 assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10) def test_kvp_n1(self): v = 3. z = 2.2 xc = -special.kv(v+1,z) + v/z*special.kv(v,z) x = special.kvp(v,z, n=1) assert_almost_equal(xc, x, 10) # this function (kvp) is broken def test_kvp_n2(self): v = 3. z = 2.2 xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z x = special.kvp(v, z, n=2) assert_almost_equal(xc, x, 10) def test_y0(self): oz = special.y0(.1) ozr = special.yn(0,.1) assert_almost_equal(oz,ozr,8) def test_y1(self): o1 = special.y1(.1) o1r = special.yn(1,.1) assert_almost_equal(o1,o1r,8) def test_y0_zeros(self): yo,ypo = special.y0_zeros(2) zo,zpo = special.y0_zeros(2,complex=1) all = r_[yo,zo] allval = r_[ypo,zpo] assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11) assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11) def test_y1_zeros(self): y1 = special.y1_zeros(1) assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) def test_y1p_zeros(self): y1p = special.y1p_zeros(1,complex=1) assert_array_almost_equal(y1p,(array([0.5768+0.904j]), array([-0.7635+0.5892j])),3) def test_yn_zeros(self): an = special.yn_zeros(4,2) assert_array_almost_equal(an,array([5.64515, 9.36162]),5) an = special.yn_zeros(443,5) assert_allclose(an, [450.13573091578090314, 463.05692376675001542, 472.80651546418663566, 481.27353184725625838, 488.98055964441374646], rtol=1e-15) def test_ynp_zeros(self): ao = special.ynp_zeros(0,2) assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6) ao = special.ynp_zeros(43,5) assert_allclose(special.yvp(43, ao), 0, atol=1e-15) ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-9) def test_ynp_zeros_large_order(self): ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-14) def test_yn(self): yn2n = special.yn(1,.2) assert_almost_equal(yn2n,-3.3238249881118471,8) def test_negv_yv(self): assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14) def test_yv(self): yv2 = special.yv(1,.2) assert_almost_equal(yv2,-3.3238249881118471,8) def test_negv_yve(self): assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14) def test_yve(self): yve2 = special.yve(1,.2) assert_almost_equal(yve2,-3.3238249881118471,8) yve2r = special.yv(1,.2+1j)*exp(-1) yve22 = special.yve(1,.2+1j) assert_almost_equal(yve22,yve2r,8) def test_yvp(self): yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0 yvp1 = special.yvp(2,.2) assert_array_almost_equal(yvp1,yvpr,10) def _cephes_vs_amos_points(self): """Yield points at which to compare Cephes implementation to AMOS""" # check several points, including large-amplitude ones for v in [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301]: for z in [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300, 10003]: yield v, z # check half-integers; these are problematic points at least # for cephes/iv for v in 0.5 + arange(-60, 60): yield v, 3.5 def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None): for v, z in self._cephes_vs_amos_points(): if skip is not None and skip(v, z): continue c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z) if np.isinf(c1): assert_(np.abs(c2) >= 1e300, (v, z)) elif np.isnan(c1): assert_(c2.imag != 0, (v, z)) else: assert_allclose(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol) if v == int(v): assert_allclose(c3, c2, err_msg=(v, z), rtol=rtol, atol=atol) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_jv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_yv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305) def test_yv_cephes_vs_amos_only_small_orders(self): skipper = lambda v, z: (abs(v) > 50) self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305, skip=skipper) def test_iv_cephes_vs_amos(self): olderr = np.seterr(all='ignore') try: self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305) finally: np.seterr(**olderr) @pytest.mark.slow def test_iv_cephes_vs_amos_mass_test(self): N = 1000000 np.random.seed(1) v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N) x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N) imsk = (np.random.randint(8, size=N) == 0) v[imsk] = v[imsk].astype(int) old_err = np.seterr(all='ignore') try: c1 = special.iv(v, x) c2 = special.iv(v, x+0j) # deal with differences in the inf and zero cutoffs c1[abs(c1) > 1e300] = np.inf c2[abs(c2) > 1e300] = np.inf c1[abs(c1) < 1e-300] = 0 c2[abs(c2) < 1e-300] = 0 dc = abs(c1/c2 - 1) dc[np.isnan(dc)] = 0 finally: np.seterr(**old_err) k = np.argmax(dc) # Most error apparently comes from AMOS and not our implementation; # there are some problems near integer orders there assert_(dc[k] < 2e-7, (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j))) def test_kv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305) self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305) def test_ticket_623(self): assert_allclose(special.jv(3, 4), 0.43017147387562193) assert_allclose(special.jv(301, 1300), 0.0183487151115275) assert_allclose(special.jv(301, 1296.0682), -0.0224174325312048) def test_ticket_853(self): """Negative-order Bessels""" # cephes assert_allclose(special.jv(-1, 1), -0.4400505857449335) assert_allclose(special.jv(-2, 1), 0.1149034849319005) assert_allclose(special.yv(-1, 1), 0.7812128213002887) assert_allclose(special.yv(-2, 1), -1.650682606816255) assert_allclose(special.iv(-1, 1), 0.5651591039924851) assert_allclose(special.iv(-2, 1), 0.1357476697670383) assert_allclose(special.kv(-1, 1), 0.6019072301972347) assert_allclose(special.kv(-2, 1), 1.624838898635178) assert_allclose(special.jv(-0.5, 1), 0.43109886801837607952) assert_allclose(special.yv(-0.5, 1), 0.6713967071418031) assert_allclose(special.iv(-0.5, 1), 1.231200214592967) assert_allclose(special.kv(-0.5, 1), 0.4610685044478945) # amos assert_allclose(special.jv(-1, 1+0j), -0.4400505857449335) assert_allclose(special.jv(-2, 1+0j), 0.1149034849319005) assert_allclose(special.yv(-1, 1+0j), 0.7812128213002887) assert_allclose(special.yv(-2, 1+0j), -1.650682606816255) assert_allclose(special.iv(-1, 1+0j), 0.5651591039924851) assert_allclose(special.iv(-2, 1+0j), 0.1357476697670383) assert_allclose(special.kv(-1, 1+0j), 0.6019072301972347) assert_allclose(special.kv(-2, 1+0j), 1.624838898635178) assert_allclose(special.jv(-0.5, 1+0j), 0.43109886801837607952) assert_allclose(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j) assert_allclose(special.yv(-0.5, 1+0j), 0.6713967071418031) assert_allclose(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j) assert_allclose(special.iv(-0.5, 1+0j), 1.231200214592967) assert_allclose(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j) assert_allclose(special.kv(-0.5, 1+0j), 0.4610685044478945) assert_allclose(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j) assert_allclose(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3)) assert_allclose(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j)) assert_allclose(special.hankel1(-0.5, 1+1j), special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j)) assert_allclose(special.hankel2(-0.5, 1+1j), special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j)) def test_ticket_854(self): """Real-valued Bessel domains""" assert_(isnan(special.jv(0.5, -1))) assert_(isnan(special.iv(0.5, -1))) assert_(isnan(special.yv(0.5, -1))) assert_(isnan(special.yv(1, -1))) assert_(isnan(special.kv(0.5, -1))) assert_(isnan(special.kv(1, -1))) assert_(isnan(special.jve(0.5, -1))) assert_(isnan(special.ive(0.5, -1))) assert_(isnan(special.yve(0.5, -1))) assert_(isnan(special.yve(1, -1))) assert_(isnan(special.kve(0.5, -1))) assert_(isnan(special.kve(1, -1))) assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1)) assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1)) def test_gh_7909(self): assert_(special.kv(1.5, 0) == np.inf) assert_(special.kve(1.5, 0) == np.inf) def test_ticket_503(self): """Real-valued Bessel I overflow""" assert_allclose(special.iv(1, 700), 1.528500390233901e302) assert_allclose(special.iv(1000, 1120), 1.301564549405821e301) def test_iv_hyperg_poles(self): assert_allclose(special.iv(-0.5, 1), 1.231200214592967) def iv_series(self, v, z, n=200): k = arange(0, n).astype(float_) r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1) r[isnan(r)] = inf r = exp(r) err = abs(r).max() * finfo(float_).eps * n + abs(r[-1])*10 return r.sum(), err def test_i0_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(0, z) assert_allclose(special.i0(z), value, atol=err, err_msg=z) def test_i1_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(1, z) assert_allclose(special.i1(z), value, atol=err, err_msg=z) def test_iv_series(self): for v in [-20., -10., -1., 0., 1., 12.49, 120.]: for z in [1., 10., 200.5, -1+2j]: value, err = self.iv_series(v, z) assert_allclose(special.iv(v, z), value, atol=err, err_msg=(v, z)) def test_i0(self): values = [[0.0, 1.0], [1e-10, 1.0], [0.1, 0.9071009258], [0.5, 0.6450352706], [1.0, 0.4657596077], [2.5, 0.2700464416], [5.0, 0.1835408126], [20.0, 0.0897803119], ] for i, (x, v) in enumerate(values): cv = special.i0(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i0e(self): oize = special.i0e(.1) oizer = special.ive(0,.1) assert_almost_equal(oize,oizer,8) def test_i1(self): values = [[0.0, 0.0], [1e-10, 0.4999999999500000e-10], [0.1, 0.0452984468], [0.5, 0.1564208032], [1.0, 0.2079104154], [5.0, 0.1639722669], [20.0, 0.0875062222], ] for i, (x, v) in enumerate(values): cv = special.i1(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i1e(self): oi1e = special.i1e(.1) oi1er = special.ive(1,.1) assert_almost_equal(oi1e,oi1er,8) def test_iti0k0(self): iti0 = array(special.iti0k0(5)) assert_array_almost_equal(iti0,array([31.848667776169801, 1.5673873907283657]),5) def test_it2i0k0(self): it2k = special.it2i0k0(.1) assert_array_almost_equal(it2k,array([0.0012503906973464409, 3.3309450354686687]),6) def test_iv(self): iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(iv1,0.90710092578230106,10) def test_negv_ive(self): assert_equal(special.ive(3,2), special.ive(-3,2)) def test_ive(self): ive1 = special.ive(0,.1) iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(ive1,iv1,10) def test_ivp0(self): assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10) def test_ivp(self): y = (special.iv(0,2) + special.iv(2,2))/2 x = special.ivp(1,2) assert_almost_equal(x,y,10) class TestLaguerre(object): def test_laguerre(self): lag0 = special.laguerre(0) lag1 = special.laguerre(1) lag2 = special.laguerre(2) lag3 = special.laguerre(3) lag4 = special.laguerre(4) lag5 = special.laguerre(5) assert_array_almost_equal(lag0.c,[1],13) assert_array_almost_equal(lag1.c,[-1,1],13) assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13) assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13) assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) def test_genlaguerre(self): k = 5*np.random.random() - 0.9 lag0 = special.genlaguerre(0,k) lag1 = special.genlaguerre(1,k) lag2 = special.genlaguerre(2,k) lag3 = special.genlaguerre(3,k) assert_equal(lag0.c,[1]) assert_equal(lag1.c,[-1,k+1]) assert_almost_equal(lag2.c,array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0) assert_almost_equal(lag3.c,array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0) # Base polynomials come from Abrahmowitz and Stegan class TestLegendre(object): def test_legendre(self): leg0 = special.legendre(0) leg1 = special.legendre(1) leg2 = special.legendre(2) leg3 = special.legendre(3) leg4 = special.legendre(4) leg5 = special.legendre(5) assert_equal(leg0.c, [1]) assert_equal(leg1.c, [1,0]) assert_almost_equal(leg2.c, array([3,0,-1])/2.0, decimal=13) assert_almost_equal(leg3.c, array([5,0,-3,0])/2.0) assert_almost_equal(leg4.c, array([35,0,-30,0,3])/8.0) assert_almost_equal(leg5.c, array([63,0,-70,0,15,0])/8.0) class TestLambda(object): def test_lmbda(self): lam = special.lmbda(1,.1) lamr = (array([special.jn(0,.1), 2*special.jn(1,.1)/.1]), array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])) assert_array_almost_equal(lam,lamr,8) class TestLog1p(object): def test_log1p(self): l1p = (special.log1p(10), special.log1p(11), special.log1p(12)) l1prl = (log(11), log(12), log(13)) assert_array_almost_equal(l1p,l1prl,8) def test_log1pmore(self): l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2)) l1pmrl = (log(2),log(2.1),log(2.2)) assert_array_almost_equal(l1pm,l1pmrl,8) class TestLegendreFunctions(object): def test_clpmn(self): z = 0.5+0.3j clp = special.clpmn(2, 2, z, 3) assert_array_almost_equal(clp, (array([[1.0000, z, 0.5*(3*z*z-1)], [0.0000, sqrt(z*z-1), 3*z*sqrt(z*z-1)], [0.0000, 0.0000, 3*(z*z-1)]]), array([[0.0000, 1.0000, 3*z], [0.0000, z/sqrt(z*z-1), 3*(2*z*z-1)/sqrt(z*z-1)], [0.0000, 0.0000, 6*z]])), 7) def test_clpmn_close_to_real_2(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x), special.lpmv(m, n, x)]), 7) def test_clpmn_close_to_real_3(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi), special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]), 7) def test_clpmn_across_unit_circle(self): eps = 1e-7 m = 1 n = 1 x = 1j for type in [2, 3]: assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n], special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6) def test_inf(self): for z in (1, -1): for n in range(4): for m in range(1, n): lp = special.clpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) lp = special.lpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) def test_deriv_clpmn(self): # data inside and outside of the unit circle zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j, 1+1j, -1+1j, -1-1j, 1-1j] m = 2 n = 3 for type in [2, 3]: for z in zvals: for h in [1e-3, 1e-3j]: approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0] - special.clpmn(m, n, z-0.5*h, type)[0])/h assert_allclose(special.clpmn(m, n, z, type)[1], approx_derivative, rtol=1e-4) def test_lpmn(self): lp = special.lpmn(0,2,.5) assert_array_almost_equal(lp,(array([[1.00000, 0.50000, -0.12500]]), array([[0.00000, 1.00000, 1.50000]])),4) def test_lpn(self): lpnf = special.lpn(2,.5) assert_array_almost_equal(lpnf,(array([1.00000, 0.50000, -0.12500]), array([0.00000, 1.00000, 1.50000])),4) def test_lpmv(self): lp = special.lpmv(0,2,.5) assert_almost_equal(lp,-0.125,7) lp = special.lpmv(0,40,.001) assert_almost_equal(lp,0.1252678976534484,7) # XXX: this is outside the domain of the current implementation, # so ensure it returns a NaN rather than a wrong answer. olderr = np.seterr(all='ignore') try: lp = special.lpmv(-1,-1,.001) finally: np.seterr(**olderr) assert_(lp != 0 or np.isnan(lp)) def test_lqmn(self): lqmnf = special.lqmn(0,2,.5) lqf = special.lqn(2,.5) assert_array_almost_equal(lqmnf[0][0],lqf[0],4) assert_array_almost_equal(lqmnf[1][0],lqf[1],4) def test_lqmn_gt1(self): """algorithm for real arguments changes at 1.0001 test against analytical result for m=2, n=1 """ x0 = 1.0001 delta = 0.00002 for x in (x0-delta, x0+delta): lq = special.lqmn(2, 1, x)[0][-1, -1] expected = 2/(x*x-1) assert_almost_equal(lq, expected) def test_lqmn_shape(self): a, b = special.lqmn(4, 4, 1.1) assert_equal(a.shape, (5, 5)) assert_equal(b.shape, (5, 5)) a, b = special.lqmn(4, 0, 1.1) assert_equal(a.shape, (5, 1)) assert_equal(b.shape, (5, 1)) def test_lqn(self): lqf = special.lqn(2,.5) assert_array_almost_equal(lqf,(array([0.5493, -0.7253, -0.8187]), array([1.3333, 1.216, -0.8427])),4) class TestMathieu(object): def test_mathieu_a(self): pass def test_mathieu_even_coef(self): special.mathieu_even_coef(2,5) # Q not defined broken and cannot figure out proper reporting order def test_mathieu_odd_coef(self): # same problem as above pass class TestFresnelIntegral(object): def test_modfresnelp(self): pass def test_modfresnelm(self): pass class TestOblCvSeq(object): def test_obl_cv_seq(self): obl = special.obl_cv_seq(0,3,1) assert_array_almost_equal(obl,array([-0.348602, 1.393206, 5.486800, 11.492120]),5) class TestParabolicCylinder(object): def test_pbdn_seq(self): pb = special.pbdn_seq(1,.1) assert_array_almost_equal(pb,(array([0.9975, 0.0998]), array([-0.0499, 0.9925])),4) def test_pbdv(self): special.pbdv(1,.2) 1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0] def test_pbdv_seq(self): pbn = special.pbdn_seq(1,.1) pbv = special.pbdv_seq(1,.1) assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) def test_pbdv_points(self): # simple case eta = np.linspace(-10, 10, 5) z = 2**(eta/2)*np.sqrt(np.pi)/special.gamma(.5-.5*eta) assert_allclose(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14) # some points assert_allclose(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12) assert_allclose(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12) def test_pbdv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbdv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) def test_pbvv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbvv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) class TestPolygamma(object): # from Table 6.2 (pg. 271) of A&S def test_polygamma(self): poly2 = special.polygamma(2,1) poly3 = special.polygamma(3,1) assert_almost_equal(poly2,-2.4041138063,10) assert_almost_equal(poly3,6.4939394023,10) # Test polygamma(0, x) == psi(x) x = [2, 3, 1.1e14] assert_almost_equal(special.polygamma(0, x), special.psi(x)) # Test broadcasting n = [0, 1, 2] x = [0.5, 1.5, 2.5] expected = [-1.9635100260214238, 0.93480220054467933, -0.23620405164172739] assert_almost_equal(special.polygamma(n, x), expected) expected = np.row_stack([expected]*2) assert_almost_equal(special.polygamma(n, np.row_stack([x]*2)), expected) assert_almost_equal(special.polygamma(np.row_stack([n]*2), x), expected) class TestProCvSeq(object): def test_pro_cv_seq(self): prol = special.pro_cv_seq(0,3,1) assert_array_almost_equal(prol,array([0.319000, 2.593084, 6.533471, 12.514462]),5) class TestPsi(object): def test_psi(self): ps = special.psi(1) assert_almost_equal(ps,-0.57721566490153287,8) class TestRadian(object): def test_radian(self): rad = special.radian(90,0,0) assert_almost_equal(rad,pi/2.0,5) def test_radianmore(self): rad1 = special.radian(90,1,60) assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) class TestRiccati(object): def test_riccati_jn(self): N, x = 2, 0.2 S = np.empty((N, N)) for n in range(N): j = special.spherical_jn(n, x) jp = special.spherical_jn(n, x, derivative=True) S[0,n] = x*j S[1,n] = x*jp + j assert_array_almost_equal(S, special.riccati_jn(n, x), 8) def test_riccati_yn(self): N, x = 2, 0.2 C = np.empty((N, N)) for n in range(N): y = special.spherical_yn(n, x) yp = special.spherical_yn(n, x, derivative=True) C[0,n] = x*y C[1,n] = x*yp + y assert_array_almost_equal(C, special.riccati_yn(n, x), 8) class TestRound(object): def test_round(self): rnd = list(map(int,(special.round(10.1),special.round(10.4),special.round(10.5),special.round(10.6)))) # Note: According to the documentation, scipy.special.round is # supposed to round to the nearest even number if the fractional # part is exactly 0.5. On some platforms, this does not appear # to work and thus this test may fail. However, this unit test is # correctly written. rndrl = (10,10,10,11) assert_array_equal(rnd,rndrl) def test_sph_harm(): # Tests derived from tables in # https://en.wikipedia.org/wiki/Table_of_spherical_harmonics sh = special.sph_harm pi = np.pi exp = np.exp sqrt = np.sqrt sin = np.sin cos = np.cos assert_array_almost_equal(sh(0,0,0,0), 0.5/sqrt(pi)) assert_array_almost_equal(sh(-2,2,0.,pi/4), 0.25*sqrt(15./(2.*pi)) * (sin(pi/4))**2.) assert_array_almost_equal(sh(-2,2,0.,pi/2), 0.25*sqrt(15./(2.*pi))) assert_array_almost_equal(sh(2,2,pi,pi/2), 0.25*sqrt(15/(2.*pi)) * exp(0+2.*pi*1j)*sin(pi/2.)**2.) assert_array_almost_equal(sh(2,4,pi/4.,pi/3.), (3./8.)*sqrt(5./(2.*pi)) * exp(0+2.*pi/4.*1j) * sin(pi/3.)**2. * (7.*cos(pi/3.)**2.-1)) assert_array_almost_equal(sh(4,4,pi/8.,pi/6.), (3./16.)*sqrt(35./(2.*pi)) * exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.) def test_sph_harm_ufunc_loop_selection(): # see https://github.com/scipy/scipy/issues/4895 dt = np.dtype(np.complex128) assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt) assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt) assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt) assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt) assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt) assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt) class TestStruve(object): def _series(self, v, z, n=100): """Compute Struve function & error estimate from its power series.""" k = arange(0, n) r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5) err = abs(r).max() * finfo(float_).eps * n return r.sum(), err def test_vs_series(self): """Check Struve function versus its power series""" for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]: for z in [1, 10, 19, 21, 30]: value, err = self._series(v, z) assert_allclose(special.struve(v, z), value, rtol=0, atol=err), (v, z) def test_some_values(self): assert_allclose(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7) assert_allclose(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8) assert_allclose(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12) assert_allclose(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11) assert_equal(special.struve(-12, -41), -special.struve(-12, 41)) assert_equal(special.struve(+12, -41), -special.struve(+12, 41)) assert_equal(special.struve(-11, -41), +special.struve(-11, 41)) assert_equal(special.struve(+11, -41), +special.struve(+11, 41)) assert_(isnan(special.struve(-7.1, -1))) assert_(isnan(special.struve(-10.1, -1))) def test_regression_679(self): """Regression test for #679""" assert_allclose(special.struve(-1.0, 20 - 1e-8), special.struve(-1.0, 20 + 1e-8)) assert_allclose(special.struve(-2.0, 20 - 1e-8), special.struve(-2.0, 20 + 1e-8)) assert_allclose(special.struve(-4.3, 20 - 1e-8), special.struve(-4.3, 20 + 1e-8)) def test_chi2_smalldf(): assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110) def test_ch2_inf(): assert_equal(special.chdtr(0.7,np.inf), 1.0) def test_chi2c_smalldf(): assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110) def test_chi2_inv_smalldf(): assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3) def test_agm_simple(): rtol = 1e-13 # Gauss's constant assert_allclose(1/special.agm(1, np.sqrt(2)), 0.834626841674073186, rtol=rtol) # These values were computed using Wolfram Alpha, with the # function ArithmeticGeometricMean[a, b]. agm13 = 1.863616783244897 agm15 = 2.604008190530940 agm35 = 3.936235503649555 assert_allclose(special.agm([[1], [3]], [1, 3, 5]), [[1, agm13, agm15], [agm13, 3, agm35]], rtol=rtol) # Computed by the iteration formula using mpmath, # with mpmath.mp.prec = 1000: agm12 = 1.4567910310469068 assert_allclose(special.agm(1, 2), agm12, rtol=rtol) assert_allclose(special.agm(2, 1), agm12, rtol=rtol) assert_allclose(special.agm(-1, -2), -agm12, rtol=rtol) assert_allclose(special.agm(24, 6), 13.458171481725614, rtol=rtol) assert_allclose(special.agm(13, 123456789.5), 11111458.498599306, rtol=rtol) assert_allclose(special.agm(1e30, 1), 2.229223055945383e+28, rtol=rtol) assert_allclose(special.agm(1e-22, 1), 0.030182566420169886, rtol=rtol) assert_allclose(special.agm(1e150, 1e180), 2.229223055945383e+178, rtol=rtol) assert_allclose(special.agm(1e180, 1e-150), 2.0634722510162677e+177, rtol=rtol) assert_allclose(special.agm(1e-150, 1e-170), 3.3112619670463756e-152, rtol=rtol) fi = np.finfo(1.0) assert_allclose(special.agm(fi.tiny, fi.max), 1.9892072050015473e+305, rtol=rtol) assert_allclose(special.agm(0.75*fi.max, fi.max), 1.564904312298045e+308, rtol=rtol) assert_allclose(special.agm(fi.tiny, 3*fi.tiny), 4.1466849866735005e-308, rtol=rtol) # zero, nan and inf cases. assert_equal(special.agm(0, 0), 0) assert_equal(special.agm(99, 0), 0) assert_equal(special.agm(-1, 10), np.nan) assert_equal(special.agm(0, np.inf), np.nan) assert_equal(special.agm(np.inf, 0), np.nan) assert_equal(special.agm(0, -np.inf), np.nan) assert_equal(special.agm(-np.inf, 0), np.nan) assert_equal(special.agm(np.inf, -np.inf), np.nan) assert_equal(special.agm(-np.inf, np.inf), np.nan) assert_equal(special.agm(1, np.nan), np.nan) assert_equal(special.agm(np.nan, -1), np.nan) assert_equal(special.agm(1, np.inf), np.inf) assert_equal(special.agm(np.inf, 1), np.inf) assert_equal(special.agm(-1, -np.inf), -np.inf) assert_equal(special.agm(-np.inf, -1), -np.inf) def test_legacy(): # Legacy behavior: truncating arguments to integers with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3)) assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3)) assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3)) assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3)) assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3)) assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3)) assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3)) assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3)) assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3)) @with_special_errors def test_error_raising(): assert_raises(special.SpecialFunctionError, special.iv, 1, 1e99j) def test_xlogy(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x*np.log(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float) z2 = np.r_[z1, [(0, 1j), (1, 1j)]] w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13) w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1]) assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13) def test_xlog1py(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x * np.log1p(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0), (1, 1e-30)], dtype=float) w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13) def test_entr(): def xfunc(x): if x < 0: return -np.inf else: return -special.xlogy(x, x) values = (0, 0.5, 1.0, np.inf) signs = [-1, 1] arr = [] for sgn, v in itertools.product(signs, values): arr.append(sgn * v) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z) assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13) def test_kl_div(): def xfunc(x, y): if x < 0 or y < 0 or (y == 0 and x != 0): # extension of natural domain to preserve convexity return np.inf elif np.isposinf(x) or np.isposinf(y): # limits within the natural domain return np.inf elif x == 0: return y else: return special.xlogy(x, x/y) - x + y values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13) def test_rel_entr(): def xfunc(x, y): if x > 0 and y > 0: return special.xlogy(x, x/y) elif x == 0 and y >= 0: return 0 else: return np.inf values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13) def test_huber(): assert_equal(special.huber(-1, 1.5), np.inf) assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5)) assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2)) def xfunc(delta, r): if delta < 0: return np.inf elif np.abs(r) < delta: return 0.5 * np.square(r) else: return delta * (np.abs(r) - 0.5 * delta) z = np.random.randn(10, 2) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13) def test_pseudo_huber(): def xfunc(delta, r): if delta < 0: return np.inf elif (not delta) or (not r): return 0 else: return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1) z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]]) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13)
aeklant/scipy
scipy/special/tests/test_basic.py
scipy/integrate/tests/test_quadrature.py
""" Functions that operate on sparse matrices """ __all__ = ['count_blocks','estimate_blocksize'] from .csr import isspmatrix_csr, csr_matrix from .csc import isspmatrix_csc from ._sparsetools import csr_count_blocks def extract_diagonal(A): raise NotImplementedError('use .diagonal() instead') #def extract_diagonal(A): # """extract_diagonal(A) returns the main diagonal of A.""" # #TODO extract kth diagonal # if isspmatrix_csr(A) or isspmatrix_csc(A): # fn = getattr(sparsetools, A.format + "_diagonal") # y = empty( min(A.shape), dtype=upcast(A.dtype) ) # fn(A.shape[0],A.shape[1],A.indptr,A.indices,A.data,y) # return y # elif isspmatrix_bsr(A): # M,N = A.shape # R,C = A.blocksize # y = empty( min(M,N), dtype=upcast(A.dtype) ) # fn = sparsetools.bsr_diagonal(M//R, N//C, R, C, \ # A.indptr, A.indices, ravel(A.data), y) # return y # else: # return extract_diagonal(csr_matrix(A)) def estimate_blocksize(A,efficiency=0.7): """Attempt to determine the blocksize of a sparse matrix Returns a blocksize=(r,c) such that - A.nnz / A.tobsr( (r,c) ).nnz > efficiency """ if not (isspmatrix_csr(A) or isspmatrix_csc(A)): A = csr_matrix(A) if A.nnz == 0: return (1,1) if not 0 < efficiency < 1.0: raise ValueError('efficiency must satisfy 0.0 < efficiency < 1.0') high_efficiency = (1.0 + efficiency) / 2.0 nnz = float(A.nnz) M,N = A.shape if M % 2 == 0 and N % 2 == 0: e22 = nnz / (4 * count_blocks(A,(2,2))) else: e22 = 0.0 if M % 3 == 0 and N % 3 == 0: e33 = nnz / (9 * count_blocks(A,(3,3))) else: e33 = 0.0 if e22 > high_efficiency and e33 > high_efficiency: e66 = nnz / (36 * count_blocks(A,(6,6))) if e66 > efficiency: return (6,6) else: return (3,3) else: if M % 4 == 0 and N % 4 == 0: e44 = nnz / (16 * count_blocks(A,(4,4))) else: e44 = 0.0 if e44 > efficiency: return (4,4) elif e33 > efficiency: return (3,3) elif e22 > efficiency: return (2,2) else: return (1,1) def count_blocks(A,blocksize): """For a given blocksize=(r,c) count the number of occupied blocks in a sparse matrix A """ r,c = blocksize if r < 1 or c < 1: raise ValueError('r and c must be positive') if isspmatrix_csr(A): M,N = A.shape return csr_count_blocks(M,N,r,c,A.indptr,A.indices) elif isspmatrix_csc(A): return count_blocks(A.T,(c,r)) else: return count_blocks(csr_matrix(A),blocksize)
# this program corresponds to special.py ### Means test is not done yet # E Means test is giving error (E) # F Means test is failing (F) # EF Means test is giving error and Failing #! Means test is segfaulting # 8 Means test runs forever ### test_besselpoly ### test_mathieu_a ### test_mathieu_even_coef ### test_mathieu_odd_coef ### test_modfresnelp ### test_modfresnelm # test_pbdv_seq ### test_pbvv_seq ### test_sph_harm import itertools import platform import numpy as np from numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp, log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, float_) import pytest from pytest import raises as assert_raises from numpy.testing import (assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_approx_equal, assert_, assert_allclose, assert_array_almost_equal_nulp, suppress_warnings) from scipy import special import scipy.special._ufuncs as cephes from scipy.special import ellipk from scipy.special._testutils import with_special_errors, \ assert_func_equal, FuncData import math class TestCephes(object): def test_airy(self): cephes.airy(0) def test_airye(self): cephes.airye(0) def test_binom(self): n = np.array([0.264, 4, 5.2, 17]) k = np.array([2, 0.4, 7, 3.3]) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389, -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846], [10.92, 2.22993515861399, -0.00585728, 10.468891352063146], [136, 3.5252179590758828, 19448, 1024.5526916174495]]) assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13) # Test branches in implementation np.random.seed(1234) n = np.r_[np.arange(-7, 30), 1000*np.random.rand(30) - 500] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_2(self): # Test branches in implementation np.random.seed(1234) n = np.r_[np.logspace(1, 300, 20)] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_exact(self): @np.vectorize def binom_int(n, k): n = int(n) k = int(k) num = int(1) den = int(1) for i in range(1, k+1): num *= i + n - k den *= i return float(num/den) np.random.seed(1234) n = np.arange(1, 15) k = np.arange(0, 15) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T nk = nk[nk[:,0] >= nk[:,1]] assert_func_equal(cephes.binom, binom_int(nk[:,0], nk[:,1]), nk, atol=0, rtol=0) def test_binom_nooverflow_8346(self): # Test (binom(n, k) doesn't overflow prematurely */ dataset = [ (1000, 500, 2.70288240945436551e+299), (1002, 501, 1.08007396880791225e+300), (1004, 502, 4.31599279169058121e+300), (1006, 503, 1.72468101616263781e+301), (1008, 504, 6.89188009236419153e+301), (1010, 505, 2.75402257948335448e+302), (1012, 506, 1.10052048531923757e+303), (1014, 507, 4.39774063758732849e+303), (1016, 508, 1.75736486108312519e+304), (1018, 509, 7.02255427788423734e+304), (1020, 510, 2.80626776829962255e+305), (1022, 511, 1.12140876377061240e+306), (1024, 512, 4.48125455209897109e+306), (1026, 513, 1.79075474304149900e+307), (1028, 514, 7.15605105487789676e+307) ] dataset = np.asarray(dataset) FuncData(cephes.binom, dataset, (0, 1), 2, rtol=1e-12).check() def test_bdtr(self): assert_equal(cephes.bdtr(1,1,0.5),1.0) def test_bdtri(self): assert_equal(cephes.bdtri(1,3,0.5),0.5) def test_bdtrc(self): assert_equal(cephes.bdtrc(1,3,0.5),0.5) def test_bdtrin(self): assert_equal(cephes.bdtrin(1,0,1),5.0) def test_bdtrik(self): cephes.bdtrik(1,3,0.5) def test_bei(self): assert_equal(cephes.bei(0),0.0) def test_beip(self): assert_equal(cephes.beip(0),0.0) def test_ber(self): assert_equal(cephes.ber(0),1.0) def test_berp(self): assert_equal(cephes.berp(0),0.0) def test_besselpoly(self): assert_equal(cephes.besselpoly(0,0,0),1.0) def test_beta(self): assert_equal(cephes.beta(1,1),1.0) assert_allclose(cephes.beta(-100.3, 1e-200), cephes.gamma(1e-200)) assert_allclose(cephes.beta(0.0342, 171), 24.070498359873497, rtol=1e-13, atol=0) def test_betainc(self): assert_equal(cephes.betainc(1,1,1),1.0) assert_allclose(cephes.betainc(0.0342, 171, 1e-10), 0.55269916901806648) def test_betaln(self): assert_equal(cephes.betaln(1,1),0.0) assert_allclose(cephes.betaln(-100.3, 1e-200), cephes.gammaln(1e-200)) assert_allclose(cephes.betaln(0.0342, 170), 3.1811881124242447, rtol=1e-14, atol=0) def test_betaincinv(self): assert_equal(cephes.betaincinv(1,1,1),1.0) assert_allclose(cephes.betaincinv(0.0342, 171, 0.25), 8.4231316935498957e-21, rtol=3e-12, atol=0) def test_beta_inf(self): assert_(np.isinf(special.beta(-1, 2))) def test_btdtr(self): assert_equal(cephes.btdtr(1,1,1),1.0) def test_btdtri(self): assert_equal(cephes.btdtri(1,1,1),1.0) def test_btdtria(self): assert_equal(cephes.btdtria(1,1,1),5.0) def test_btdtrib(self): assert_equal(cephes.btdtrib(1,1,1),5.0) def test_cbrt(self): assert_approx_equal(cephes.cbrt(1),1.0) def test_chdtr(self): assert_equal(cephes.chdtr(1,0),0.0) def test_chdtrc(self): assert_equal(cephes.chdtrc(1,0),1.0) def test_chdtri(self): assert_equal(cephes.chdtri(1,1),0.0) def test_chdtriv(self): assert_equal(cephes.chdtriv(0,0),5.0) def test_chndtr(self): assert_equal(cephes.chndtr(0,1,0),0.0) # Each row holds (x, nu, lam, expected_value) # These values were computed using Wolfram Alpha with # CDF[NoncentralChiSquareDistribution[nu, lam], x] values = np.array([ [25.00, 20.0, 400, 4.1210655112396197139e-57], [25.00, 8.00, 250, 2.3988026526832425878e-29], [0.001, 8.00, 40., 5.3761806201366039084e-24], [0.010, 8.00, 40., 5.45396231055999457039e-20], [20.00, 2.00, 107, 1.39390743555819597802e-9], [22.50, 2.00, 107, 7.11803307138105870671e-9], [25.00, 2.00, 107, 3.11041244829864897313e-8], [3.000, 2.00, 1.0, 0.62064365321954362734], [350.0, 300., 10., 0.93880128006276407710], [100.0, 13.5, 10., 0.99999999650104210949], [700.0, 20.0, 400, 0.99999999925680650105], [150.0, 13.5, 10., 0.99999999999999983046], [160.0, 13.5, 10., 0.99999999999999999518], # 1.0 ]) cdf = cephes.chndtr(values[:, 0], values[:, 1], values[:, 2]) assert_allclose(cdf, values[:, 3], rtol=1e-12) assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0) assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0) assert_(np.isnan(cephes.chndtr(np.nan, 1, 2))) assert_(np.isnan(cephes.chndtr(5, np.nan, 2))) assert_(np.isnan(cephes.chndtr(5, 1, np.nan))) def test_chndtridf(self): assert_equal(cephes.chndtridf(0,0,1),5.0) def test_chndtrinc(self): assert_equal(cephes.chndtrinc(0,1,0),5.0) def test_chndtrix(self): assert_equal(cephes.chndtrix(0,1,0),0.0) def test_cosdg(self): assert_equal(cephes.cosdg(0),1.0) def test_cosm1(self): assert_equal(cephes.cosm1(0),0.0) def test_cotdg(self): assert_almost_equal(cephes.cotdg(45),1.0) def test_dawsn(self): assert_equal(cephes.dawsn(0),0.0) assert_allclose(cephes.dawsn(1.23), 0.50053727749081767) def test_diric(self): # Test behavior near multiples of 2pi. Regression test for issue # described in gh-4001. n_odd = [1, 5, 25] x = np.array(2*np.pi + 5e-5).astype(np.float32) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7) x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) x = np.array(2*np.pi + 1e-15).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) if hasattr(np, 'float128'): # No float128 available in 32-bit numpy x = np.array(2*np.pi + 1e-12).astype(np.float128) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19) n_even = [2, 4, 24] x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15) # Test at some values not near a multiple of pi x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi) octave_result = [0.872677996249965, 0.539344662916632, 0.127322003750035, -0.206011329583298] assert_almost_equal(special.diric(x, 3), octave_result, decimal=15) def test_diric_broadcasting(self): x = np.arange(5) n = np.array([1, 3, 7]) assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size)) def test_ellipe(self): assert_equal(cephes.ellipe(1),1.0) def test_ellipeinc(self): assert_equal(cephes.ellipeinc(0,1),0.0) def test_ellipj(self): cephes.ellipj(0,1) def test_ellipk(self): assert_allclose(ellipk(0), pi/2) def test_ellipkinc(self): assert_equal(cephes.ellipkinc(0,0),0.0) def test_erf(self): assert_equal(cephes.erf(0), 0.0) def test_erf_symmetry(self): x = 5.905732037710919 assert_equal(cephes.erf(x) + cephes.erf(-x), 0.0) def test_erfc(self): assert_equal(cephes.erfc(0), 1.0) def test_exp10(self): assert_approx_equal(cephes.exp10(2),100.0) def test_exp2(self): assert_equal(cephes.exp2(2),4.0) def test_expm1(self): assert_equal(cephes.expm1(0),0.0) assert_equal(cephes.expm1(np.inf), np.inf) assert_equal(cephes.expm1(-np.inf), -1) assert_equal(cephes.expm1(np.nan), np.nan) def test_expm1_complex(self): expm1 = cephes.expm1 assert_equal(expm1(0 + 0j), 0 + 0j) assert_equal(expm1(complex(np.inf, 0)), complex(np.inf, 0)) assert_equal(expm1(complex(np.inf, 1)), complex(np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 2)), complex(-np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 4)), complex(-np.inf, -np.inf)) assert_equal(expm1(complex(np.inf, 5)), complex(np.inf, -np.inf)) assert_equal(expm1(complex(1, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(0, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.inf, np.inf)), complex(np.inf, np.nan)) assert_equal(expm1(complex(-np.inf, np.inf)), complex(-1, 0)) assert_equal(expm1(complex(-np.inf, np.nan)), complex(-1, 0)) assert_equal(expm1(complex(np.inf, np.nan)), complex(np.inf, np.nan)) assert_equal(expm1(complex(0, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(1, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, 1)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, np.nan)), complex(np.nan, np.nan)) @pytest.mark.xfail(reason='The real part of expm1(z) bad at these points') def test_expm1_complex_hard(self): # The real part of this function is difficult to evaluate when # z.real = -log(cos(z.imag)). y = np.array([0.1, 0.2, 0.3, 5, 11, 20]) x = -np.log(np.cos(y)) z = x + 1j*y # evaluate using mpmath.expm1 with dps=1000 expected = np.array([-5.5507901846769623e-17+0.10033467208545054j, 2.4289354732893695e-18+0.20271003550867248j, 4.5235500262585768e-17+0.30933624960962319j, 7.8234305217489006e-17-3.3805150062465863j, -1.3685191953697676e-16-225.95084645419513j, 8.7175620481291045e-17+2.2371609442247422j]) found = cephes.expm1(z) # this passes. assert_array_almost_equal_nulp(found.imag, expected.imag, 3) # this fails. assert_array_almost_equal_nulp(found.real, expected.real, 20) def test_fdtr(self): assert_equal(cephes.fdtr(1, 1, 0), 0.0) # Computed using Wolfram Alpha: CDF[FRatioDistribution[1e-6, 5], 10] assert_allclose(cephes.fdtr(1e-6, 5, 10), 0.9999940790193488, rtol=1e-12) def test_fdtrc(self): assert_equal(cephes.fdtrc(1, 1, 0), 1.0) # Computed using Wolfram Alpha: # 1 - CDF[FRatioDistribution[2, 1/10], 1e10] assert_allclose(cephes.fdtrc(2, 0.1, 1e10), 0.27223784621293512, rtol=1e-12) def test_fdtri(self): assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]), array([0.9937365, 1.00630298]), rtol=1e-6) # From Wolfram Alpha: # CDF[FRatioDistribution[1/10, 1], 3] = 0.8756751669632105666874... p = 0.8756751669632105666874 assert_allclose(cephes.fdtri(0.1, 1, p), 3, rtol=1e-12) @pytest.mark.xfail(reason='Returns nan on i686.') def test_fdtri_mysterious_failure(self): assert_allclose(cephes.fdtri(1, 1, 0.5), 1) def test_fdtridfd(self): assert_equal(cephes.fdtridfd(1,0,0),5.0) def test_fresnel(self): assert_equal(cephes.fresnel(0),(0.0,0.0)) def test_gamma(self): assert_equal(cephes.gamma(5),24.0) def test_gammainccinv(self): assert_equal(cephes.gammainccinv(5,1),0.0) def test_gammaln(self): cephes.gammaln(10) def test_gammasgn(self): vals = np.array([-4, -3.5, -2.3, 1, 4.2], np.float64) assert_array_equal(cephes.gammasgn(vals), np.sign(cephes.rgamma(vals))) def test_gdtr(self): assert_equal(cephes.gdtr(1,1,0),0.0) def test_gdtr_inf(self): assert_equal(cephes.gdtr(1,1,np.inf),1.0) def test_gdtrc(self): assert_equal(cephes.gdtrc(1,1,0),1.0) def test_gdtria(self): assert_equal(cephes.gdtria(0,1,1),0.0) def test_gdtrib(self): cephes.gdtrib(1,0,1) # assert_equal(cephes.gdtrib(1,0,1),5.0) def test_gdtrix(self): cephes.gdtrix(1,1,.1) def test_hankel1(self): cephes.hankel1(1,1) def test_hankel1e(self): cephes.hankel1e(1,1) def test_hankel2(self): cephes.hankel2(1,1) def test_hankel2e(self): cephes.hankel2e(1,1) def test_hyp1f1(self): assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) cephes.hyp1f1(1,1,1) def test_hyp2f1(self): assert_equal(cephes.hyp2f1(1,1,1,0),1.0) def test_i0(self): assert_equal(cephes.i0(0),1.0) def test_i0e(self): assert_equal(cephes.i0e(0),1.0) def test_i1(self): assert_equal(cephes.i1(0),0.0) def test_i1e(self): assert_equal(cephes.i1e(0),0.0) def test_it2i0k0(self): cephes.it2i0k0(1) def test_it2j0y0(self): cephes.it2j0y0(1) def test_it2struve0(self): cephes.it2struve0(1) def test_itairy(self): cephes.itairy(1) def test_iti0k0(self): assert_equal(cephes.iti0k0(0),(0.0,0.0)) def test_itj0y0(self): assert_equal(cephes.itj0y0(0),(0.0,0.0)) def test_itmodstruve0(self): assert_equal(cephes.itmodstruve0(0),0.0) def test_itstruve0(self): assert_equal(cephes.itstruve0(0),0.0) def test_iv(self): assert_equal(cephes.iv(1,0),0.0) def _check_ive(self): assert_equal(cephes.ive(1,0),0.0) def test_j0(self): assert_equal(cephes.j0(0),1.0) def test_j1(self): assert_equal(cephes.j1(0),0.0) def test_jn(self): assert_equal(cephes.jn(0,0),1.0) def test_jv(self): assert_equal(cephes.jv(0,0),1.0) def _check_jve(self): assert_equal(cephes.jve(0,0),1.0) def test_k0(self): cephes.k0(2) def test_k0e(self): cephes.k0e(2) def test_k1(self): cephes.k1(2) def test_k1e(self): cephes.k1e(2) def test_kei(self): cephes.kei(2) def test_keip(self): assert_equal(cephes.keip(0),0.0) def test_ker(self): cephes.ker(2) def test_kerp(self): cephes.kerp(2) def _check_kelvin(self): cephes.kelvin(2) def test_kn(self): cephes.kn(1,1) def test_kolmogi(self): assert_equal(cephes.kolmogi(1),0.0) assert_(np.isnan(cephes.kolmogi(np.nan))) def test_kolmogorov(self): assert_equal(cephes.kolmogorov(0), 1.0) def test_kolmogp(self): assert_equal(cephes._kolmogp(0), -0.0) def test_kolmogc(self): assert_equal(cephes._kolmogc(0), 0.0) def test_kolmogci(self): assert_equal(cephes._kolmogci(0), 0.0) assert_(np.isnan(cephes._kolmogci(np.nan))) def _check_kv(self): cephes.kv(1,1) def _check_kve(self): cephes.kve(1,1) def test_log1p(self): log1p = cephes.log1p assert_equal(log1p(0), 0.0) assert_equal(log1p(-1), -np.inf) assert_equal(log1p(-2), np.nan) assert_equal(log1p(np.inf), np.inf) def test_log1p_complex(self): log1p = cephes.log1p c = complex assert_equal(log1p(0 + 0j), 0 + 0j) assert_equal(log1p(c(-1, 0)), c(-np.inf, 0)) with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in multiply") assert_allclose(log1p(c(1, np.inf)), c(np.inf, np.pi/2)) assert_equal(log1p(c(1, np.nan)), c(np.nan, np.nan)) assert_allclose(log1p(c(-np.inf, 1)), c(np.inf, np.pi)) assert_equal(log1p(c(np.inf, 1)), c(np.inf, 0)) assert_allclose(log1p(c(-np.inf, np.inf)), c(np.inf, 3*np.pi/4)) assert_allclose(log1p(c(np.inf, np.inf)), c(np.inf, np.pi/4)) assert_equal(log1p(c(np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(-np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, np.inf)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, 1)), c(np.nan, np.nan)) assert_equal(log1p(c(np.nan, np.nan)), c(np.nan, np.nan)) def test_lpmv(self): assert_equal(cephes.lpmv(0,0,1),1.0) def test_mathieu_a(self): assert_equal(cephes.mathieu_a(1,0),1.0) def test_mathieu_b(self): assert_equal(cephes.mathieu_b(1,0),1.0) def test_mathieu_cem(self): assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) # Test AMS 20.2.27 @np.vectorize def ce_smallq(m, q, z): z *= np.pi/180 if m == 0: return 2**(-0.5) * (1 - .5*q*cos(2*z)) # + O(q^2) elif m == 1: return cos(z) - q/8 * cos(3*z) # + O(q^2) elif m == 2: return cos(2*z) - q*(cos(4*z)/12 - 1/4) # + O(q^2) else: return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(0, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0], ce_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_sem(self): assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) # Test AMS 20.2.27 @np.vectorize def se_smallq(m, q, z): z *= np.pi/180 if m == 1: return sin(z) - q/8 * sin(3*z) # + O(q^2) elif m == 2: return sin(2*z) - q*sin(4*z)/12 # + O(q^2) else: return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(1, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0], se_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_modcem1(self): assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) def test_mathieu_modcem2(self): cephes.mathieu_modcem2(1,1,1) # Test reflection relation AMS 20.6.19 m = np.arange(0, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modcem2(m, q, -z)[0] fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0] y2 = -cephes.mathieu_modcem2(m, q, z)[0] - 2*fr*cephes.mathieu_modcem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_modsem1(self): assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) def test_mathieu_modsem2(self): cephes.mathieu_modsem2(1,1,1) # Test reflection relation AMS 20.6.20 m = np.arange(1, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modsem2(m, q, -z)[0] fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1] y2 = cephes.mathieu_modsem2(m, q, z)[0] - 2*fr*cephes.mathieu_modsem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_overflow(self): # Check that these return NaNs instead of causing a SEGV assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan)) def test_mathieu_ticket_1847(self): # Regression test --- this call had some out-of-bounds access # and could return nan occasionally for k in range(60): v = cephes.mathieu_modsem2(2, 100, -1) # Values from ACM TOMS 804 (derivate by numerical differentiation) assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10) assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4) def test_modfresnelm(self): cephes.modfresnelm(0) def test_modfresnelp(self): cephes.modfresnelp(0) def _check_modstruve(self): assert_equal(cephes.modstruve(1,0),0.0) def test_nbdtr(self): assert_equal(cephes.nbdtr(1,1,1),1.0) def test_nbdtrc(self): assert_equal(cephes.nbdtrc(1,1,1),0.0) def test_nbdtri(self): assert_equal(cephes.nbdtri(1,1,1),1.0) def __check_nbdtrik(self): cephes.nbdtrik(1,.4,.5) def test_nbdtrin(self): assert_equal(cephes.nbdtrin(1,0,0),5.0) def test_ncfdtr(self): assert_equal(cephes.ncfdtr(1,1,1,0),0.0) def test_ncfdtri(self): assert_equal(cephes.ncfdtri(1, 1, 1, 0), 0.0) f = [0.5, 1, 1.5] p = cephes.ncfdtr(2, 3, 1.5, f) assert_allclose(cephes.ncfdtri(2, 3, 1.5, p), f) def test_ncfdtridfd(self): dfd = [1, 2, 3] p = cephes.ncfdtr(2, dfd, 0.25, 15) assert_allclose(cephes.ncfdtridfd(2, p, 0.25, 15), dfd) def test_ncfdtridfn(self): dfn = [0.1, 1, 2, 3, 1e4] p = cephes.ncfdtr(dfn, 2, 0.25, 15) assert_allclose(cephes.ncfdtridfn(p, 2, 0.25, 15), dfn, rtol=1e-5) def test_ncfdtrinc(self): nc = [0.5, 1.5, 2.0] p = cephes.ncfdtr(2, 3, nc, 15) assert_allclose(cephes.ncfdtrinc(2, 3, p, 15), nc) def test_nctdtr(self): assert_equal(cephes.nctdtr(1,0,0),0.5) assert_equal(cephes.nctdtr(9, 65536, 45), 0.0) assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5) assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.))) assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.) assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.))) assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.))) assert_(np.isnan(cephes.nctdtr(2., 1., np.nan))) def __check_nctdtridf(self): cephes.nctdtridf(1,0.5,0) def test_nctdtrinc(self): cephes.nctdtrinc(1,0,0) def test_nctdtrit(self): cephes.nctdtrit(.1,0.2,.5) def test_nrdtrimn(self): assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) def test_nrdtrisd(self): assert_allclose(cephes.nrdtrisd(0.5,0.5,0.5), 0.0, atol=0, rtol=0) def test_obl_ang1(self): cephes.obl_ang1(1,1,1,0) def test_obl_ang1_cv(self): result = cephes.obl_ang1_cv(1,1,1,1,0) assert_almost_equal(result[0],1.0) assert_almost_equal(result[1],0.0) def _check_obl_cv(self): assert_equal(cephes.obl_cv(1,1,0),2.0) def test_obl_rad1(self): cephes.obl_rad1(1,1,1,0) def test_obl_rad1_cv(self): cephes.obl_rad1_cv(1,1,1,1,0) def test_obl_rad2(self): cephes.obl_rad2(1,1,1,0) def test_obl_rad2_cv(self): cephes.obl_rad2_cv(1,1,1,1,0) def test_pbdv(self): assert_equal(cephes.pbdv(1,0),(0.0,1.0)) def test_pbvv(self): cephes.pbvv(1,0) def test_pbwa(self): cephes.pbwa(1,0) def test_pdtr(self): val = cephes.pdtr(0, 1) assert_almost_equal(val, np.exp(-1)) # Edge case: m = 0. val = cephes.pdtr([0, 1, 2], 0) assert_array_equal(val, [1, 1, 1]) def test_pdtrc(self): val = cephes.pdtrc(0, 1) assert_almost_equal(val, 1 - np.exp(-1)) # Edge case: m = 0. val = cephes.pdtrc([0, 1, 2], 0.0) assert_array_equal(val, [0, 0, 0]) def test_pdtri(self): with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") cephes.pdtri(0.5,0.5) def test_pdtrik(self): k = cephes.pdtrik(0.5, 1) assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5) # Edge case: m = 0 or very small. k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6]) assert_array_equal(k, np.zeros((3, 3))) def test_pro_ang1(self): cephes.pro_ang1(1,1,1,0) def test_pro_ang1_cv(self): assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), array((1.0,0.0))) def _check_pro_cv(self): assert_equal(cephes.pro_cv(1,1,0),2.0) def test_pro_rad1(self): cephes.pro_rad1(1,1,1,0.1) def test_pro_rad1_cv(self): cephes.pro_rad1_cv(1,1,1,1,0) def test_pro_rad2(self): cephes.pro_rad2(1,1,1,0) def test_pro_rad2_cv(self): cephes.pro_rad2_cv(1,1,1,1,0) def test_psi(self): cephes.psi(1) def test_radian(self): assert_equal(cephes.radian(0,0,0),0) def test_rgamma(self): assert_equal(cephes.rgamma(1),1.0) def test_round(self): assert_equal(cephes.round(3.4),3.0) assert_equal(cephes.round(-3.4),-3.0) assert_equal(cephes.round(3.6),4.0) assert_equal(cephes.round(-3.6),-4.0) assert_equal(cephes.round(3.5),4.0) assert_equal(cephes.round(-3.5),-4.0) def test_shichi(self): cephes.shichi(1) def test_sici(self): cephes.sici(1) s, c = cephes.sici(np.inf) assert_almost_equal(s, np.pi * 0.5) assert_almost_equal(c, 0) s, c = cephes.sici(-np.inf) assert_almost_equal(s, -np.pi * 0.5) assert_(np.isnan(c), "cosine integral(-inf) is not nan") def test_sindg(self): assert_equal(cephes.sindg(90),1.0) def test_smirnov(self): assert_equal(cephes.smirnov(1,.1),0.9) assert_(np.isnan(cephes.smirnov(1,np.nan))) def test_smirnovp(self): assert_equal(cephes._smirnovp(1, .1), -1) assert_equal(cephes._smirnovp(2, 0.75), -2*(0.25)**(2-1)) assert_equal(cephes._smirnovp(3, 0.75), -3*(0.25)**(3-1)) assert_(np.isnan(cephes._smirnovp(1, np.nan))) def test_smirnovc(self): assert_equal(cephes._smirnovc(1,.1),0.1) assert_(np.isnan(cephes._smirnovc(1,np.nan))) x10 = np.linspace(0, 1, 11, endpoint=True) assert_almost_equal(cephes._smirnovc(3, x10), 1-cephes.smirnov(3, x10)) x4 = np.linspace(0, 1, 5, endpoint=True) assert_almost_equal(cephes._smirnovc(4, x4), 1-cephes.smirnov(4, x4)) def test_smirnovi(self): assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) assert_(np.isnan(cephes.smirnovi(1,np.nan))) def test_smirnovci(self): assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.4)),0.4) assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.6)),0.6) assert_(np.isnan(cephes._smirnovci(1,np.nan))) def test_spence(self): assert_equal(cephes.spence(1),0.0) def test_stdtr(self): assert_equal(cephes.stdtr(1,0),0.5) assert_almost_equal(cephes.stdtr(1,1), 0.75) assert_almost_equal(cephes.stdtr(1,2), 0.852416382349) def test_stdtridf(self): cephes.stdtridf(0.7,1) def test_stdtrit(self): cephes.stdtrit(1,0.7) def test_struve(self): assert_equal(cephes.struve(0,0),0.0) def test_tandg(self): assert_equal(cephes.tandg(45),1.0) def test_tklmbda(self): assert_almost_equal(cephes.tklmbda(1,1),1.0) def test_y0(self): cephes.y0(1) def test_y1(self): cephes.y1(1) def test_yn(self): cephes.yn(1,1) def test_yv(self): cephes.yv(1,1) def _check_yve(self): cephes.yve(1,1) def test_wofz(self): z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.), complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.), complex(-0.0000000234545,1.1234), complex(-3.,5.1), complex(-53,30.1), complex(0.0,0.12345), complex(11,1), complex(-22,-2), complex(9,-28), complex(21,-33), complex(1e5,1e5), complex(1e14,1e14) ] w = [ complex(-3.78270245518980507452677445620103199303131110e-7, 0.000903861276433172057331093754199933411710053155), complex(0.1764906227004816847297495349730234591778719532788, -0.02146550539468457616788719893991501311573031095617), complex(0.2410250715772692146133539023007113781272362309451, 0.06087579663428089745895459735240964093522265589350), complex(0.30474420525691259245713884106959496013413834051768, -0.20821893820283162728743734725471561394145872072738), complex(7.317131068972378096865595229600561710140617977e34, 8.321873499714402777186848353320412813066170427e34), complex(0.0615698507236323685519612934241429530190806818395, -0.00676005783716575013073036218018565206070072304635), complex(0.3960793007699874918961319170187598400134746631, -5.593152259116644920546186222529802777409274656e-9), complex(0.08217199226739447943295069917990417630675021771804, -0.04701291087643609891018366143118110965272615832184), complex(0.00457246000350281640952328010227885008541748668738, -0.00804900791411691821818731763401840373998654987934), complex(0.8746342859608052666092782112565360755791467973338452, 0.), complex(0.00468190164965444174367477874864366058339647648741, 0.0510735563901306197993676329845149741675029197050), complex(-0.0023193175200187620902125853834909543869428763219, -0.025460054739731556004902057663500272721780776336), complex(9.11463368405637174660562096516414499772662584e304, 3.97101807145263333769664875189354358563218932e305), complex(-4.4927207857715598976165541011143706155432296e281, -2.8019591213423077494444700357168707775769028e281), complex(2.820947917809305132678577516325951485807107151e-6, 2.820947917668257736791638444590253942253354058e-6), complex(2.82094791773878143474039725787438662716372268e-15, 2.82094791773878143474039725773333923127678361e-15) ] assert_func_equal(cephes.wofz, w, z, rtol=1e-13) class TestAiry(object): def test_airy(self): # This tests the airy function to ensure 8 place accuracy in computation x = special.airy(.99) assert_array_almost_equal(x,array([0.13689066,-0.16050153,1.19815925,0.92046818]),8) x = special.airy(.41) assert_array_almost_equal(x,array([0.25238916,-.23480512,0.80686202,0.51053919]),8) x = special.airy(-.36) assert_array_almost_equal(x,array([0.44508477,-0.23186773,0.44939534,0.48105354]),8) def test_airye(self): a = special.airye(0.01) b = special.airy(0.01) b1 = [None]*4 for n in range(2): b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01)) for n in range(2,4): b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) assert_array_almost_equal(a,b1,6) def test_bi_zeros(self): bi = special.bi_zeros(2) bia = (array([-1.17371322, -3.2710930]), array([-2.29443968, -4.07315509]), array([-0.45494438, 0.39652284]), array([0.60195789, -0.76031014])) assert_array_almost_equal(bi,bia,4) bi = special.bi_zeros(5) assert_array_almost_equal(bi[0],array([-1.173713222709127, -3.271093302836352, -4.830737841662016, -6.169852128310251, -7.376762079367764]),11) assert_array_almost_equal(bi[1],array([-2.294439682614122, -4.073155089071828, -5.512395729663599, -6.781294445990305, -7.940178689168587]),10) assert_array_almost_equal(bi[2],array([-0.454944383639657, 0.396522836094465, -0.367969161486959, 0.349499116831805, -0.336026240133662]),11) assert_array_almost_equal(bi[3],array([0.601957887976239, -0.760310141492801, 0.836991012619261, -0.88947990142654, 0.929983638568022]),10) def test_ai_zeros(self): ai = special.ai_zeros(1) assert_array_almost_equal(ai,(array([-2.33810741]), array([-1.01879297]), array([0.5357]), array([0.7012])),4) def test_ai_zeros_big(self): z, zp, ai_zpx, aip_zx = special.ai_zeros(50000) ai_z, aip_z, _, _ = special.airy(z) ai_zp, aip_zp, _, _ = special.airy(zp) ai_envelope = 1/abs(z)**(1./4) aip_envelope = abs(zp)**(1./4) # Check values assert_allclose(ai_zpx, ai_zp, rtol=1e-10) assert_allclose(aip_zx, aip_z, rtol=1e-10) # Check they are zeros assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0) assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.1 assert_allclose(z[:6], [-2.3381074105, -4.0879494441, -5.5205598281, -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10) assert_allclose(zp[:6], [-1.0187929716, -3.2481975822, -4.8200992112, -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10) def test_bi_zeros_big(self): z, zp, bi_zpx, bip_zx = special.bi_zeros(50000) _, _, bi_z, bip_z = special.airy(z) _, _, bi_zp, bip_zp = special.airy(zp) bi_envelope = 1/abs(z)**(1./4) bip_envelope = abs(zp)**(1./4) # Check values assert_allclose(bi_zpx, bi_zp, rtol=1e-10) assert_allclose(bip_zx, bip_z, rtol=1e-10) # Check they are zeros assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0) assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.2 assert_allclose(z[:6], [-1.1737132227, -3.2710933028, -4.8307378417, -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10) assert_allclose(zp[:6], [-2.2944396826, -4.0731550891, -5.5123957297, -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10) class TestAssocLaguerre(object): def test_assoc_laguerre(self): a1 = special.genlaguerre(11,1) a2 = special.assoc_laguerre(.2,11,1) assert_array_almost_equal(a2,a1(.2),8) a2 = special.assoc_laguerre(1,11,1) assert_array_almost_equal(a2,a1(1),8) class TestBesselpoly(object): def test_besselpoly(self): pass class TestKelvin(object): def test_bei(self): mbei = special.bei(2) assert_almost_equal(mbei, 0.9722916273066613,5) # this may not be exact def test_beip(self): mbeip = special.beip(2) assert_almost_equal(mbeip,0.91701361338403631,5) # this may not be exact def test_ber(self): mber = special.ber(2) assert_almost_equal(mber,0.75173418271380821,5) # this may not be exact def test_berp(self): mberp = special.berp(2) assert_almost_equal(mberp,-0.49306712470943909,5) # this may not be exact def test_bei_zeros(self): # Abramowitz & Stegun, Table 9.12 bi = special.bei_zeros(5) assert_array_almost_equal(bi,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) def test_beip_zeros(self): bip = special.beip_zeros(5) assert_array_almost_equal(bip,array([3.772673304934953, 8.280987849760042, 12.742147523633703, 17.193431752512542, 21.641143941167325]),8) def test_ber_zeros(self): ber = special.ber_zeros(5) assert_array_almost_equal(ber,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) def test_berp_zeros(self): brp = special.berp_zeros(5) assert_array_almost_equal(brp,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) def test_kelvin(self): mkelv = special.kelvin(2) assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j, special.ker(2) + special.kei(2)*1j, special.berp(2) + special.beip(2)*1j, special.kerp(2) + special.keip(2)*1j),8) def test_kei(self): mkei = special.kei(2) assert_almost_equal(mkei,-0.20240006776470432,5) def test_keip(self): mkeip = special.keip(2) assert_almost_equal(mkeip,0.21980790991960536,5) def test_ker(self): mker = special.ker(2) assert_almost_equal(mker,-0.041664513991509472,5) def test_kerp(self): mkerp = special.kerp(2) assert_almost_equal(mkerp,-0.10660096588105264,5) def test_kei_zeros(self): kei = special.kei_zeros(5) assert_array_almost_equal(kei,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) def test_keip_zeros(self): keip = special.keip_zeros(5) assert_array_almost_equal(keip,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) # numbers come from 9.9 of A&S pg. 381 def test_kelvin_zeros(self): tmp = special.kelvin_zeros(5) berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp assert_array_almost_equal(berz,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) assert_array_almost_equal(beiz,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) assert_array_almost_equal(kerz,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44382]),4) assert_array_almost_equal(keiz,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) assert_array_almost_equal(berpz,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) assert_array_almost_equal(beipz,array([3.77267, # table from 1927 had 3.77320 # but this is more accurate 8.28099, 12.74215, 17.19343, 21.64114]),4) assert_array_almost_equal(kerpz,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) assert_array_almost_equal(keipz,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) def test_ker_zeros(self): ker = special.ker_zeros(5) assert_array_almost_equal(ker,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44381]),4) def test_kerp_zeros(self): kerp = special.kerp_zeros(5) assert_array_almost_equal(kerp,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) class TestBernoulli(object): def test_bernoulli(self): brn = special.bernoulli(5) assert_array_almost_equal(brn,array([1.0000, -0.5000, 0.1667, 0.0000, -0.0333, 0.0000]),4) class TestBeta(object): def test_beta(self): bet = special.beta(2,4) betg = (special.gamma(2)*special.gamma(4))/special.gamma(6) assert_almost_equal(bet,betg,8) def test_betaln(self): betln = special.betaln(2,4) bet = log(abs(special.beta(2,4))) assert_almost_equal(betln,bet,8) def test_betainc(self): btinc = special.betainc(1,1,.2) assert_almost_equal(btinc,0.2,8) def test_betaincinv(self): y = special.betaincinv(2,4,.5) comp = special.betainc(2,4,y) assert_almost_equal(comp,.5,5) class TestCombinatorics(object): def test_comb(self): assert_array_almost_equal(special.comb([10, 10], [3, 4]), [120., 210.]) assert_almost_equal(special.comb(10, 3), 120.) assert_equal(special.comb(10, 3, exact=True), 120) assert_equal(special.comb(10, 3, exact=True, repetition=True), 220) assert_allclose([special.comb(20, k, exact=True) for k in range(21)], special.comb(20, list(range(21))), atol=1e-15) ii = np.iinfo(int).max + 1 assert_equal(special.comb(ii, ii-1, exact=True), ii) expected = 100891344545564193334812497256 assert_equal(special.comb(100, 50, exact=True), expected) def test_comb_with_np_int64(self): n = 70 k = 30 np_n = np.int64(n) np_k = np.int64(k) assert_equal(special.comb(np_n, np_k, exact=True), special.comb(n, k, exact=True)) def test_comb_zeros(self): assert_equal(special.comb(2, 3, exact=True), 0) assert_equal(special.comb(-1, 3, exact=True), 0) assert_equal(special.comb(2, -1, exact=True), 0) assert_equal(special.comb(2, -1, exact=False), 0) assert_array_almost_equal(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 120.]) def test_perm(self): assert_array_almost_equal(special.perm([10, 10], [3, 4]), [720., 5040.]) assert_almost_equal(special.perm(10, 3), 720.) assert_equal(special.perm(10, 3, exact=True), 720) def test_perm_zeros(self): assert_equal(special.perm(2, 3, exact=True), 0) assert_equal(special.perm(-1, 3, exact=True), 0) assert_equal(special.perm(2, -1, exact=True), 0) assert_equal(special.perm(2, -1, exact=False), 0) assert_array_almost_equal(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 720.]) class TestTrigonometric(object): def test_cbrt(self): cb = special.cbrt(27) cbrl = 27**(1.0/3.0) assert_approx_equal(cb,cbrl) def test_cbrtmore(self): cb1 = special.cbrt(27.9) cbrl1 = 27.9**(1.0/3.0) assert_almost_equal(cb1,cbrl1,8) def test_cosdg(self): cdg = special.cosdg(90) cdgrl = cos(pi/2.0) assert_almost_equal(cdg,cdgrl,8) def test_cosdgmore(self): cdgm = special.cosdg(30) cdgmrl = cos(pi/6.0) assert_almost_equal(cdgm,cdgmrl,8) def test_cosm1(self): cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10)) csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) assert_array_almost_equal(cs,csrl,8) def test_cotdg(self): ct = special.cotdg(30) ctrl = tan(pi/6.0)**(-1) assert_almost_equal(ct,ctrl,8) def test_cotdgmore(self): ct1 = special.cotdg(45) ctrl1 = tan(pi/4.0)**(-1) assert_almost_equal(ct1,ctrl1,8) def test_specialpoints(self): assert_almost_equal(special.cotdg(45), 1.0, 14) assert_almost_equal(special.cotdg(-45), -1.0, 14) assert_almost_equal(special.cotdg(90), 0.0, 14) assert_almost_equal(special.cotdg(-90), 0.0, 14) assert_almost_equal(special.cotdg(135), -1.0, 14) assert_almost_equal(special.cotdg(-135), 1.0, 14) assert_almost_equal(special.cotdg(225), 1.0, 14) assert_almost_equal(special.cotdg(-225), -1.0, 14) assert_almost_equal(special.cotdg(270), 0.0, 14) assert_almost_equal(special.cotdg(-270), 0.0, 14) assert_almost_equal(special.cotdg(315), -1.0, 14) assert_almost_equal(special.cotdg(-315), 1.0, 14) assert_almost_equal(special.cotdg(765), 1.0, 14) def test_sinc(self): # the sinc implementation and more extensive sinc tests are in numpy assert_array_equal(special.sinc([0]), 1) assert_equal(special.sinc(0.0), 1.0) def test_sindg(self): sn = special.sindg(90) assert_equal(sn,1.0) def test_sindgmore(self): snm = special.sindg(30) snmrl = sin(pi/6.0) assert_almost_equal(snm,snmrl,8) snm1 = special.sindg(45) snmrl1 = sin(pi/4.0) assert_almost_equal(snm1,snmrl1,8) class TestTandg(object): def test_tandg(self): tn = special.tandg(30) tnrl = tan(pi/6.0) assert_almost_equal(tn,tnrl,8) def test_tandgmore(self): tnm = special.tandg(45) tnmrl = tan(pi/4.0) assert_almost_equal(tnm,tnmrl,8) tnm1 = special.tandg(60) tnmrl1 = tan(pi/3.0) assert_almost_equal(tnm1,tnmrl1,8) def test_specialpoints(self): assert_almost_equal(special.tandg(0), 0.0, 14) assert_almost_equal(special.tandg(45), 1.0, 14) assert_almost_equal(special.tandg(-45), -1.0, 14) assert_almost_equal(special.tandg(135), -1.0, 14) assert_almost_equal(special.tandg(-135), 1.0, 14) assert_almost_equal(special.tandg(180), 0.0, 14) assert_almost_equal(special.tandg(-180), 0.0, 14) assert_almost_equal(special.tandg(225), 1.0, 14) assert_almost_equal(special.tandg(-225), -1.0, 14) assert_almost_equal(special.tandg(315), -1.0, 14) assert_almost_equal(special.tandg(-315), 1.0, 14) class TestEllip(object): def test_ellipj_nan(self): """Regression test for #912.""" special.ellipj(0.5, np.nan) def test_ellipj(self): el = special.ellipj(0.2,0) rel = [sin(0.2),cos(0.2),1.0,0.20] assert_array_almost_equal(el,rel,13) def test_ellipk(self): elk = special.ellipk(.2) assert_almost_equal(elk,1.659623598610528,11) assert_equal(special.ellipkm1(0.0), np.inf) assert_equal(special.ellipkm1(1.0), pi/2) assert_equal(special.ellipkm1(np.inf), 0.0) assert_equal(special.ellipkm1(np.nan), np.nan) assert_equal(special.ellipkm1(-1), np.nan) assert_allclose(special.ellipk(-10), 0.7908718902387385) def test_ellipkinc(self): elkinc = special.ellipkinc(pi/2,.2) elk = special.ellipk(0.2) assert_almost_equal(elkinc,elk,15) alpha = 20*pi/180 phi = 45*pi/180 m = sin(alpha)**2 elkinc = special.ellipkinc(phi,m) assert_almost_equal(elkinc,0.79398143,8) # From pg. 614 of A & S assert_equal(special.ellipkinc(pi/2, 0.0), pi/2) assert_equal(special.ellipkinc(pi/2, 1.0), np.inf) assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0) assert_equal(special.ellipkinc(pi/2, np.nan), np.nan) assert_equal(special.ellipkinc(pi/2, 2), np.nan) assert_equal(special.ellipkinc(0, 0.5), 0.0) assert_equal(special.ellipkinc(np.inf, 0.5), np.inf) assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipkinc(np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.nan, 0.5), np.nan) assert_equal(special.ellipkinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14) assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946) def test_ellipkinc_2(self): # Regression test for gh-3550 # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipkinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 1.0259330100195334), 1) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipkinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 5.1296650500976675), 2) def test_ellipkinc_singular(self): # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2) xlog = np.logspace(-300, -17, 25) xlin = np.linspace(1e-17, 0.1, 25) xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False) assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)), rtol=1e14) assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)), rtol=1e14) assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)), rtol=1e14) assert_equal(special.ellipkinc(np.pi/2, 1), np.inf) assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)), rtol=1e14) assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf) def test_ellipe(self): ele = special.ellipe(.2) assert_almost_equal(ele,1.4890350580958529,8) assert_equal(special.ellipe(0.0), pi/2) assert_equal(special.ellipe(1.0), 1.0) assert_equal(special.ellipe(-np.inf), np.inf) assert_equal(special.ellipe(np.nan), np.nan) assert_equal(special.ellipe(2), np.nan) assert_allclose(special.ellipe(-10), 3.6391380384177689) def test_ellipeinc(self): eleinc = special.ellipeinc(pi/2,.2) ele = special.ellipe(0.2) assert_almost_equal(eleinc,ele,14) # pg 617 of A & S alpha, phi = 52*pi/180,35*pi/180 m = sin(alpha)**2 eleinc = special.ellipeinc(phi,m) assert_almost_equal(eleinc, 0.58823065, 8) assert_equal(special.ellipeinc(pi/2, 0.0), pi/2) assert_equal(special.ellipeinc(pi/2, 1.0), 1.0) assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf) assert_equal(special.ellipeinc(pi/2, np.nan), np.nan) assert_equal(special.ellipeinc(pi/2, 2), np.nan) assert_equal(special.ellipeinc(0, 0.5), 0.0) assert_equal(special.ellipeinc(np.inf, 0.5), np.inf) assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf) assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf) assert_equal(special.ellipeinc(np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(np.nan, 0.5), np.nan) assert_equal(special.ellipeinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876) def test_ellipeinc_2(self): # Regression test for gh-3550 # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipeinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 0.84442884574781019), 2) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipeinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 3.3471442287390509), 4) class TestErf(object): def test_erf(self): er = special.erf(.25) assert_almost_equal(er,0.2763263902,8) def test_erf_zeros(self): erz = special.erf_zeros(5) erzr = array([1.45061616+1.88094300j, 2.24465928+2.61657514j, 2.83974105+3.17562810j, 3.33546074+3.64617438j, 3.76900557+4.06069723j]) assert_array_almost_equal(erz,erzr,4) def _check_variant_func(self, func, other_func, rtol, atol=0): np.random.seed(1234) n = 10000 x = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) y = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) z = x + 1j*y old_errors = np.seterr(all='ignore') try: w = other_func(z) w_real = other_func(x).real mask = np.isfinite(w) w = w[mask] z = z[mask] mask = np.isfinite(w_real) w_real = w_real[mask] x = x[mask] # test both real and complex variants assert_func_equal(func, w, z, rtol=rtol, atol=atol) assert_func_equal(func, w_real, x, rtol=rtol, atol=atol) finally: np.seterr(**old_errors) def test_erfc_consistent(self): self._check_variant_func( cephes.erfc, lambda z: 1 - cephes.erf(z), rtol=1e-12, atol=1e-14 # <- the test function loses precision ) def test_erfcx_consistent(self): self._check_variant_func( cephes.erfcx, lambda z: np.exp(z*z) * cephes.erfc(z), rtol=1e-12 ) def test_erfi_consistent(self): self._check_variant_func( cephes.erfi, lambda z: -1j * cephes.erf(1j*z), rtol=1e-12 ) def test_dawsn_consistent(self): self._check_variant_func( cephes.dawsn, lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z), rtol=1e-12 ) def test_erf_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -1, 1] assert_allclose(special.erf(vals), expected, rtol=1e-15) def test_erfc_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, 2, 0] assert_allclose(special.erfc(vals), expected, rtol=1e-15) def test_erfcx_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, np.inf, 0] assert_allclose(special.erfcx(vals), expected, rtol=1e-15) def test_erfi_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -np.inf, np.inf] assert_allclose(special.erfi(vals), expected, rtol=1e-15) def test_dawsn_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -0.0, 0.0] assert_allclose(special.dawsn(vals), expected, rtol=1e-15) def test_wofz_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan + np.nan * 1.j, 0.-0.j, 0.+0.j] assert_allclose(special.wofz(vals), expected, rtol=1e-15) class TestEuler(object): def test_euler(self): eu0 = special.euler(0) eu1 = special.euler(1) eu2 = special.euler(2) # just checking segfaults assert_allclose(eu0, [1], rtol=1e-15) assert_allclose(eu1, [1, 0], rtol=1e-15) assert_allclose(eu2, [1, 0, -1], rtol=1e-15) eu24 = special.euler(24) mathworld = [1,1,5,61,1385,50521,2702765,199360981, 19391512145,2404879675441, 370371188237525,69348874393137901, 15514534163557086905] correct = zeros((25,),'d') for k in range(0,13): if (k % 2): correct[2*k] = -float(mathworld[k]) else: correct[2*k] = float(mathworld[k]) olderr = np.seterr(all='ignore') try: err = nan_to_num((eu24-correct)/correct) errmax = max(err) finally: np.seterr(**olderr) assert_almost_equal(errmax, 0.0, 14) class TestExp(object): def test_exp2(self): ex = special.exp2(2) exrl = 2**2 assert_equal(ex,exrl) def test_exp2more(self): exm = special.exp2(2.5) exmrl = 2**(2.5) assert_almost_equal(exm,exmrl,8) def test_exp10(self): ex = special.exp10(2) exrl = 10**2 assert_approx_equal(ex,exrl) def test_exp10more(self): exm = special.exp10(2.5) exmrl = 10**(2.5) assert_almost_equal(exm,exmrl,8) def test_expm1(self): ex = (special.expm1(2),special.expm1(3),special.expm1(4)) exrl = (exp(2)-1,exp(3)-1,exp(4)-1) assert_array_almost_equal(ex,exrl,8) def test_expm1more(self): ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2)) exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) assert_array_almost_equal(ex1,exrl1,8) class TestFactorialFunctions(object): def test_factorial(self): # Some known values, float math assert_array_almost_equal(special.factorial(0), 1) assert_array_almost_equal(special.factorial(1), 1) assert_array_almost_equal(special.factorial(2), 2) assert_array_almost_equal([6., 24., 120.], special.factorial([3, 4, 5], exact=False)) assert_array_almost_equal(special.factorial([[5, 3], [4, 3]]), [[120, 6], [24, 6]]) # Some known values, integer math assert_equal(special.factorial(0, exact=True), 1) assert_equal(special.factorial(1, exact=True), 1) assert_equal(special.factorial(2, exact=True), 2) assert_equal(special.factorial(5, exact=True), 120) assert_equal(special.factorial(15, exact=True), 1307674368000) # ndarray shape is maintained assert_equal(special.factorial([7, 4, 15, 10], exact=True), [5040, 24, 1307674368000, 3628800]) assert_equal(special.factorial([[5, 3], [4, 3]], True), [[120, 6], [24, 6]]) # object arrays assert_equal(special.factorial(np.arange(-3, 22), True), special.factorial(np.arange(-3, 22), False)) # int64 array assert_equal(special.factorial(np.arange(-3, 15), True), special.factorial(np.arange(-3, 15), False)) # int32 array assert_equal(special.factorial(np.arange(-3, 5), True), special.factorial(np.arange(-3, 5), False)) # Consistent output for n < 0 for exact in (True, False): assert_array_equal(0, special.factorial(-3, exact)) assert_array_equal([1, 2, 0, 0], special.factorial([1, 2, -5, -4], exact)) for n in range(0, 22): # Compare all with math.factorial correct = math.factorial(n) assert_array_equal(correct, special.factorial(n, True)) assert_array_equal(correct, special.factorial([n], True)[0]) assert_allclose(float(correct), special.factorial(n, False)) assert_allclose(float(correct), special.factorial([n], False)[0]) # Compare exact=True vs False, scalar vs array assert_array_equal(special.factorial(n, True), special.factorial(n, False)) assert_array_equal(special.factorial([n], True), special.factorial([n], False)) @pytest.mark.parametrize('x, exact', [ (1, True), (1, False), (np.array(1), True), (np.array(1), False), ]) def test_factorial_0d_return_type(self, x, exact): assert np.isscalar(special.factorial(x, exact=exact)) def test_factorial2(self): assert_array_almost_equal([105., 384., 945.], special.factorial2([7, 8, 9], exact=False)) assert_equal(special.factorial2(7, exact=True), 105) def test_factorialk(self): assert_equal(special.factorialk(5, 1, exact=True), 120) assert_equal(special.factorialk(5, 3, exact=True), 10) @pytest.mark.parametrize('x, exact', [ (np.nan, True), (np.nan, False), (np.array([np.nan]), True), (np.array([np.nan]), False), ]) def test_nan_inputs(self, x, exact): result = special.factorial(x, exact=exact) assert_(np.isnan(result)) def test_mixed_nan_inputs(self): x = np.array([np.nan, 1, 2, 3, np.nan]) result = special.factorial(x, exact=True) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) result = special.factorial(x, exact=False) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) class TestFresnel(object): def test_fresnel(self): frs = array(special.fresnel(.5)) assert_array_almost_equal(frs,array([0.064732432859999287, 0.49234422587144644]),8) def test_fresnel_inf1(self): frs = special.fresnel(np.inf) assert_equal(frs, (0.5, 0.5)) def test_fresnel_inf2(self): frs = special.fresnel(-np.inf) assert_equal(frs, (-0.5, -0.5)) # values from pg 329 Table 7.11 of A & S # slightly corrected in 4th decimal place def test_fresnel_zeros(self): szo, czo = special.fresnel_zeros(5) assert_array_almost_equal(szo, array([2.0093+0.2885j, 2.8335+0.2443j, 3.4675+0.2185j, 4.0026+0.2009j, 4.4742+0.1877j]),3) assert_array_almost_equal(czo, array([1.7437+0.3057j, 2.6515+0.2529j, 3.3204+0.2240j, 3.8757+0.2047j, 4.3611+0.1907j]),3) vals1 = special.fresnel(szo)[0] vals2 = special.fresnel(czo)[1] assert_array_almost_equal(vals1,0,14) assert_array_almost_equal(vals2,0,14) def test_fresnelc_zeros(self): szo, czo = special.fresnel_zeros(6) frc = special.fresnelc_zeros(6) assert_array_almost_equal(frc,czo,12) def test_fresnels_zeros(self): szo, czo = special.fresnel_zeros(5) frs = special.fresnels_zeros(5) assert_array_almost_equal(frs,szo,12) class TestGamma(object): def test_gamma(self): gam = special.gamma(5) assert_equal(gam,24.0) def test_gammaln(self): gamln = special.gammaln(3) lngam = log(special.gamma(3)) assert_almost_equal(gamln,lngam,8) def test_gammainccinv(self): gccinv = special.gammainccinv(.5,.5) gcinv = special.gammaincinv(.5,.5) assert_almost_equal(gccinv,gcinv,8) @with_special_errors def test_gammaincinv(self): y = special.gammaincinv(.4,.4) x = special.gammainc(.4,y) assert_almost_equal(x,0.4,1) y = special.gammainc(10, 0.05) x = special.gammaincinv(10, 2.5715803516000736e-20) assert_almost_equal(0.05, x, decimal=10) assert_almost_equal(y, 2.5715803516000736e-20, decimal=10) x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18) assert_almost_equal(11.0, x, decimal=10) @with_special_errors def test_975(self): # Regression test for ticket #975 -- switch point in algorithm # check that things work OK at the point, immediately next floats # around it, and a bit further away pts = [0.25, np.nextafter(0.25, 0), 0.25 - 1e-12, np.nextafter(0.25, 1), 0.25 + 1e-12] for xp in pts: y = special.gammaincinv(.4, xp) x = special.gammainc(0.4, y) assert_allclose(x, xp, rtol=1e-12) def test_rgamma(self): rgam = special.rgamma(8) rlgam = 1/special.gamma(8) assert_almost_equal(rgam,rlgam,8) def test_infinity(self): assert_(np.isinf(special.gamma(-1))) assert_equal(special.rgamma(-1), 0) class TestHankel(object): def test_negv1(self): assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14) def test_hankel1(self): hank1 = special.hankel1(1,.1) hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j) assert_almost_equal(hank1,hankrl,8) def test_negv1e(self): assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14) def test_hankel1e(self): hank1e = special.hankel1e(1,.1) hankrle = special.hankel1(1,.1)*exp(-.1j) assert_almost_equal(hank1e,hankrle,8) def test_negv2(self): assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14) def test_hankel2(self): hank2 = special.hankel2(1,.1) hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j) assert_almost_equal(hank2,hankrl2,8) def test_neg2e(self): assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14) def test_hankl2e(self): hank2e = special.hankel2e(1,.1) hankrl2e = special.hankel2e(1,.1) assert_almost_equal(hank2e,hankrl2e,8) class TestHyper(object): def test_h1vp(self): h1 = special.h1vp(1,.1) h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j) assert_almost_equal(h1,h1real,8) def test_h2vp(self): h2 = special.h2vp(1,.1) h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j) assert_almost_equal(h2,h2real,8) def test_hyp0f1(self): # scalar input assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12) assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15) # float input, expected values match mpmath x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5]) expected = np.array([0.58493659229143, 0.70566805723127, 1.0, 1.37789689539747, 1.60373685288480]) assert_allclose(x, expected, rtol=1e-12) # complex input x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j) assert_allclose(x, expected.astype(complex), rtol=1e-12) # test broadcasting x1 = [0.5, 1.5, 2.5] x2 = [0, 1, 0.5] x = special.hyp0f1(x1, x2) expected = [1.0, 1.8134302039235093, 1.21482702689997] assert_allclose(x, expected, rtol=1e-12) x = special.hyp0f1(np.row_stack([x1] * 2), x2) assert_allclose(x, np.row_stack([expected] * 2), rtol=1e-12) assert_raises(ValueError, special.hyp0f1, np.row_stack([x1] * 3), [0, 1]) def test_hyp0f1_gh5764(self): # Just checks the point that failed; there's a more systematic # test in test_mpmath res = special.hyp0f1(0.8, 0.5 + 0.5*1J) # The expected value was generated using mpmath assert_almost_equal(res, 1.6139719776441115 + 1J*0.80893054061790665) def test_hyp1f1(self): hyp1 = special.hyp1f1(.1,.1,.3) assert_almost_equal(hyp1, 1.3498588075760032,7) # test contributed by Moritz Deger (2008-05-29) # https://github.com/scipy/scipy/issues/1186 (Trac #659) # reference data obtained from mathematica [ a, b, x, m(a,b,x)]: # produced with test_hyp1f1.nb ref_data = array([[-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04], [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00], [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05], [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08], [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24], [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21], [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13], [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13], [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02], [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10], [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01], [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21], [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20], [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07], [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03], [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02], [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11], [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03], [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17], [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01], [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00], [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00], [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23], [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01], [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04], [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08], [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01], [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07], [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03], [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09], [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06], [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00], [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01], [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02], [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02], [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02], [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00], [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09], [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01], [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00], [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02], [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05], [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05], [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02], [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02], [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13], [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05], [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12], [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01], [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16], [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37], [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06], [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02], [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12], [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27], [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04], [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06], [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07], [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03], [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07], [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27], [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12], [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32], [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04], [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01], [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02], [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19], [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09], [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31], [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01], [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02], [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08], [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09], [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33], [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01], [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29], [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01], [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29], [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02], [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00], [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08], [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01], [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01], [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01], [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13], [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11], [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02], [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02], [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01], [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31], [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04], [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25], [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01], [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00], [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02], [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05], [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02], [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01], [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01], [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00]]) for a,b,c,expected in ref_data: result = special.hyp1f1(a,b,c) assert_(abs(expected - result)/expected < 1e-4) def test_hyp1f1_gh2957(self): hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933) hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934) assert_almost_equal(hyp1, hyp2, 12) def test_hyp1f1_gh2282(self): hyp = special.hyp1f1(0.5, 1.5, -1000) assert_almost_equal(hyp, 0.028024956081989643, 12) def test_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], [3, 4, 8, 1, special.gamma(8)*special.gamma(8-4-3)/special.gamma(8-3)/special.gamma(8-4)], [3, 2, 3-2+1, -1, 1./2**3*sqrt(pi) * special.gamma(1+3-2)/special.gamma(1+0.5*3-2)/special.gamma(0.5+0.5*3)], [5, 2, 5-2+1, -1, 1./2**5*sqrt(pi) * special.gamma(1+5-2)/special.gamma(1+0.5*5-2)/special.gamma(0.5+0.5*5)], [4, 0.5+4, 1.5-2*4, -1./3, (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4)/special.gamma(3./2)/special.gamma(4./3-2*4)], # and some others # ticket #424 [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484], # negative integer a or b, with c-a-b integer and x > 0.9 [-2,3,1,0.95,0.715], [2,-3,1,0.95,-0.007], [-6,3,1,0.95,0.0000810625], [2,-5,1,0.95,-0.000029375], # huge negative integers (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24), (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18), ] for i, (a, b, c, x, v) in enumerate(values): cv = special.hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_hyperu(self): val1 = special.hyperu(1,0.1,100) assert_almost_equal(val1,0.0098153,7) a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] a,b = asarray(a), asarray(b) z = 0.5 hypu = special.hyperu(a,b,z) hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) / (special.gamma(1+a-b)*special.gamma(b)) - z**(1-b)*special.hyp1f1(1+a-b,2-b,z) / (special.gamma(a)*special.gamma(2-b))) assert_array_almost_equal(hypu,hprl,12) def test_hyperu_gh2287(self): assert_almost_equal(special.hyperu(1, 1.5, 20.2), 0.048360918656699191, 12) class TestBessel(object): def test_itj0y0(self): it0 = array(special.itj0y0(.2)) assert_array_almost_equal(it0,array([0.19933433254006822, -0.34570883800412566]),8) def test_it2j0y0(self): it2 = array(special.it2j0y0(.2)) assert_array_almost_equal(it2,array([0.0049937546274601858, -0.43423067011231614]),8) def test_negv_iv(self): assert_equal(special.iv(3,2), special.iv(-3,2)) def test_j0(self): oz = special.j0(.1) ozr = special.jn(0,.1) assert_almost_equal(oz,ozr,8) def test_j1(self): o1 = special.j1(.1) o1r = special.jn(1,.1) assert_almost_equal(o1,o1r,8) def test_jn(self): jnnr = special.jn(1,.2) assert_almost_equal(jnnr,0.099500832639235995,8) def test_negv_jv(self): assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14) def test_jv(self): values = [[0, 0.1, 0.99750156206604002], [2./3, 1e-8, 0.3239028506761532e-5], [2./3, 1e-10, 0.1503423854873779e-6], [3.1, 1e-10, 0.1711956265409013e-32], [2./3, 4.0, -0.2325440850267039], ] for i, (v, x, y) in enumerate(values): yc = special.jv(v, x) assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) def test_negv_jve(self): assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14) def test_jve(self): jvexp = special.jve(1,.2) assert_almost_equal(jvexp,0.099500832639235995,8) jvexp1 = special.jve(1,.2+1j) z = .2+1j jvexpr = special.jv(1,z)*exp(-abs(z.imag)) assert_almost_equal(jvexp1,jvexpr,8) def test_jn_zeros(self): jn0 = special.jn_zeros(0,5) jn1 = special.jn_zeros(1,5) assert_array_almost_equal(jn0,array([2.4048255577, 5.5200781103, 8.6537279129, 11.7915344391, 14.9309177086]),4) assert_array_almost_equal(jn1,array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]),4) jn102 = special.jn_zeros(102,5) assert_allclose(jn102, array([110.89174935992040343, 117.83464175788308398, 123.70194191713507279, 129.02417238949092824, 134.00114761868422559]), rtol=1e-13) jn301 = special.jn_zeros(301,5) assert_allclose(jn301, array([313.59097866698830153, 323.21549776096288280, 331.22338738656748796, 338.39676338872084500, 345.03284233056064157]), rtol=1e-13) def test_jn_zeros_slow(self): jn0 = special.jn_zeros(0, 300) assert_allclose(jn0[260-1], 816.02884495068867280, rtol=1e-13) assert_allclose(jn0[280-1], 878.86068707124422606, rtol=1e-13) assert_allclose(jn0[300-1], 941.69253065317954064, rtol=1e-13) jn10 = special.jn_zeros(10, 300) assert_allclose(jn10[260-1], 831.67668514305631151, rtol=1e-13) assert_allclose(jn10[280-1], 894.51275095371316931, rtol=1e-13) assert_allclose(jn10[300-1], 957.34826370866539775, rtol=1e-13) jn3010 = special.jn_zeros(3010,5) assert_allclose(jn3010, array([3036.86590780927, 3057.06598526482, 3073.66360690272, 3088.37736494778, 3101.86438139042]), rtol=1e-8) def test_jnjnp_zeros(self): jn = special.jn def jnp(n, x): return (jn(n-1,x) - jn(n+1,x))/2 for nt in range(1, 30): z, n, m, t = special.jnjnp_zeros(nt) for zz, nn, tt in zip(z, n, t): if tt == 0: assert_allclose(jn(nn, zz), 0, atol=1e-6) elif tt == 1: assert_allclose(jnp(nn, zz), 0, atol=1e-6) else: raise AssertionError("Invalid t return for nt=%d" % nt) def test_jnp_zeros(self): jnp = special.jnp_zeros(1,5) assert_array_almost_equal(jnp, array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]),4) jnp = special.jnp_zeros(443,5) assert_allclose(special.jvp(443, jnp), 0, atol=1e-15) def test_jnyn_zeros(self): jnz = special.jnyn_zeros(1,5) assert_array_almost_equal(jnz,(array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]), array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]), array([2.19714, 5.42968, 8.59601, 11.74915, 14.89744]), array([3.68302, 6.94150, 10.12340, 13.28576, 16.44006])),5) def test_jvp(self): jvprim = special.jvp(2,2) jv0 = (special.jv(1,2)-special.jv(3,2))/2 assert_almost_equal(jvprim,jv0,10) def test_k0(self): ozk = special.k0(.1) ozkr = special.kv(0,.1) assert_almost_equal(ozk,ozkr,8) def test_k0e(self): ozke = special.k0e(.1) ozker = special.kve(0,.1) assert_almost_equal(ozke,ozker,8) def test_k1(self): o1k = special.k1(.1) o1kr = special.kv(1,.1) assert_almost_equal(o1k,o1kr,8) def test_k1e(self): o1ke = special.k1e(.1) o1ker = special.kve(1,.1) assert_almost_equal(o1ke,o1ker,8) def test_jacobi(self): a = 5*np.random.random() - 1 b = 5*np.random.random() - 1 P0 = special.jacobi(0,a,b) P1 = special.jacobi(1,a,b) P2 = special.jacobi(2,a,b) P3 = special.jacobi(3,a,b) assert_array_almost_equal(P0.c,[1],13) assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13) cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)] p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]] assert_array_almost_equal(P2.c,array(p2c)/8.0,13) cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3), 12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)] p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] assert_array_almost_equal(P3.c,array(p3c)/48.0,13) def test_kn(self): kn1 = special.kn(0,.2) assert_almost_equal(kn1,1.7527038555281462,8) def test_negv_kv(self): assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2)) def test_kv0(self): kv0 = special.kv(0,.2) assert_almost_equal(kv0, 1.7527038555281462, 10) def test_kv1(self): kv1 = special.kv(1,0.2) assert_almost_equal(kv1, 4.775972543220472, 10) def test_kv2(self): kv2 = special.kv(2,0.2) assert_almost_equal(kv2, 49.51242928773287, 10) def test_kn_largeorder(self): assert_allclose(special.kn(32, 1), 1.7516596664574289e+43) def test_kv_largearg(self): assert_equal(special.kv(0, 1e19), 0) def test_negv_kve(self): assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2)) def test_kve(self): kve1 = special.kve(0,.2) kv1 = special.kv(0,.2)*exp(.2) assert_almost_equal(kve1,kv1,8) z = .2+1j kve2 = special.kve(0,z) kv2 = special.kv(0,z)*exp(z) assert_almost_equal(kve2,kv2,8) def test_kvp_v0n1(self): z = 2.2 assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10) def test_kvp_n1(self): v = 3. z = 2.2 xc = -special.kv(v+1,z) + v/z*special.kv(v,z) x = special.kvp(v,z, n=1) assert_almost_equal(xc, x, 10) # this function (kvp) is broken def test_kvp_n2(self): v = 3. z = 2.2 xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z x = special.kvp(v, z, n=2) assert_almost_equal(xc, x, 10) def test_y0(self): oz = special.y0(.1) ozr = special.yn(0,.1) assert_almost_equal(oz,ozr,8) def test_y1(self): o1 = special.y1(.1) o1r = special.yn(1,.1) assert_almost_equal(o1,o1r,8) def test_y0_zeros(self): yo,ypo = special.y0_zeros(2) zo,zpo = special.y0_zeros(2,complex=1) all = r_[yo,zo] allval = r_[ypo,zpo] assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11) assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11) def test_y1_zeros(self): y1 = special.y1_zeros(1) assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) def test_y1p_zeros(self): y1p = special.y1p_zeros(1,complex=1) assert_array_almost_equal(y1p,(array([0.5768+0.904j]), array([-0.7635+0.5892j])),3) def test_yn_zeros(self): an = special.yn_zeros(4,2) assert_array_almost_equal(an,array([5.64515, 9.36162]),5) an = special.yn_zeros(443,5) assert_allclose(an, [450.13573091578090314, 463.05692376675001542, 472.80651546418663566, 481.27353184725625838, 488.98055964441374646], rtol=1e-15) def test_ynp_zeros(self): ao = special.ynp_zeros(0,2) assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6) ao = special.ynp_zeros(43,5) assert_allclose(special.yvp(43, ao), 0, atol=1e-15) ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-9) def test_ynp_zeros_large_order(self): ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-14) def test_yn(self): yn2n = special.yn(1,.2) assert_almost_equal(yn2n,-3.3238249881118471,8) def test_negv_yv(self): assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14) def test_yv(self): yv2 = special.yv(1,.2) assert_almost_equal(yv2,-3.3238249881118471,8) def test_negv_yve(self): assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14) def test_yve(self): yve2 = special.yve(1,.2) assert_almost_equal(yve2,-3.3238249881118471,8) yve2r = special.yv(1,.2+1j)*exp(-1) yve22 = special.yve(1,.2+1j) assert_almost_equal(yve22,yve2r,8) def test_yvp(self): yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0 yvp1 = special.yvp(2,.2) assert_array_almost_equal(yvp1,yvpr,10) def _cephes_vs_amos_points(self): """Yield points at which to compare Cephes implementation to AMOS""" # check several points, including large-amplitude ones for v in [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301]: for z in [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300, 10003]: yield v, z # check half-integers; these are problematic points at least # for cephes/iv for v in 0.5 + arange(-60, 60): yield v, 3.5 def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None): for v, z in self._cephes_vs_amos_points(): if skip is not None and skip(v, z): continue c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z) if np.isinf(c1): assert_(np.abs(c2) >= 1e300, (v, z)) elif np.isnan(c1): assert_(c2.imag != 0, (v, z)) else: assert_allclose(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol) if v == int(v): assert_allclose(c3, c2, err_msg=(v, z), rtol=rtol, atol=atol) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_jv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_yv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305) def test_yv_cephes_vs_amos_only_small_orders(self): skipper = lambda v, z: (abs(v) > 50) self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305, skip=skipper) def test_iv_cephes_vs_amos(self): olderr = np.seterr(all='ignore') try: self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305) finally: np.seterr(**olderr) @pytest.mark.slow def test_iv_cephes_vs_amos_mass_test(self): N = 1000000 np.random.seed(1) v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N) x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N) imsk = (np.random.randint(8, size=N) == 0) v[imsk] = v[imsk].astype(int) old_err = np.seterr(all='ignore') try: c1 = special.iv(v, x) c2 = special.iv(v, x+0j) # deal with differences in the inf and zero cutoffs c1[abs(c1) > 1e300] = np.inf c2[abs(c2) > 1e300] = np.inf c1[abs(c1) < 1e-300] = 0 c2[abs(c2) < 1e-300] = 0 dc = abs(c1/c2 - 1) dc[np.isnan(dc)] = 0 finally: np.seterr(**old_err) k = np.argmax(dc) # Most error apparently comes from AMOS and not our implementation; # there are some problems near integer orders there assert_(dc[k] < 2e-7, (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j))) def test_kv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305) self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305) def test_ticket_623(self): assert_allclose(special.jv(3, 4), 0.43017147387562193) assert_allclose(special.jv(301, 1300), 0.0183487151115275) assert_allclose(special.jv(301, 1296.0682), -0.0224174325312048) def test_ticket_853(self): """Negative-order Bessels""" # cephes assert_allclose(special.jv(-1, 1), -0.4400505857449335) assert_allclose(special.jv(-2, 1), 0.1149034849319005) assert_allclose(special.yv(-1, 1), 0.7812128213002887) assert_allclose(special.yv(-2, 1), -1.650682606816255) assert_allclose(special.iv(-1, 1), 0.5651591039924851) assert_allclose(special.iv(-2, 1), 0.1357476697670383) assert_allclose(special.kv(-1, 1), 0.6019072301972347) assert_allclose(special.kv(-2, 1), 1.624838898635178) assert_allclose(special.jv(-0.5, 1), 0.43109886801837607952) assert_allclose(special.yv(-0.5, 1), 0.6713967071418031) assert_allclose(special.iv(-0.5, 1), 1.231200214592967) assert_allclose(special.kv(-0.5, 1), 0.4610685044478945) # amos assert_allclose(special.jv(-1, 1+0j), -0.4400505857449335) assert_allclose(special.jv(-2, 1+0j), 0.1149034849319005) assert_allclose(special.yv(-1, 1+0j), 0.7812128213002887) assert_allclose(special.yv(-2, 1+0j), -1.650682606816255) assert_allclose(special.iv(-1, 1+0j), 0.5651591039924851) assert_allclose(special.iv(-2, 1+0j), 0.1357476697670383) assert_allclose(special.kv(-1, 1+0j), 0.6019072301972347) assert_allclose(special.kv(-2, 1+0j), 1.624838898635178) assert_allclose(special.jv(-0.5, 1+0j), 0.43109886801837607952) assert_allclose(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j) assert_allclose(special.yv(-0.5, 1+0j), 0.6713967071418031) assert_allclose(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j) assert_allclose(special.iv(-0.5, 1+0j), 1.231200214592967) assert_allclose(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j) assert_allclose(special.kv(-0.5, 1+0j), 0.4610685044478945) assert_allclose(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j) assert_allclose(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3)) assert_allclose(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j)) assert_allclose(special.hankel1(-0.5, 1+1j), special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j)) assert_allclose(special.hankel2(-0.5, 1+1j), special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j)) def test_ticket_854(self): """Real-valued Bessel domains""" assert_(isnan(special.jv(0.5, -1))) assert_(isnan(special.iv(0.5, -1))) assert_(isnan(special.yv(0.5, -1))) assert_(isnan(special.yv(1, -1))) assert_(isnan(special.kv(0.5, -1))) assert_(isnan(special.kv(1, -1))) assert_(isnan(special.jve(0.5, -1))) assert_(isnan(special.ive(0.5, -1))) assert_(isnan(special.yve(0.5, -1))) assert_(isnan(special.yve(1, -1))) assert_(isnan(special.kve(0.5, -1))) assert_(isnan(special.kve(1, -1))) assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1)) assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1)) def test_gh_7909(self): assert_(special.kv(1.5, 0) == np.inf) assert_(special.kve(1.5, 0) == np.inf) def test_ticket_503(self): """Real-valued Bessel I overflow""" assert_allclose(special.iv(1, 700), 1.528500390233901e302) assert_allclose(special.iv(1000, 1120), 1.301564549405821e301) def test_iv_hyperg_poles(self): assert_allclose(special.iv(-0.5, 1), 1.231200214592967) def iv_series(self, v, z, n=200): k = arange(0, n).astype(float_) r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1) r[isnan(r)] = inf r = exp(r) err = abs(r).max() * finfo(float_).eps * n + abs(r[-1])*10 return r.sum(), err def test_i0_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(0, z) assert_allclose(special.i0(z), value, atol=err, err_msg=z) def test_i1_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(1, z) assert_allclose(special.i1(z), value, atol=err, err_msg=z) def test_iv_series(self): for v in [-20., -10., -1., 0., 1., 12.49, 120.]: for z in [1., 10., 200.5, -1+2j]: value, err = self.iv_series(v, z) assert_allclose(special.iv(v, z), value, atol=err, err_msg=(v, z)) def test_i0(self): values = [[0.0, 1.0], [1e-10, 1.0], [0.1, 0.9071009258], [0.5, 0.6450352706], [1.0, 0.4657596077], [2.5, 0.2700464416], [5.0, 0.1835408126], [20.0, 0.0897803119], ] for i, (x, v) in enumerate(values): cv = special.i0(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i0e(self): oize = special.i0e(.1) oizer = special.ive(0,.1) assert_almost_equal(oize,oizer,8) def test_i1(self): values = [[0.0, 0.0], [1e-10, 0.4999999999500000e-10], [0.1, 0.0452984468], [0.5, 0.1564208032], [1.0, 0.2079104154], [5.0, 0.1639722669], [20.0, 0.0875062222], ] for i, (x, v) in enumerate(values): cv = special.i1(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i1e(self): oi1e = special.i1e(.1) oi1er = special.ive(1,.1) assert_almost_equal(oi1e,oi1er,8) def test_iti0k0(self): iti0 = array(special.iti0k0(5)) assert_array_almost_equal(iti0,array([31.848667776169801, 1.5673873907283657]),5) def test_it2i0k0(self): it2k = special.it2i0k0(.1) assert_array_almost_equal(it2k,array([0.0012503906973464409, 3.3309450354686687]),6) def test_iv(self): iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(iv1,0.90710092578230106,10) def test_negv_ive(self): assert_equal(special.ive(3,2), special.ive(-3,2)) def test_ive(self): ive1 = special.ive(0,.1) iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(ive1,iv1,10) def test_ivp0(self): assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10) def test_ivp(self): y = (special.iv(0,2) + special.iv(2,2))/2 x = special.ivp(1,2) assert_almost_equal(x,y,10) class TestLaguerre(object): def test_laguerre(self): lag0 = special.laguerre(0) lag1 = special.laguerre(1) lag2 = special.laguerre(2) lag3 = special.laguerre(3) lag4 = special.laguerre(4) lag5 = special.laguerre(5) assert_array_almost_equal(lag0.c,[1],13) assert_array_almost_equal(lag1.c,[-1,1],13) assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13) assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13) assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) def test_genlaguerre(self): k = 5*np.random.random() - 0.9 lag0 = special.genlaguerre(0,k) lag1 = special.genlaguerre(1,k) lag2 = special.genlaguerre(2,k) lag3 = special.genlaguerre(3,k) assert_equal(lag0.c,[1]) assert_equal(lag1.c,[-1,k+1]) assert_almost_equal(lag2.c,array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0) assert_almost_equal(lag3.c,array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0) # Base polynomials come from Abrahmowitz and Stegan class TestLegendre(object): def test_legendre(self): leg0 = special.legendre(0) leg1 = special.legendre(1) leg2 = special.legendre(2) leg3 = special.legendre(3) leg4 = special.legendre(4) leg5 = special.legendre(5) assert_equal(leg0.c, [1]) assert_equal(leg1.c, [1,0]) assert_almost_equal(leg2.c, array([3,0,-1])/2.0, decimal=13) assert_almost_equal(leg3.c, array([5,0,-3,0])/2.0) assert_almost_equal(leg4.c, array([35,0,-30,0,3])/8.0) assert_almost_equal(leg5.c, array([63,0,-70,0,15,0])/8.0) class TestLambda(object): def test_lmbda(self): lam = special.lmbda(1,.1) lamr = (array([special.jn(0,.1), 2*special.jn(1,.1)/.1]), array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])) assert_array_almost_equal(lam,lamr,8) class TestLog1p(object): def test_log1p(self): l1p = (special.log1p(10), special.log1p(11), special.log1p(12)) l1prl = (log(11), log(12), log(13)) assert_array_almost_equal(l1p,l1prl,8) def test_log1pmore(self): l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2)) l1pmrl = (log(2),log(2.1),log(2.2)) assert_array_almost_equal(l1pm,l1pmrl,8) class TestLegendreFunctions(object): def test_clpmn(self): z = 0.5+0.3j clp = special.clpmn(2, 2, z, 3) assert_array_almost_equal(clp, (array([[1.0000, z, 0.5*(3*z*z-1)], [0.0000, sqrt(z*z-1), 3*z*sqrt(z*z-1)], [0.0000, 0.0000, 3*(z*z-1)]]), array([[0.0000, 1.0000, 3*z], [0.0000, z/sqrt(z*z-1), 3*(2*z*z-1)/sqrt(z*z-1)], [0.0000, 0.0000, 6*z]])), 7) def test_clpmn_close_to_real_2(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x), special.lpmv(m, n, x)]), 7) def test_clpmn_close_to_real_3(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi), special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]), 7) def test_clpmn_across_unit_circle(self): eps = 1e-7 m = 1 n = 1 x = 1j for type in [2, 3]: assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n], special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6) def test_inf(self): for z in (1, -1): for n in range(4): for m in range(1, n): lp = special.clpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) lp = special.lpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) def test_deriv_clpmn(self): # data inside and outside of the unit circle zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j, 1+1j, -1+1j, -1-1j, 1-1j] m = 2 n = 3 for type in [2, 3]: for z in zvals: for h in [1e-3, 1e-3j]: approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0] - special.clpmn(m, n, z-0.5*h, type)[0])/h assert_allclose(special.clpmn(m, n, z, type)[1], approx_derivative, rtol=1e-4) def test_lpmn(self): lp = special.lpmn(0,2,.5) assert_array_almost_equal(lp,(array([[1.00000, 0.50000, -0.12500]]), array([[0.00000, 1.00000, 1.50000]])),4) def test_lpn(self): lpnf = special.lpn(2,.5) assert_array_almost_equal(lpnf,(array([1.00000, 0.50000, -0.12500]), array([0.00000, 1.00000, 1.50000])),4) def test_lpmv(self): lp = special.lpmv(0,2,.5) assert_almost_equal(lp,-0.125,7) lp = special.lpmv(0,40,.001) assert_almost_equal(lp,0.1252678976534484,7) # XXX: this is outside the domain of the current implementation, # so ensure it returns a NaN rather than a wrong answer. olderr = np.seterr(all='ignore') try: lp = special.lpmv(-1,-1,.001) finally: np.seterr(**olderr) assert_(lp != 0 or np.isnan(lp)) def test_lqmn(self): lqmnf = special.lqmn(0,2,.5) lqf = special.lqn(2,.5) assert_array_almost_equal(lqmnf[0][0],lqf[0],4) assert_array_almost_equal(lqmnf[1][0],lqf[1],4) def test_lqmn_gt1(self): """algorithm for real arguments changes at 1.0001 test against analytical result for m=2, n=1 """ x0 = 1.0001 delta = 0.00002 for x in (x0-delta, x0+delta): lq = special.lqmn(2, 1, x)[0][-1, -1] expected = 2/(x*x-1) assert_almost_equal(lq, expected) def test_lqmn_shape(self): a, b = special.lqmn(4, 4, 1.1) assert_equal(a.shape, (5, 5)) assert_equal(b.shape, (5, 5)) a, b = special.lqmn(4, 0, 1.1) assert_equal(a.shape, (5, 1)) assert_equal(b.shape, (5, 1)) def test_lqn(self): lqf = special.lqn(2,.5) assert_array_almost_equal(lqf,(array([0.5493, -0.7253, -0.8187]), array([1.3333, 1.216, -0.8427])),4) class TestMathieu(object): def test_mathieu_a(self): pass def test_mathieu_even_coef(self): special.mathieu_even_coef(2,5) # Q not defined broken and cannot figure out proper reporting order def test_mathieu_odd_coef(self): # same problem as above pass class TestFresnelIntegral(object): def test_modfresnelp(self): pass def test_modfresnelm(self): pass class TestOblCvSeq(object): def test_obl_cv_seq(self): obl = special.obl_cv_seq(0,3,1) assert_array_almost_equal(obl,array([-0.348602, 1.393206, 5.486800, 11.492120]),5) class TestParabolicCylinder(object): def test_pbdn_seq(self): pb = special.pbdn_seq(1,.1) assert_array_almost_equal(pb,(array([0.9975, 0.0998]), array([-0.0499, 0.9925])),4) def test_pbdv(self): special.pbdv(1,.2) 1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0] def test_pbdv_seq(self): pbn = special.pbdn_seq(1,.1) pbv = special.pbdv_seq(1,.1) assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) def test_pbdv_points(self): # simple case eta = np.linspace(-10, 10, 5) z = 2**(eta/2)*np.sqrt(np.pi)/special.gamma(.5-.5*eta) assert_allclose(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14) # some points assert_allclose(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12) assert_allclose(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12) def test_pbdv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbdv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) def test_pbvv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbvv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) class TestPolygamma(object): # from Table 6.2 (pg. 271) of A&S def test_polygamma(self): poly2 = special.polygamma(2,1) poly3 = special.polygamma(3,1) assert_almost_equal(poly2,-2.4041138063,10) assert_almost_equal(poly3,6.4939394023,10) # Test polygamma(0, x) == psi(x) x = [2, 3, 1.1e14] assert_almost_equal(special.polygamma(0, x), special.psi(x)) # Test broadcasting n = [0, 1, 2] x = [0.5, 1.5, 2.5] expected = [-1.9635100260214238, 0.93480220054467933, -0.23620405164172739] assert_almost_equal(special.polygamma(n, x), expected) expected = np.row_stack([expected]*2) assert_almost_equal(special.polygamma(n, np.row_stack([x]*2)), expected) assert_almost_equal(special.polygamma(np.row_stack([n]*2), x), expected) class TestProCvSeq(object): def test_pro_cv_seq(self): prol = special.pro_cv_seq(0,3,1) assert_array_almost_equal(prol,array([0.319000, 2.593084, 6.533471, 12.514462]),5) class TestPsi(object): def test_psi(self): ps = special.psi(1) assert_almost_equal(ps,-0.57721566490153287,8) class TestRadian(object): def test_radian(self): rad = special.radian(90,0,0) assert_almost_equal(rad,pi/2.0,5) def test_radianmore(self): rad1 = special.radian(90,1,60) assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) class TestRiccati(object): def test_riccati_jn(self): N, x = 2, 0.2 S = np.empty((N, N)) for n in range(N): j = special.spherical_jn(n, x) jp = special.spherical_jn(n, x, derivative=True) S[0,n] = x*j S[1,n] = x*jp + j assert_array_almost_equal(S, special.riccati_jn(n, x), 8) def test_riccati_yn(self): N, x = 2, 0.2 C = np.empty((N, N)) for n in range(N): y = special.spherical_yn(n, x) yp = special.spherical_yn(n, x, derivative=True) C[0,n] = x*y C[1,n] = x*yp + y assert_array_almost_equal(C, special.riccati_yn(n, x), 8) class TestRound(object): def test_round(self): rnd = list(map(int,(special.round(10.1),special.round(10.4),special.round(10.5),special.round(10.6)))) # Note: According to the documentation, scipy.special.round is # supposed to round to the nearest even number if the fractional # part is exactly 0.5. On some platforms, this does not appear # to work and thus this test may fail. However, this unit test is # correctly written. rndrl = (10,10,10,11) assert_array_equal(rnd,rndrl) def test_sph_harm(): # Tests derived from tables in # https://en.wikipedia.org/wiki/Table_of_spherical_harmonics sh = special.sph_harm pi = np.pi exp = np.exp sqrt = np.sqrt sin = np.sin cos = np.cos assert_array_almost_equal(sh(0,0,0,0), 0.5/sqrt(pi)) assert_array_almost_equal(sh(-2,2,0.,pi/4), 0.25*sqrt(15./(2.*pi)) * (sin(pi/4))**2.) assert_array_almost_equal(sh(-2,2,0.,pi/2), 0.25*sqrt(15./(2.*pi))) assert_array_almost_equal(sh(2,2,pi,pi/2), 0.25*sqrt(15/(2.*pi)) * exp(0+2.*pi*1j)*sin(pi/2.)**2.) assert_array_almost_equal(sh(2,4,pi/4.,pi/3.), (3./8.)*sqrt(5./(2.*pi)) * exp(0+2.*pi/4.*1j) * sin(pi/3.)**2. * (7.*cos(pi/3.)**2.-1)) assert_array_almost_equal(sh(4,4,pi/8.,pi/6.), (3./16.)*sqrt(35./(2.*pi)) * exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.) def test_sph_harm_ufunc_loop_selection(): # see https://github.com/scipy/scipy/issues/4895 dt = np.dtype(np.complex128) assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt) assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt) assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt) assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt) assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt) assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt) class TestStruve(object): def _series(self, v, z, n=100): """Compute Struve function & error estimate from its power series.""" k = arange(0, n) r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5) err = abs(r).max() * finfo(float_).eps * n return r.sum(), err def test_vs_series(self): """Check Struve function versus its power series""" for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]: for z in [1, 10, 19, 21, 30]: value, err = self._series(v, z) assert_allclose(special.struve(v, z), value, rtol=0, atol=err), (v, z) def test_some_values(self): assert_allclose(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7) assert_allclose(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8) assert_allclose(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12) assert_allclose(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11) assert_equal(special.struve(-12, -41), -special.struve(-12, 41)) assert_equal(special.struve(+12, -41), -special.struve(+12, 41)) assert_equal(special.struve(-11, -41), +special.struve(-11, 41)) assert_equal(special.struve(+11, -41), +special.struve(+11, 41)) assert_(isnan(special.struve(-7.1, -1))) assert_(isnan(special.struve(-10.1, -1))) def test_regression_679(self): """Regression test for #679""" assert_allclose(special.struve(-1.0, 20 - 1e-8), special.struve(-1.0, 20 + 1e-8)) assert_allclose(special.struve(-2.0, 20 - 1e-8), special.struve(-2.0, 20 + 1e-8)) assert_allclose(special.struve(-4.3, 20 - 1e-8), special.struve(-4.3, 20 + 1e-8)) def test_chi2_smalldf(): assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110) def test_ch2_inf(): assert_equal(special.chdtr(0.7,np.inf), 1.0) def test_chi2c_smalldf(): assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110) def test_chi2_inv_smalldf(): assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3) def test_agm_simple(): rtol = 1e-13 # Gauss's constant assert_allclose(1/special.agm(1, np.sqrt(2)), 0.834626841674073186, rtol=rtol) # These values were computed using Wolfram Alpha, with the # function ArithmeticGeometricMean[a, b]. agm13 = 1.863616783244897 agm15 = 2.604008190530940 agm35 = 3.936235503649555 assert_allclose(special.agm([[1], [3]], [1, 3, 5]), [[1, agm13, agm15], [agm13, 3, agm35]], rtol=rtol) # Computed by the iteration formula using mpmath, # with mpmath.mp.prec = 1000: agm12 = 1.4567910310469068 assert_allclose(special.agm(1, 2), agm12, rtol=rtol) assert_allclose(special.agm(2, 1), agm12, rtol=rtol) assert_allclose(special.agm(-1, -2), -agm12, rtol=rtol) assert_allclose(special.agm(24, 6), 13.458171481725614, rtol=rtol) assert_allclose(special.agm(13, 123456789.5), 11111458.498599306, rtol=rtol) assert_allclose(special.agm(1e30, 1), 2.229223055945383e+28, rtol=rtol) assert_allclose(special.agm(1e-22, 1), 0.030182566420169886, rtol=rtol) assert_allclose(special.agm(1e150, 1e180), 2.229223055945383e+178, rtol=rtol) assert_allclose(special.agm(1e180, 1e-150), 2.0634722510162677e+177, rtol=rtol) assert_allclose(special.agm(1e-150, 1e-170), 3.3112619670463756e-152, rtol=rtol) fi = np.finfo(1.0) assert_allclose(special.agm(fi.tiny, fi.max), 1.9892072050015473e+305, rtol=rtol) assert_allclose(special.agm(0.75*fi.max, fi.max), 1.564904312298045e+308, rtol=rtol) assert_allclose(special.agm(fi.tiny, 3*fi.tiny), 4.1466849866735005e-308, rtol=rtol) # zero, nan and inf cases. assert_equal(special.agm(0, 0), 0) assert_equal(special.agm(99, 0), 0) assert_equal(special.agm(-1, 10), np.nan) assert_equal(special.agm(0, np.inf), np.nan) assert_equal(special.agm(np.inf, 0), np.nan) assert_equal(special.agm(0, -np.inf), np.nan) assert_equal(special.agm(-np.inf, 0), np.nan) assert_equal(special.agm(np.inf, -np.inf), np.nan) assert_equal(special.agm(-np.inf, np.inf), np.nan) assert_equal(special.agm(1, np.nan), np.nan) assert_equal(special.agm(np.nan, -1), np.nan) assert_equal(special.agm(1, np.inf), np.inf) assert_equal(special.agm(np.inf, 1), np.inf) assert_equal(special.agm(-1, -np.inf), -np.inf) assert_equal(special.agm(-np.inf, -1), -np.inf) def test_legacy(): # Legacy behavior: truncating arguments to integers with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3)) assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3)) assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3)) assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3)) assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3)) assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3)) assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3)) assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3)) assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3)) @with_special_errors def test_error_raising(): assert_raises(special.SpecialFunctionError, special.iv, 1, 1e99j) def test_xlogy(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x*np.log(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float) z2 = np.r_[z1, [(0, 1j), (1, 1j)]] w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13) w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1]) assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13) def test_xlog1py(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x * np.log1p(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0), (1, 1e-30)], dtype=float) w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13) def test_entr(): def xfunc(x): if x < 0: return -np.inf else: return -special.xlogy(x, x) values = (0, 0.5, 1.0, np.inf) signs = [-1, 1] arr = [] for sgn, v in itertools.product(signs, values): arr.append(sgn * v) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z) assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13) def test_kl_div(): def xfunc(x, y): if x < 0 or y < 0 or (y == 0 and x != 0): # extension of natural domain to preserve convexity return np.inf elif np.isposinf(x) or np.isposinf(y): # limits within the natural domain return np.inf elif x == 0: return y else: return special.xlogy(x, x/y) - x + y values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13) def test_rel_entr(): def xfunc(x, y): if x > 0 and y > 0: return special.xlogy(x, x/y) elif x == 0 and y >= 0: return 0 else: return np.inf values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13) def test_huber(): assert_equal(special.huber(-1, 1.5), np.inf) assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5)) assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2)) def xfunc(delta, r): if delta < 0: return np.inf elif np.abs(r) < delta: return 0.5 * np.square(r) else: return delta * (np.abs(r) - 0.5 * delta) z = np.random.randn(10, 2) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13) def test_pseudo_huber(): def xfunc(delta, r): if delta < 0: return np.inf elif (not delta) or (not r): return 0 else: return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1) z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]]) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13)
aeklant/scipy
scipy/special/tests/test_basic.py
scipy/sparse/spfuncs.py
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections.abc import Iterable import warnings import numpy import operator from . import _ni_support from . import _nd_image from . import _ni_docstrings __all__ = ['correlate1d', 'convolve1d', 'gaussian_filter1d', 'gaussian_filter', 'prewitt', 'sobel', 'generic_laplace', 'laplace', 'gaussian_laplace', 'generic_gradient_magnitude', 'gaussian_gradient_magnitude', 'correlate', 'convolve', 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d', 'maximum_filter1d', 'minimum_filter', 'maximum_filter', 'rank_filter', 'median_filter', 'percentile_filter', 'generic_filter1d', 'generic_filter'] def _invalid_origin(origin, lenw): return (origin < -(lenw // 2)) or (origin > (lenw - 1) // 2) @_ni_docstrings.docfiller def correlate1d(input, weights, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a 1-D correlation along the given axis. The lines of the array along the given axis are correlated with the given weights. Parameters ---------- %(input)s weights : array 1-D sequence of numbers. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Examples -------- >>> from scipy.ndimage import correlate1d >>> correlate1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3]) array([ 8, 26, 8, 12, 7, 28, 36, 9]) """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output = _ni_support._get_output(output, input) weights = numpy.asarray(weights, dtype=numpy.float64) if weights.ndim != 1 or weights.shape[0] < 1: raise RuntimeError('no filter weights given') if not weights.flags.contiguous: weights = weights.copy() axis = _ni_support._check_axis(axis, input.ndim) if _invalid_origin(origin, len(weights)): raise ValueError('Invalid origin; origin must satisfy ' '-(len(weights) // 2) <= origin <= ' '(len(weights)-1) // 2') mode = _ni_support._extend_mode_to_code(mode) _nd_image.correlate1d(input, weights, axis, output, mode, cval, origin) return output @_ni_docstrings.docfiller def convolve1d(input, weights, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a 1-D convolution along the given axis. The lines of the array along the given axis are convolved with the given weights. Parameters ---------- %(input)s weights : ndarray 1-D sequence of numbers. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Returns ------- convolve1d : ndarray Convolved array with same shape as input Examples -------- >>> from scipy.ndimage import convolve1d >>> convolve1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3]) array([14, 24, 4, 13, 12, 36, 27, 0]) """ weights = weights[::-1] origin = -origin if not len(weights) & 1: origin -= 1 return correlate1d(input, weights, axis, output, mode, cval, origin) def _gaussian_kernel1d(sigma, order, radius): """ Computes a 1-D Gaussian convolution kernel. """ if order < 0: raise ValueError('order must be non-negative') exponent_range = numpy.arange(order + 1) sigma2 = sigma * sigma x = numpy.arange(-radius, radius+1) phi_x = numpy.exp(-0.5 / sigma2 * x ** 2) phi_x = phi_x / phi_x.sum() if order == 0: return phi_x else: # f(x) = q(x) * phi(x) = q(x) * exp(p(x)) # f'(x) = (q'(x) + q(x) * p'(x)) * phi(x) # p'(x) = -1 / sigma ** 2 # Implement q'(x) + q(x) * p'(x) as a matrix operator and apply to the # coefficients of q(x) q = numpy.zeros(order + 1) q[0] = 1 D = numpy.diag(exponent_range[1:], 1) # D @ q(x) = q'(x) P = numpy.diag(numpy.ones(order)/-sigma2, -1) # P @ q(x) = q(x) * p'(x) Q_deriv = D + P for _ in range(order): q = Q_deriv.dot(q) q = (x[:, None] ** exponent_range).dot(q) return q * phi_x @_ni_docstrings.docfiller def gaussian_filter1d(input, sigma, axis=-1, order=0, output=None, mode="reflect", cval=0.0, truncate=4.0): """1-D Gaussian filter. Parameters ---------- %(input)s sigma : scalar standard deviation for Gaussian kernel %(axis)s order : int, optional An order of 0 corresponds to convolution with a Gaussian kernel. A positive order corresponds to convolution with that derivative of a Gaussian. %(output)s %(mode)s %(cval)s truncate : float, optional Truncate the filter at this many standard deviations. Default is 4.0. Returns ------- gaussian_filter1d : ndarray Examples -------- >>> from scipy.ndimage import gaussian_filter1d >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 1) array([ 1.42704095, 2.06782203, 3. , 3.93217797, 4.57295905]) >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 4) array([ 2.91948343, 2.95023502, 3. , 3.04976498, 3.08051657]) >>> import matplotlib.pyplot as plt >>> np.random.seed(280490) >>> x = np.random.randn(101).cumsum() >>> y3 = gaussian_filter1d(x, 3) >>> y6 = gaussian_filter1d(x, 6) >>> plt.plot(x, 'k', label='original data') >>> plt.plot(y3, '--', label='filtered, sigma=3') >>> plt.plot(y6, ':', label='filtered, sigma=6') >>> plt.legend() >>> plt.grid() >>> plt.show() """ sd = float(sigma) # make the radius of the filter equal to truncate standard deviations lw = int(truncate * sd + 0.5) # Since we are calling correlate, not convolve, revert the kernel weights = _gaussian_kernel1d(sigma, order, lw)[::-1] return correlate1d(input, weights, axis, output, mode, cval, 0) @_ni_docstrings.docfiller def gaussian_filter(input, sigma, order=0, output=None, mode="reflect", cval=0.0, truncate=4.0): """Multidimensional Gaussian filter. Parameters ---------- %(input)s sigma : scalar or sequence of scalars Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. order : int or sequence of ints, optional The order of the filter along each axis is given as a sequence of integers, or as a single number. An order of 0 corresponds to convolution with a Gaussian kernel. A positive order corresponds to convolution with that derivative of a Gaussian. %(output)s %(mode_multiple)s %(cval)s truncate : float Truncate the filter at this many standard deviations. Default is 4.0. Returns ------- gaussian_filter : ndarray Returned array of same shape as `input`. Notes ----- The multidimensional filter is implemented as a sequence of 1-D convolution filters. The intermediate arrays are stored in the same data type as the output. Therefore, for output types with a limited precision, the results may be imprecise because intermediate results may be stored with insufficient precision. Examples -------- >>> from scipy.ndimage import gaussian_filter >>> a = np.arange(50, step=2).reshape((5,5)) >>> a array([[ 0, 2, 4, 6, 8], [10, 12, 14, 16, 18], [20, 22, 24, 26, 28], [30, 32, 34, 36, 38], [40, 42, 44, 46, 48]]) >>> gaussian_filter(a, sigma=1) array([[ 4, 6, 8, 9, 11], [10, 12, 14, 15, 17], [20, 22, 24, 25, 27], [29, 31, 33, 34, 36], [35, 37, 39, 40, 42]]) >>> from scipy import misc >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> plt.gray() # show the filtered result in grayscale >>> ax1 = fig.add_subplot(121) # left side >>> ax2 = fig.add_subplot(122) # right side >>> ascent = misc.ascent() >>> result = gaussian_filter(ascent, sigma=5) >>> ax1.imshow(ascent) >>> ax2.imshow(result) >>> plt.show() """ input = numpy.asarray(input) output = _ni_support._get_output(output, input) orders = _ni_support._normalize_sequence(order, input.ndim) sigmas = _ni_support._normalize_sequence(sigma, input.ndim) modes = _ni_support._normalize_sequence(mode, input.ndim) axes = list(range(input.ndim)) axes = [(axes[ii], sigmas[ii], orders[ii], modes[ii]) for ii in range(len(axes)) if sigmas[ii] > 1e-15] if len(axes) > 0: for axis, sigma, order, mode in axes: gaussian_filter1d(input, sigma, axis, order, output, mode, cval, truncate) input = output else: output[...] = input[...] return output @_ni_docstrings.docfiller def prewitt(input, axis=-1, output=None, mode="reflect", cval=0.0): """Calculate a Prewitt filter. Parameters ---------- %(input)s %(axis)s %(output)s %(mode_multiple)s %(cval)s Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> plt.gray() # show the filtered result in grayscale >>> ax1 = fig.add_subplot(121) # left side >>> ax2 = fig.add_subplot(122) # right side >>> ascent = misc.ascent() >>> result = ndimage.prewitt(ascent) >>> ax1.imshow(ascent) >>> ax2.imshow(result) >>> plt.show() """ input = numpy.asarray(input) axis = _ni_support._check_axis(axis, input.ndim) output = _ni_support._get_output(output, input) modes = _ni_support._normalize_sequence(mode, input.ndim) correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0) axes = [ii for ii in range(input.ndim) if ii != axis] for ii in axes: correlate1d(output, [1, 1, 1], ii, output, modes[ii], cval, 0,) return output @_ni_docstrings.docfiller def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0): """Calculate a Sobel filter. Parameters ---------- %(input)s %(axis)s %(output)s %(mode_multiple)s %(cval)s Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> plt.gray() # show the filtered result in grayscale >>> ax1 = fig.add_subplot(121) # left side >>> ax2 = fig.add_subplot(122) # right side >>> ascent = misc.ascent() >>> result = ndimage.sobel(ascent) >>> ax1.imshow(ascent) >>> ax2.imshow(result) >>> plt.show() """ input = numpy.asarray(input) axis = _ni_support._check_axis(axis, input.ndim) output = _ni_support._get_output(output, input) modes = _ni_support._normalize_sequence(mode, input.ndim) correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0) axes = [ii for ii in range(input.ndim) if ii != axis] for ii in axes: correlate1d(output, [1, 2, 1], ii, output, modes[ii], cval, 0) return output @_ni_docstrings.docfiller def generic_laplace(input, derivative2, output=None, mode="reflect", cval=0.0, extra_arguments=(), extra_keywords=None): """ N-D Laplace filter using a provided second derivative function. Parameters ---------- %(input)s derivative2 : callable Callable with the following signature:: derivative2(input, axis, output, mode, cval, *extra_arguments, **extra_keywords) See `extra_arguments`, `extra_keywords` below. %(output)s %(mode_multiple)s %(cval)s %(extra_keywords)s %(extra_arguments)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) output = _ni_support._get_output(output, input) axes = list(range(input.ndim)) if len(axes) > 0: modes = _ni_support._normalize_sequence(mode, len(axes)) derivative2(input, axes[0], output, modes[0], cval, *extra_arguments, **extra_keywords) for ii in range(1, len(axes)): tmp = derivative2(input, axes[ii], output.dtype, modes[ii], cval, *extra_arguments, **extra_keywords) output += tmp else: output[...] = input[...] return output @_ni_docstrings.docfiller def laplace(input, output=None, mode="reflect", cval=0.0): """N-D Laplace filter based on approximate second derivatives. Parameters ---------- %(input)s %(output)s %(mode_multiple)s %(cval)s Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> plt.gray() # show the filtered result in grayscale >>> ax1 = fig.add_subplot(121) # left side >>> ax2 = fig.add_subplot(122) # right side >>> ascent = misc.ascent() >>> result = ndimage.laplace(ascent) >>> ax1.imshow(ascent) >>> ax2.imshow(result) >>> plt.show() """ def derivative2(input, axis, output, mode, cval): return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0) return generic_laplace(input, derivative2, output, mode, cval) @_ni_docstrings.docfiller def gaussian_laplace(input, sigma, output=None, mode="reflect", cval=0.0, **kwargs): """Multidimensional Laplace filter using Gaussian second derivatives. Parameters ---------- %(input)s sigma : scalar or sequence of scalars The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. %(output)s %(mode_multiple)s %(cval)s Extra keyword arguments will be passed to gaussian_filter(). Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> ascent = misc.ascent() >>> fig = plt.figure() >>> plt.gray() # show the filtered result in grayscale >>> ax1 = fig.add_subplot(121) # left side >>> ax2 = fig.add_subplot(122) # right side >>> result = ndimage.gaussian_laplace(ascent, sigma=1) >>> ax1.imshow(result) >>> result = ndimage.gaussian_laplace(ascent, sigma=3) >>> ax2.imshow(result) >>> plt.show() """ input = numpy.asarray(input) def derivative2(input, axis, output, mode, cval, sigma, **kwargs): order = [0] * input.ndim order[axis] = 2 return gaussian_filter(input, sigma, order, output, mode, cval, **kwargs) return generic_laplace(input, derivative2, output, mode, cval, extra_arguments=(sigma,), extra_keywords=kwargs) @_ni_docstrings.docfiller def generic_gradient_magnitude(input, derivative, output=None, mode="reflect", cval=0.0, extra_arguments=(), extra_keywords=None): """Gradient magnitude using a provided gradient function. Parameters ---------- %(input)s derivative : callable Callable with the following signature:: derivative(input, axis, output, mode, cval, *extra_arguments, **extra_keywords) See `extra_arguments`, `extra_keywords` below. `derivative` can assume that `input` and `output` are ndarrays. Note that the output from `derivative` is modified inplace; be careful to copy important inputs before returning them. %(output)s %(mode_multiple)s %(cval)s %(extra_keywords)s %(extra_arguments)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) output = _ni_support._get_output(output, input) axes = list(range(input.ndim)) if len(axes) > 0: modes = _ni_support._normalize_sequence(mode, len(axes)) derivative(input, axes[0], output, modes[0], cval, *extra_arguments, **extra_keywords) numpy.multiply(output, output, output) for ii in range(1, len(axes)): tmp = derivative(input, axes[ii], output.dtype, modes[ii], cval, *extra_arguments, **extra_keywords) numpy.multiply(tmp, tmp, tmp) output += tmp # This allows the sqrt to work with a different default casting numpy.sqrt(output, output, casting='unsafe') else: output[...] = input[...] return output @_ni_docstrings.docfiller def gaussian_gradient_magnitude(input, sigma, output=None, mode="reflect", cval=0.0, **kwargs): """Multidimensional gradient magnitude using Gaussian derivatives. Parameters ---------- %(input)s sigma : scalar or sequence of scalars The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. %(output)s %(mode_multiple)s %(cval)s Extra keyword arguments will be passed to gaussian_filter(). Returns ------- gaussian_gradient_magnitude : ndarray Filtered array. Has the same shape as `input`. Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> plt.gray() # show the filtered result in grayscale >>> ax1 = fig.add_subplot(121) # left side >>> ax2 = fig.add_subplot(122) # right side >>> ascent = misc.ascent() >>> result = ndimage.gaussian_gradient_magnitude(ascent, sigma=5) >>> ax1.imshow(ascent) >>> ax2.imshow(result) >>> plt.show() """ input = numpy.asarray(input) def derivative(input, axis, output, mode, cval, sigma, **kwargs): order = [0] * input.ndim order[axis] = 1 return gaussian_filter(input, sigma, order, output, mode, cval, **kwargs) return generic_gradient_magnitude(input, derivative, output, mode, cval, extra_arguments=(sigma,), extra_keywords=kwargs) def _correlate_or_convolve(input, weights, output, mode, cval, origin, convolution): input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') origins = _ni_support._normalize_sequence(origin, input.ndim) weights = numpy.asarray(weights, dtype=numpy.float64) wshape = [ii for ii in weights.shape if ii > 0] if len(wshape) != input.ndim: raise RuntimeError('filter weights array has incorrect shape.') if convolution: weights = weights[tuple([slice(None, None, -1)] * weights.ndim)] for ii in range(len(origins)): origins[ii] = -origins[ii] if not weights.shape[ii] & 1: origins[ii] -= 1 for origin, lenw in zip(origins, wshape): if _invalid_origin(origin, lenw): raise ValueError('Invalid origin; origin must satisfy ' '-(weights.shape[k] // 2) <= origin[k] <= ' '(weights.shape[k]-1) // 2') if not weights.flags.contiguous: weights = weights.copy() output = _ni_support._get_output(output, input) if not isinstance(mode, str) and isinstance(mode, Iterable): raise RuntimeError("A sequence of modes is not supported") mode = _ni_support._extend_mode_to_code(mode) _nd_image.correlate(input, weights, output, mode, cval, origins) return output @_ni_docstrings.docfiller def correlate(input, weights, output=None, mode='reflect', cval=0.0, origin=0): """ Multidimensional correlation. The array is correlated with the given kernel. Parameters ---------- %(input)s weights : ndarray array of weights, same number of dimensions as input %(output)s %(mode)s %(cval)s %(origin_multiple)s See Also -------- convolve : Convolve an image with a kernel. """ return _correlate_or_convolve(input, weights, output, mode, cval, origin, False) @_ni_docstrings.docfiller def convolve(input, weights, output=None, mode='reflect', cval=0.0, origin=0): """ Multidimensional convolution. The array is convolved with the given kernel. Parameters ---------- %(input)s weights : array_like Array of weights, same number of dimensions as input %(output)s %(mode)s cval : scalar, optional Value to fill past edges of input if `mode` is 'constant'. Default is 0.0 %(origin_multiple)s Returns ------- result : ndarray The result of convolution of `input` with `weights`. See Also -------- correlate : Correlate an image with a kernel. Notes ----- Each value in result is :math:`C_i = \\sum_j{I_{i+k-j} W_j}`, where W is the `weights` kernel, j is the N-D spatial index over :math:`W`, I is the `input` and k is the coordinate of the center of W, specified by `origin` in the input parameters. Examples -------- Perhaps the simplest case to understand is ``mode='constant', cval=0.0``, because in this case borders (i.e., where the `weights` kernel, centered on any one value, extends beyond an edge of `input`) are treated as zeros. >>> a = np.array([[1, 2, 0, 0], ... [5, 3, 0, 4], ... [0, 0, 0, 7], ... [9, 3, 0, 0]]) >>> k = np.array([[1,1,1],[1,1,0],[1,0,0]]) >>> from scipy import ndimage >>> ndimage.convolve(a, k, mode='constant', cval=0.0) array([[11, 10, 7, 4], [10, 3, 11, 11], [15, 12, 14, 7], [12, 3, 7, 0]]) Setting ``cval=1.0`` is equivalent to padding the outer edge of `input` with 1.0's (and then extracting only the original region of the result). >>> ndimage.convolve(a, k, mode='constant', cval=1.0) array([[13, 11, 8, 7], [11, 3, 11, 14], [16, 12, 14, 10], [15, 6, 10, 5]]) With ``mode='reflect'`` (the default), outer values are reflected at the edge of `input` to fill in missing values. >>> b = np.array([[2, 0, 0], ... [1, 0, 0], ... [0, 0, 0]]) >>> k = np.array([[0,1,0], [0,1,0], [0,1,0]]) >>> ndimage.convolve(b, k, mode='reflect') array([[5, 0, 0], [3, 0, 0], [1, 0, 0]]) This includes diagonally at the corners. >>> k = np.array([[1,0,0],[0,1,0],[0,0,1]]) >>> ndimage.convolve(b, k) array([[4, 2, 0], [3, 2, 0], [1, 1, 0]]) With ``mode='nearest'``, the single nearest value in to an edge in `input` is repeated as many times as needed to match the overlapping `weights`. >>> c = np.array([[2, 0, 1], ... [1, 0, 0], ... [0, 0, 0]]) >>> k = np.array([[0, 1, 0], ... [0, 1, 0], ... [0, 1, 0], ... [0, 1, 0], ... [0, 1, 0]]) >>> ndimage.convolve(c, k, mode='nearest') array([[7, 0, 3], [5, 0, 2], [3, 0, 1]]) """ return _correlate_or_convolve(input, weights, output, mode, cval, origin, True) @_ni_docstrings.docfiller def uniform_filter1d(input, size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a 1-D uniform filter along the given axis. The lines of the array along the given axis are filtered with a uniform filter of given size. Parameters ---------- %(input)s size : int length of uniform filter %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Examples -------- >>> from scipy.ndimage import uniform_filter1d >>> uniform_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3) array([4, 3, 4, 1, 4, 6, 6, 3]) """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') axis = _ni_support._check_axis(axis, input.ndim) if size < 1: raise RuntimeError('incorrect filter size') output = _ni_support._get_output(output, input) if (size // 2 + origin < 0) or (size // 2 + origin >= size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.uniform_filter1d(input, size, axis, output, mode, cval, origin) return output @_ni_docstrings.docfiller def uniform_filter(input, size=3, output=None, mode="reflect", cval=0.0, origin=0): """Multidimensional uniform filter. Parameters ---------- %(input)s size : int or sequence of ints, optional The sizes of the uniform filter are given for each axis as a sequence, or as a single number, in which case the size is equal for all axes. %(output)s %(mode_multiple)s %(cval)s %(origin_multiple)s Returns ------- uniform_filter : ndarray Filtered array. Has the same shape as `input`. Notes ----- The multidimensional filter is implemented as a sequence of 1-D uniform filters. The intermediate arrays are stored in the same data type as the output. Therefore, for output types with a limited precision, the results may be imprecise because intermediate results may be stored with insufficient precision. Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> plt.gray() # show the filtered result in grayscale >>> ax1 = fig.add_subplot(121) # left side >>> ax2 = fig.add_subplot(122) # right side >>> ascent = misc.ascent() >>> result = ndimage.uniform_filter(ascent, size=20) >>> ax1.imshow(ascent) >>> ax2.imshow(result) >>> plt.show() """ input = numpy.asarray(input) output = _ni_support._get_output(output, input) sizes = _ni_support._normalize_sequence(size, input.ndim) origins = _ni_support._normalize_sequence(origin, input.ndim) modes = _ni_support._normalize_sequence(mode, input.ndim) axes = list(range(input.ndim)) axes = [(axes[ii], sizes[ii], origins[ii], modes[ii]) for ii in range(len(axes)) if sizes[ii] > 1] if len(axes) > 0: for axis, size, origin, mode in axes: uniform_filter1d(input, int(size), axis, output, mode, cval, origin) input = output else: output[...] = input[...] return output @_ni_docstrings.docfiller def minimum_filter1d(input, size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a 1-D minimum filter along the given axis. The lines of the array along the given axis are filtered with a minimum filter of given size. Parameters ---------- %(input)s size : int length along which to calculate 1D minimum %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Notes ----- This function implements the MINLIST algorithm [1]_, as described by Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being the `input` length, regardless of filter size. References ---------- .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html Examples -------- >>> from scipy.ndimage import minimum_filter1d >>> minimum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3) array([2, 0, 0, 0, 1, 1, 0, 0]) """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') axis = _ni_support._check_axis(axis, input.ndim) if size < 1: raise RuntimeError('incorrect filter size') output = _ni_support._get_output(output, input) if (size // 2 + origin < 0) or (size // 2 + origin >= size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, origin, 1) return output @_ni_docstrings.docfiller def maximum_filter1d(input, size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a 1-D maximum filter along the given axis. The lines of the array along the given axis are filtered with a maximum filter of given size. Parameters ---------- %(input)s size : int Length along which to calculate the 1-D maximum. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Returns ------- maximum1d : ndarray, None Maximum-filtered array with same shape as input. None if `output` is not None Notes ----- This function implements the MAXLIST algorithm [1]_, as described by Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being the `input` length, regardless of filter size. References ---------- .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html Examples -------- >>> from scipy.ndimage import maximum_filter1d >>> maximum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3) array([8, 8, 8, 4, 9, 9, 9, 9]) """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') axis = _ni_support._check_axis(axis, input.ndim) if size < 1: raise RuntimeError('incorrect filter size') output = _ni_support._get_output(output, input) if (size // 2 + origin < 0) or (size // 2 + origin >= size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, origin, 0) return output def _min_or_max_filter(input, size, footprint, structure, output, mode, cval, origin, minimum): if (size is not None) and (footprint is not None): warnings.warn("ignoring size because footprint is set", UserWarning, stacklevel=3) if structure is None: if footprint is None: if size is None: raise RuntimeError("no footprint provided") separable = True else: footprint = numpy.asarray(footprint, dtype=bool) if not footprint.any(): raise ValueError("All-zero footprint is not supported.") if footprint.all(): size = footprint.shape footprint = None separable = True else: separable = False else: structure = numpy.asarray(structure, dtype=numpy.float64) separable = False if footprint is None: footprint = numpy.ones(structure.shape, bool) else: footprint = numpy.asarray(footprint, dtype=bool) input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output = _ni_support._get_output(output, input) origins = _ni_support._normalize_sequence(origin, input.ndim) if separable: sizes = _ni_support._normalize_sequence(size, input.ndim) modes = _ni_support._normalize_sequence(mode, input.ndim) axes = list(range(input.ndim)) axes = [(axes[ii], sizes[ii], origins[ii], modes[ii]) for ii in range(len(axes)) if sizes[ii] > 1] if minimum: filter_ = minimum_filter1d else: filter_ = maximum_filter1d if len(axes) > 0: for axis, size, origin, mode in axes: filter_(input, int(size), axis, output, mode, cval, origin) input = output else: output[...] = input[...] else: fshape = [ii for ii in footprint.shape if ii > 0] if len(fshape) != input.ndim: raise RuntimeError('footprint array has incorrect shape.') for origin, lenf in zip(origins, fshape): if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): raise ValueError('invalid origin') if not footprint.flags.contiguous: footprint = footprint.copy() if structure is not None: if len(structure.shape) != input.ndim: raise RuntimeError('structure array has incorrect shape') if not structure.flags.contiguous: structure = structure.copy() if not isinstance(mode, str) and isinstance(mode, Iterable): raise RuntimeError( "A sequence of modes is not supported for non-separable " "footprints") mode = _ni_support._extend_mode_to_code(mode) _nd_image.min_or_max_filter(input, footprint, structure, output, mode, cval, origins, minimum) return output @_ni_docstrings.docfiller def minimum_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a multidimensional minimum filter. Parameters ---------- %(input)s %(size_foot)s %(output)s %(mode_multiple)s %(cval)s %(origin_multiple)s Returns ------- minimum_filter : ndarray Filtered array. Has the same shape as `input`. Notes ----- A sequence of modes (one per axis) is only supported when the footprint is separable. Otherwise, a single mode string must be provided. Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> plt.gray() # show the filtered result in grayscale >>> ax1 = fig.add_subplot(121) # left side >>> ax2 = fig.add_subplot(122) # right side >>> ascent = misc.ascent() >>> result = ndimage.minimum_filter(ascent, size=20) >>> ax1.imshow(ascent) >>> ax2.imshow(result) >>> plt.show() """ return _min_or_max_filter(input, size, footprint, None, output, mode, cval, origin, 1) @_ni_docstrings.docfiller def maximum_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a multidimensional maximum filter. Parameters ---------- %(input)s %(size_foot)s %(output)s %(mode_multiple)s %(cval)s %(origin_multiple)s Returns ------- maximum_filter : ndarray Filtered array. Has the same shape as `input`. Notes ----- A sequence of modes (one per axis) is only supported when the footprint is separable. Otherwise, a single mode string must be provided. Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> plt.gray() # show the filtered result in grayscale >>> ax1 = fig.add_subplot(121) # left side >>> ax2 = fig.add_subplot(122) # right side >>> ascent = misc.ascent() >>> result = ndimage.maximum_filter(ascent, size=20) >>> ax1.imshow(ascent) >>> ax2.imshow(result) >>> plt.show() """ return _min_or_max_filter(input, size, footprint, None, output, mode, cval, origin, 0) @_ni_docstrings.docfiller def _rank_filter(input, rank, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0, operation='rank'): if (size is not None) and (footprint is not None): warnings.warn("ignoring size because footprint is set", UserWarning, stacklevel=3) input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') origins = _ni_support._normalize_sequence(origin, input.ndim) if footprint is None: if size is None: raise RuntimeError("no footprint or filter size provided") sizes = _ni_support._normalize_sequence(size, input.ndim) footprint = numpy.ones(sizes, dtype=bool) else: footprint = numpy.asarray(footprint, dtype=bool) fshape = [ii for ii in footprint.shape if ii > 0] if len(fshape) != input.ndim: raise RuntimeError('filter footprint array has incorrect shape.') for origin, lenf in zip(origins, fshape): if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): raise ValueError('invalid origin') if not footprint.flags.contiguous: footprint = footprint.copy() filter_size = numpy.where(footprint, 1, 0).sum() if operation == 'median': rank = filter_size // 2 elif operation == 'percentile': percentile = rank if percentile < 0.0: percentile += 100.0 if percentile < 0 or percentile > 100: raise RuntimeError('invalid percentile') if percentile == 100.0: rank = filter_size - 1 else: rank = int(float(filter_size) * percentile / 100.0) if rank < 0: rank += filter_size if rank < 0 or rank >= filter_size: raise RuntimeError('rank not within filter footprint size') if rank == 0: return minimum_filter(input, None, footprint, output, mode, cval, origins) elif rank == filter_size - 1: return maximum_filter(input, None, footprint, output, mode, cval, origins) else: output = _ni_support._get_output(output, input) if not isinstance(mode, str) and isinstance(mode, Iterable): raise RuntimeError( "A sequence of modes is not supported by non-separable rank " "filters") mode = _ni_support._extend_mode_to_code(mode) _nd_image.rank_filter(input, rank, footprint, output, mode, cval, origins) return output @_ni_docstrings.docfiller def rank_filter(input, rank, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a multidimensional rank filter. Parameters ---------- %(input)s rank : int The rank parameter may be less then zero, i.e., rank = -1 indicates the largest element. %(size_foot)s %(output)s %(mode)s %(cval)s %(origin_multiple)s Returns ------- rank_filter : ndarray Filtered array. Has the same shape as `input`. Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> plt.gray() # show the filtered result in grayscale >>> ax1 = fig.add_subplot(121) # left side >>> ax2 = fig.add_subplot(122) # right side >>> ascent = misc.ascent() >>> result = ndimage.rank_filter(ascent, rank=42, size=20) >>> ax1.imshow(ascent) >>> ax2.imshow(result) >>> plt.show() """ rank = operator.index(rank) return _rank_filter(input, rank, size, footprint, output, mode, cval, origin, 'rank') @_ni_docstrings.docfiller def median_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """ Calculate a multidimensional median filter. Parameters ---------- %(input)s %(size_foot)s %(output)s %(mode)s %(cval)s %(origin_multiple)s Returns ------- median_filter : ndarray Filtered array. Has the same shape as `input`. Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> plt.gray() # show the filtered result in grayscale >>> ax1 = fig.add_subplot(121) # left side >>> ax2 = fig.add_subplot(122) # right side >>> ascent = misc.ascent() >>> result = ndimage.median_filter(ascent, size=20) >>> ax1.imshow(ascent) >>> ax2.imshow(result) >>> plt.show() """ return _rank_filter(input, 0, size, footprint, output, mode, cval, origin, 'median') @_ni_docstrings.docfiller def percentile_filter(input, percentile, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a multidimensional percentile filter. Parameters ---------- %(input)s percentile : scalar The percentile parameter may be less then zero, i.e., percentile = -20 equals percentile = 80 %(size_foot)s %(output)s %(mode)s %(cval)s %(origin_multiple)s Returns ------- percentile_filter : ndarray Filtered array. Has the same shape as `input`. Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> plt.gray() # show the filtered result in grayscale >>> ax1 = fig.add_subplot(121) # left side >>> ax2 = fig.add_subplot(122) # right side >>> ascent = misc.ascent() >>> result = ndimage.percentile_filter(ascent, percentile=20, size=20) >>> ax1.imshow(ascent) >>> ax2.imshow(result) >>> plt.show() """ return _rank_filter(input, percentile, size, footprint, output, mode, cval, origin, 'percentile') @_ni_docstrings.docfiller def generic_filter1d(input, function, filter_size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0, extra_arguments=(), extra_keywords=None): """Calculate a 1-D filter along the given axis. `generic_filter1d` iterates over the lines of the array, calling the given function at each line. The arguments of the line are the input line, and the output line. The input and output lines are 1-D double arrays. The input line is extended appropriately according to the filter size and origin. The output line must be modified in-place with the result. Parameters ---------- %(input)s function : {callable, scipy.LowLevelCallable} Function to apply along given axis. filter_size : scalar Length of the filter. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s %(extra_arguments)s %(extra_keywords)s Notes ----- This function also accepts low-level callback functions with one of the following signatures and wrapped in `scipy.LowLevelCallable`: .. code:: c int function(double *input_line, npy_intp input_length, double *output_line, npy_intp output_length, void *user_data) int function(double *input_line, intptr_t input_length, double *output_line, intptr_t output_length, void *user_data) The calling function iterates over the lines of the input and output arrays, calling the callback function at each line. The current line is extended according to the border conditions set by the calling function, and the result is copied into the array that is passed through ``input_line``. The length of the input line (after extension) is passed through ``input_length``. The callback function should apply the filter and store the result in the array passed through ``output_line``. The length of the output line is passed through ``output_length``. ``user_data`` is the data pointer provided to `scipy.LowLevelCallable` as-is. The callback function must return an integer error status that is zero if something went wrong and one otherwise. If an error occurs, you should normally set the python error status with an informative message before returning, otherwise a default error message is set by the calling function. In addition, some other low-level function pointer specifications are accepted, but these are for backward compatibility only and should not be used in new code. """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output = _ni_support._get_output(output, input) if filter_size < 1: raise RuntimeError('invalid filter size') axis = _ni_support._check_axis(axis, input.ndim) if (filter_size // 2 + origin < 0) or (filter_size // 2 + origin >= filter_size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.generic_filter1d(input, function, filter_size, axis, output, mode, cval, origin, extra_arguments, extra_keywords) return output @_ni_docstrings.docfiller def generic_filter(input, function, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0, extra_arguments=(), extra_keywords=None): """Calculate a multidimensional filter using the given function. At each element the provided function is called. The input values within the filter footprint at that element are passed to the function as a 1-D array of double values. Parameters ---------- %(input)s function : {callable, scipy.LowLevelCallable} Function to apply at each element. %(size_foot)s %(output)s %(mode)s %(cval)s %(origin_multiple)s %(extra_arguments)s %(extra_keywords)s Notes ----- This function also accepts low-level callback functions with one of the following signatures and wrapped in `scipy.LowLevelCallable`: .. code:: c int callback(double *buffer, npy_intp filter_size, double *return_value, void *user_data) int callback(double *buffer, intptr_t filter_size, double *return_value, void *user_data) The calling function iterates over the elements of the input and output arrays, calling the callback function at each element. The elements within the footprint of the filter at the current element are passed through the ``buffer`` parameter, and the number of elements within the footprint through ``filter_size``. The calculated value is returned in ``return_value``. ``user_data`` is the data pointer provided to `scipy.LowLevelCallable` as-is. The callback function must return an integer error status that is zero if something went wrong and one otherwise. If an error occurs, you should normally set the python error status with an informative message before returning, otherwise a default error message is set by the calling function. In addition, some other low-level function pointer specifications are accepted, but these are for backward compatibility only and should not be used in new code. """ if (size is not None) and (footprint is not None): warnings.warn("ignoring size because footprint is set", UserWarning, stacklevel=2) if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') origins = _ni_support._normalize_sequence(origin, input.ndim) if footprint is None: if size is None: raise RuntimeError("no footprint or filter size provided") sizes = _ni_support._normalize_sequence(size, input.ndim) footprint = numpy.ones(sizes, dtype=bool) else: footprint = numpy.asarray(footprint, dtype=bool) fshape = [ii for ii in footprint.shape if ii > 0] if len(fshape) != input.ndim: raise RuntimeError('filter footprint array has incorrect shape.') for origin, lenf in zip(origins, fshape): if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): raise ValueError('invalid origin') if not footprint.flags.contiguous: footprint = footprint.copy() output = _ni_support._get_output(output, input) mode = _ni_support._extend_mode_to_code(mode) _nd_image.generic_filter(input, function, footprint, output, mode, cval, origins, extra_arguments, extra_keywords) return output
# this program corresponds to special.py ### Means test is not done yet # E Means test is giving error (E) # F Means test is failing (F) # EF Means test is giving error and Failing #! Means test is segfaulting # 8 Means test runs forever ### test_besselpoly ### test_mathieu_a ### test_mathieu_even_coef ### test_mathieu_odd_coef ### test_modfresnelp ### test_modfresnelm # test_pbdv_seq ### test_pbvv_seq ### test_sph_harm import itertools import platform import numpy as np from numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp, log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, float_) import pytest from pytest import raises as assert_raises from numpy.testing import (assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_approx_equal, assert_, assert_allclose, assert_array_almost_equal_nulp, suppress_warnings) from scipy import special import scipy.special._ufuncs as cephes from scipy.special import ellipk from scipy.special._testutils import with_special_errors, \ assert_func_equal, FuncData import math class TestCephes(object): def test_airy(self): cephes.airy(0) def test_airye(self): cephes.airye(0) def test_binom(self): n = np.array([0.264, 4, 5.2, 17]) k = np.array([2, 0.4, 7, 3.3]) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389, -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846], [10.92, 2.22993515861399, -0.00585728, 10.468891352063146], [136, 3.5252179590758828, 19448, 1024.5526916174495]]) assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13) # Test branches in implementation np.random.seed(1234) n = np.r_[np.arange(-7, 30), 1000*np.random.rand(30) - 500] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_2(self): # Test branches in implementation np.random.seed(1234) n = np.r_[np.logspace(1, 300, 20)] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_exact(self): @np.vectorize def binom_int(n, k): n = int(n) k = int(k) num = int(1) den = int(1) for i in range(1, k+1): num *= i + n - k den *= i return float(num/den) np.random.seed(1234) n = np.arange(1, 15) k = np.arange(0, 15) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T nk = nk[nk[:,0] >= nk[:,1]] assert_func_equal(cephes.binom, binom_int(nk[:,0], nk[:,1]), nk, atol=0, rtol=0) def test_binom_nooverflow_8346(self): # Test (binom(n, k) doesn't overflow prematurely */ dataset = [ (1000, 500, 2.70288240945436551e+299), (1002, 501, 1.08007396880791225e+300), (1004, 502, 4.31599279169058121e+300), (1006, 503, 1.72468101616263781e+301), (1008, 504, 6.89188009236419153e+301), (1010, 505, 2.75402257948335448e+302), (1012, 506, 1.10052048531923757e+303), (1014, 507, 4.39774063758732849e+303), (1016, 508, 1.75736486108312519e+304), (1018, 509, 7.02255427788423734e+304), (1020, 510, 2.80626776829962255e+305), (1022, 511, 1.12140876377061240e+306), (1024, 512, 4.48125455209897109e+306), (1026, 513, 1.79075474304149900e+307), (1028, 514, 7.15605105487789676e+307) ] dataset = np.asarray(dataset) FuncData(cephes.binom, dataset, (0, 1), 2, rtol=1e-12).check() def test_bdtr(self): assert_equal(cephes.bdtr(1,1,0.5),1.0) def test_bdtri(self): assert_equal(cephes.bdtri(1,3,0.5),0.5) def test_bdtrc(self): assert_equal(cephes.bdtrc(1,3,0.5),0.5) def test_bdtrin(self): assert_equal(cephes.bdtrin(1,0,1),5.0) def test_bdtrik(self): cephes.bdtrik(1,3,0.5) def test_bei(self): assert_equal(cephes.bei(0),0.0) def test_beip(self): assert_equal(cephes.beip(0),0.0) def test_ber(self): assert_equal(cephes.ber(0),1.0) def test_berp(self): assert_equal(cephes.berp(0),0.0) def test_besselpoly(self): assert_equal(cephes.besselpoly(0,0,0),1.0) def test_beta(self): assert_equal(cephes.beta(1,1),1.0) assert_allclose(cephes.beta(-100.3, 1e-200), cephes.gamma(1e-200)) assert_allclose(cephes.beta(0.0342, 171), 24.070498359873497, rtol=1e-13, atol=0) def test_betainc(self): assert_equal(cephes.betainc(1,1,1),1.0) assert_allclose(cephes.betainc(0.0342, 171, 1e-10), 0.55269916901806648) def test_betaln(self): assert_equal(cephes.betaln(1,1),0.0) assert_allclose(cephes.betaln(-100.3, 1e-200), cephes.gammaln(1e-200)) assert_allclose(cephes.betaln(0.0342, 170), 3.1811881124242447, rtol=1e-14, atol=0) def test_betaincinv(self): assert_equal(cephes.betaincinv(1,1,1),1.0) assert_allclose(cephes.betaincinv(0.0342, 171, 0.25), 8.4231316935498957e-21, rtol=3e-12, atol=0) def test_beta_inf(self): assert_(np.isinf(special.beta(-1, 2))) def test_btdtr(self): assert_equal(cephes.btdtr(1,1,1),1.0) def test_btdtri(self): assert_equal(cephes.btdtri(1,1,1),1.0) def test_btdtria(self): assert_equal(cephes.btdtria(1,1,1),5.0) def test_btdtrib(self): assert_equal(cephes.btdtrib(1,1,1),5.0) def test_cbrt(self): assert_approx_equal(cephes.cbrt(1),1.0) def test_chdtr(self): assert_equal(cephes.chdtr(1,0),0.0) def test_chdtrc(self): assert_equal(cephes.chdtrc(1,0),1.0) def test_chdtri(self): assert_equal(cephes.chdtri(1,1),0.0) def test_chdtriv(self): assert_equal(cephes.chdtriv(0,0),5.0) def test_chndtr(self): assert_equal(cephes.chndtr(0,1,0),0.0) # Each row holds (x, nu, lam, expected_value) # These values were computed using Wolfram Alpha with # CDF[NoncentralChiSquareDistribution[nu, lam], x] values = np.array([ [25.00, 20.0, 400, 4.1210655112396197139e-57], [25.00, 8.00, 250, 2.3988026526832425878e-29], [0.001, 8.00, 40., 5.3761806201366039084e-24], [0.010, 8.00, 40., 5.45396231055999457039e-20], [20.00, 2.00, 107, 1.39390743555819597802e-9], [22.50, 2.00, 107, 7.11803307138105870671e-9], [25.00, 2.00, 107, 3.11041244829864897313e-8], [3.000, 2.00, 1.0, 0.62064365321954362734], [350.0, 300., 10., 0.93880128006276407710], [100.0, 13.5, 10., 0.99999999650104210949], [700.0, 20.0, 400, 0.99999999925680650105], [150.0, 13.5, 10., 0.99999999999999983046], [160.0, 13.5, 10., 0.99999999999999999518], # 1.0 ]) cdf = cephes.chndtr(values[:, 0], values[:, 1], values[:, 2]) assert_allclose(cdf, values[:, 3], rtol=1e-12) assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0) assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0) assert_(np.isnan(cephes.chndtr(np.nan, 1, 2))) assert_(np.isnan(cephes.chndtr(5, np.nan, 2))) assert_(np.isnan(cephes.chndtr(5, 1, np.nan))) def test_chndtridf(self): assert_equal(cephes.chndtridf(0,0,1),5.0) def test_chndtrinc(self): assert_equal(cephes.chndtrinc(0,1,0),5.0) def test_chndtrix(self): assert_equal(cephes.chndtrix(0,1,0),0.0) def test_cosdg(self): assert_equal(cephes.cosdg(0),1.0) def test_cosm1(self): assert_equal(cephes.cosm1(0),0.0) def test_cotdg(self): assert_almost_equal(cephes.cotdg(45),1.0) def test_dawsn(self): assert_equal(cephes.dawsn(0),0.0) assert_allclose(cephes.dawsn(1.23), 0.50053727749081767) def test_diric(self): # Test behavior near multiples of 2pi. Regression test for issue # described in gh-4001. n_odd = [1, 5, 25] x = np.array(2*np.pi + 5e-5).astype(np.float32) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7) x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) x = np.array(2*np.pi + 1e-15).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) if hasattr(np, 'float128'): # No float128 available in 32-bit numpy x = np.array(2*np.pi + 1e-12).astype(np.float128) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19) n_even = [2, 4, 24] x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15) # Test at some values not near a multiple of pi x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi) octave_result = [0.872677996249965, 0.539344662916632, 0.127322003750035, -0.206011329583298] assert_almost_equal(special.diric(x, 3), octave_result, decimal=15) def test_diric_broadcasting(self): x = np.arange(5) n = np.array([1, 3, 7]) assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size)) def test_ellipe(self): assert_equal(cephes.ellipe(1),1.0) def test_ellipeinc(self): assert_equal(cephes.ellipeinc(0,1),0.0) def test_ellipj(self): cephes.ellipj(0,1) def test_ellipk(self): assert_allclose(ellipk(0), pi/2) def test_ellipkinc(self): assert_equal(cephes.ellipkinc(0,0),0.0) def test_erf(self): assert_equal(cephes.erf(0), 0.0) def test_erf_symmetry(self): x = 5.905732037710919 assert_equal(cephes.erf(x) + cephes.erf(-x), 0.0) def test_erfc(self): assert_equal(cephes.erfc(0), 1.0) def test_exp10(self): assert_approx_equal(cephes.exp10(2),100.0) def test_exp2(self): assert_equal(cephes.exp2(2),4.0) def test_expm1(self): assert_equal(cephes.expm1(0),0.0) assert_equal(cephes.expm1(np.inf), np.inf) assert_equal(cephes.expm1(-np.inf), -1) assert_equal(cephes.expm1(np.nan), np.nan) def test_expm1_complex(self): expm1 = cephes.expm1 assert_equal(expm1(0 + 0j), 0 + 0j) assert_equal(expm1(complex(np.inf, 0)), complex(np.inf, 0)) assert_equal(expm1(complex(np.inf, 1)), complex(np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 2)), complex(-np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 4)), complex(-np.inf, -np.inf)) assert_equal(expm1(complex(np.inf, 5)), complex(np.inf, -np.inf)) assert_equal(expm1(complex(1, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(0, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.inf, np.inf)), complex(np.inf, np.nan)) assert_equal(expm1(complex(-np.inf, np.inf)), complex(-1, 0)) assert_equal(expm1(complex(-np.inf, np.nan)), complex(-1, 0)) assert_equal(expm1(complex(np.inf, np.nan)), complex(np.inf, np.nan)) assert_equal(expm1(complex(0, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(1, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, 1)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, np.nan)), complex(np.nan, np.nan)) @pytest.mark.xfail(reason='The real part of expm1(z) bad at these points') def test_expm1_complex_hard(self): # The real part of this function is difficult to evaluate when # z.real = -log(cos(z.imag)). y = np.array([0.1, 0.2, 0.3, 5, 11, 20]) x = -np.log(np.cos(y)) z = x + 1j*y # evaluate using mpmath.expm1 with dps=1000 expected = np.array([-5.5507901846769623e-17+0.10033467208545054j, 2.4289354732893695e-18+0.20271003550867248j, 4.5235500262585768e-17+0.30933624960962319j, 7.8234305217489006e-17-3.3805150062465863j, -1.3685191953697676e-16-225.95084645419513j, 8.7175620481291045e-17+2.2371609442247422j]) found = cephes.expm1(z) # this passes. assert_array_almost_equal_nulp(found.imag, expected.imag, 3) # this fails. assert_array_almost_equal_nulp(found.real, expected.real, 20) def test_fdtr(self): assert_equal(cephes.fdtr(1, 1, 0), 0.0) # Computed using Wolfram Alpha: CDF[FRatioDistribution[1e-6, 5], 10] assert_allclose(cephes.fdtr(1e-6, 5, 10), 0.9999940790193488, rtol=1e-12) def test_fdtrc(self): assert_equal(cephes.fdtrc(1, 1, 0), 1.0) # Computed using Wolfram Alpha: # 1 - CDF[FRatioDistribution[2, 1/10], 1e10] assert_allclose(cephes.fdtrc(2, 0.1, 1e10), 0.27223784621293512, rtol=1e-12) def test_fdtri(self): assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]), array([0.9937365, 1.00630298]), rtol=1e-6) # From Wolfram Alpha: # CDF[FRatioDistribution[1/10, 1], 3] = 0.8756751669632105666874... p = 0.8756751669632105666874 assert_allclose(cephes.fdtri(0.1, 1, p), 3, rtol=1e-12) @pytest.mark.xfail(reason='Returns nan on i686.') def test_fdtri_mysterious_failure(self): assert_allclose(cephes.fdtri(1, 1, 0.5), 1) def test_fdtridfd(self): assert_equal(cephes.fdtridfd(1,0,0),5.0) def test_fresnel(self): assert_equal(cephes.fresnel(0),(0.0,0.0)) def test_gamma(self): assert_equal(cephes.gamma(5),24.0) def test_gammainccinv(self): assert_equal(cephes.gammainccinv(5,1),0.0) def test_gammaln(self): cephes.gammaln(10) def test_gammasgn(self): vals = np.array([-4, -3.5, -2.3, 1, 4.2], np.float64) assert_array_equal(cephes.gammasgn(vals), np.sign(cephes.rgamma(vals))) def test_gdtr(self): assert_equal(cephes.gdtr(1,1,0),0.0) def test_gdtr_inf(self): assert_equal(cephes.gdtr(1,1,np.inf),1.0) def test_gdtrc(self): assert_equal(cephes.gdtrc(1,1,0),1.0) def test_gdtria(self): assert_equal(cephes.gdtria(0,1,1),0.0) def test_gdtrib(self): cephes.gdtrib(1,0,1) # assert_equal(cephes.gdtrib(1,0,1),5.0) def test_gdtrix(self): cephes.gdtrix(1,1,.1) def test_hankel1(self): cephes.hankel1(1,1) def test_hankel1e(self): cephes.hankel1e(1,1) def test_hankel2(self): cephes.hankel2(1,1) def test_hankel2e(self): cephes.hankel2e(1,1) def test_hyp1f1(self): assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) cephes.hyp1f1(1,1,1) def test_hyp2f1(self): assert_equal(cephes.hyp2f1(1,1,1,0),1.0) def test_i0(self): assert_equal(cephes.i0(0),1.0) def test_i0e(self): assert_equal(cephes.i0e(0),1.0) def test_i1(self): assert_equal(cephes.i1(0),0.0) def test_i1e(self): assert_equal(cephes.i1e(0),0.0) def test_it2i0k0(self): cephes.it2i0k0(1) def test_it2j0y0(self): cephes.it2j0y0(1) def test_it2struve0(self): cephes.it2struve0(1) def test_itairy(self): cephes.itairy(1) def test_iti0k0(self): assert_equal(cephes.iti0k0(0),(0.0,0.0)) def test_itj0y0(self): assert_equal(cephes.itj0y0(0),(0.0,0.0)) def test_itmodstruve0(self): assert_equal(cephes.itmodstruve0(0),0.0) def test_itstruve0(self): assert_equal(cephes.itstruve0(0),0.0) def test_iv(self): assert_equal(cephes.iv(1,0),0.0) def _check_ive(self): assert_equal(cephes.ive(1,0),0.0) def test_j0(self): assert_equal(cephes.j0(0),1.0) def test_j1(self): assert_equal(cephes.j1(0),0.0) def test_jn(self): assert_equal(cephes.jn(0,0),1.0) def test_jv(self): assert_equal(cephes.jv(0,0),1.0) def _check_jve(self): assert_equal(cephes.jve(0,0),1.0) def test_k0(self): cephes.k0(2) def test_k0e(self): cephes.k0e(2) def test_k1(self): cephes.k1(2) def test_k1e(self): cephes.k1e(2) def test_kei(self): cephes.kei(2) def test_keip(self): assert_equal(cephes.keip(0),0.0) def test_ker(self): cephes.ker(2) def test_kerp(self): cephes.kerp(2) def _check_kelvin(self): cephes.kelvin(2) def test_kn(self): cephes.kn(1,1) def test_kolmogi(self): assert_equal(cephes.kolmogi(1),0.0) assert_(np.isnan(cephes.kolmogi(np.nan))) def test_kolmogorov(self): assert_equal(cephes.kolmogorov(0), 1.0) def test_kolmogp(self): assert_equal(cephes._kolmogp(0), -0.0) def test_kolmogc(self): assert_equal(cephes._kolmogc(0), 0.0) def test_kolmogci(self): assert_equal(cephes._kolmogci(0), 0.0) assert_(np.isnan(cephes._kolmogci(np.nan))) def _check_kv(self): cephes.kv(1,1) def _check_kve(self): cephes.kve(1,1) def test_log1p(self): log1p = cephes.log1p assert_equal(log1p(0), 0.0) assert_equal(log1p(-1), -np.inf) assert_equal(log1p(-2), np.nan) assert_equal(log1p(np.inf), np.inf) def test_log1p_complex(self): log1p = cephes.log1p c = complex assert_equal(log1p(0 + 0j), 0 + 0j) assert_equal(log1p(c(-1, 0)), c(-np.inf, 0)) with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in multiply") assert_allclose(log1p(c(1, np.inf)), c(np.inf, np.pi/2)) assert_equal(log1p(c(1, np.nan)), c(np.nan, np.nan)) assert_allclose(log1p(c(-np.inf, 1)), c(np.inf, np.pi)) assert_equal(log1p(c(np.inf, 1)), c(np.inf, 0)) assert_allclose(log1p(c(-np.inf, np.inf)), c(np.inf, 3*np.pi/4)) assert_allclose(log1p(c(np.inf, np.inf)), c(np.inf, np.pi/4)) assert_equal(log1p(c(np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(-np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, np.inf)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, 1)), c(np.nan, np.nan)) assert_equal(log1p(c(np.nan, np.nan)), c(np.nan, np.nan)) def test_lpmv(self): assert_equal(cephes.lpmv(0,0,1),1.0) def test_mathieu_a(self): assert_equal(cephes.mathieu_a(1,0),1.0) def test_mathieu_b(self): assert_equal(cephes.mathieu_b(1,0),1.0) def test_mathieu_cem(self): assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) # Test AMS 20.2.27 @np.vectorize def ce_smallq(m, q, z): z *= np.pi/180 if m == 0: return 2**(-0.5) * (1 - .5*q*cos(2*z)) # + O(q^2) elif m == 1: return cos(z) - q/8 * cos(3*z) # + O(q^2) elif m == 2: return cos(2*z) - q*(cos(4*z)/12 - 1/4) # + O(q^2) else: return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(0, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0], ce_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_sem(self): assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) # Test AMS 20.2.27 @np.vectorize def se_smallq(m, q, z): z *= np.pi/180 if m == 1: return sin(z) - q/8 * sin(3*z) # + O(q^2) elif m == 2: return sin(2*z) - q*sin(4*z)/12 # + O(q^2) else: return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(1, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0], se_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_modcem1(self): assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) def test_mathieu_modcem2(self): cephes.mathieu_modcem2(1,1,1) # Test reflection relation AMS 20.6.19 m = np.arange(0, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modcem2(m, q, -z)[0] fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0] y2 = -cephes.mathieu_modcem2(m, q, z)[0] - 2*fr*cephes.mathieu_modcem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_modsem1(self): assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) def test_mathieu_modsem2(self): cephes.mathieu_modsem2(1,1,1) # Test reflection relation AMS 20.6.20 m = np.arange(1, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modsem2(m, q, -z)[0] fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1] y2 = cephes.mathieu_modsem2(m, q, z)[0] - 2*fr*cephes.mathieu_modsem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_overflow(self): # Check that these return NaNs instead of causing a SEGV assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan)) def test_mathieu_ticket_1847(self): # Regression test --- this call had some out-of-bounds access # and could return nan occasionally for k in range(60): v = cephes.mathieu_modsem2(2, 100, -1) # Values from ACM TOMS 804 (derivate by numerical differentiation) assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10) assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4) def test_modfresnelm(self): cephes.modfresnelm(0) def test_modfresnelp(self): cephes.modfresnelp(0) def _check_modstruve(self): assert_equal(cephes.modstruve(1,0),0.0) def test_nbdtr(self): assert_equal(cephes.nbdtr(1,1,1),1.0) def test_nbdtrc(self): assert_equal(cephes.nbdtrc(1,1,1),0.0) def test_nbdtri(self): assert_equal(cephes.nbdtri(1,1,1),1.0) def __check_nbdtrik(self): cephes.nbdtrik(1,.4,.5) def test_nbdtrin(self): assert_equal(cephes.nbdtrin(1,0,0),5.0) def test_ncfdtr(self): assert_equal(cephes.ncfdtr(1,1,1,0),0.0) def test_ncfdtri(self): assert_equal(cephes.ncfdtri(1, 1, 1, 0), 0.0) f = [0.5, 1, 1.5] p = cephes.ncfdtr(2, 3, 1.5, f) assert_allclose(cephes.ncfdtri(2, 3, 1.5, p), f) def test_ncfdtridfd(self): dfd = [1, 2, 3] p = cephes.ncfdtr(2, dfd, 0.25, 15) assert_allclose(cephes.ncfdtridfd(2, p, 0.25, 15), dfd) def test_ncfdtridfn(self): dfn = [0.1, 1, 2, 3, 1e4] p = cephes.ncfdtr(dfn, 2, 0.25, 15) assert_allclose(cephes.ncfdtridfn(p, 2, 0.25, 15), dfn, rtol=1e-5) def test_ncfdtrinc(self): nc = [0.5, 1.5, 2.0] p = cephes.ncfdtr(2, 3, nc, 15) assert_allclose(cephes.ncfdtrinc(2, 3, p, 15), nc) def test_nctdtr(self): assert_equal(cephes.nctdtr(1,0,0),0.5) assert_equal(cephes.nctdtr(9, 65536, 45), 0.0) assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5) assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.))) assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.) assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.))) assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.))) assert_(np.isnan(cephes.nctdtr(2., 1., np.nan))) def __check_nctdtridf(self): cephes.nctdtridf(1,0.5,0) def test_nctdtrinc(self): cephes.nctdtrinc(1,0,0) def test_nctdtrit(self): cephes.nctdtrit(.1,0.2,.5) def test_nrdtrimn(self): assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) def test_nrdtrisd(self): assert_allclose(cephes.nrdtrisd(0.5,0.5,0.5), 0.0, atol=0, rtol=0) def test_obl_ang1(self): cephes.obl_ang1(1,1,1,0) def test_obl_ang1_cv(self): result = cephes.obl_ang1_cv(1,1,1,1,0) assert_almost_equal(result[0],1.0) assert_almost_equal(result[1],0.0) def _check_obl_cv(self): assert_equal(cephes.obl_cv(1,1,0),2.0) def test_obl_rad1(self): cephes.obl_rad1(1,1,1,0) def test_obl_rad1_cv(self): cephes.obl_rad1_cv(1,1,1,1,0) def test_obl_rad2(self): cephes.obl_rad2(1,1,1,0) def test_obl_rad2_cv(self): cephes.obl_rad2_cv(1,1,1,1,0) def test_pbdv(self): assert_equal(cephes.pbdv(1,0),(0.0,1.0)) def test_pbvv(self): cephes.pbvv(1,0) def test_pbwa(self): cephes.pbwa(1,0) def test_pdtr(self): val = cephes.pdtr(0, 1) assert_almost_equal(val, np.exp(-1)) # Edge case: m = 0. val = cephes.pdtr([0, 1, 2], 0) assert_array_equal(val, [1, 1, 1]) def test_pdtrc(self): val = cephes.pdtrc(0, 1) assert_almost_equal(val, 1 - np.exp(-1)) # Edge case: m = 0. val = cephes.pdtrc([0, 1, 2], 0.0) assert_array_equal(val, [0, 0, 0]) def test_pdtri(self): with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") cephes.pdtri(0.5,0.5) def test_pdtrik(self): k = cephes.pdtrik(0.5, 1) assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5) # Edge case: m = 0 or very small. k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6]) assert_array_equal(k, np.zeros((3, 3))) def test_pro_ang1(self): cephes.pro_ang1(1,1,1,0) def test_pro_ang1_cv(self): assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), array((1.0,0.0))) def _check_pro_cv(self): assert_equal(cephes.pro_cv(1,1,0),2.0) def test_pro_rad1(self): cephes.pro_rad1(1,1,1,0.1) def test_pro_rad1_cv(self): cephes.pro_rad1_cv(1,1,1,1,0) def test_pro_rad2(self): cephes.pro_rad2(1,1,1,0) def test_pro_rad2_cv(self): cephes.pro_rad2_cv(1,1,1,1,0) def test_psi(self): cephes.psi(1) def test_radian(self): assert_equal(cephes.radian(0,0,0),0) def test_rgamma(self): assert_equal(cephes.rgamma(1),1.0) def test_round(self): assert_equal(cephes.round(3.4),3.0) assert_equal(cephes.round(-3.4),-3.0) assert_equal(cephes.round(3.6),4.0) assert_equal(cephes.round(-3.6),-4.0) assert_equal(cephes.round(3.5),4.0) assert_equal(cephes.round(-3.5),-4.0) def test_shichi(self): cephes.shichi(1) def test_sici(self): cephes.sici(1) s, c = cephes.sici(np.inf) assert_almost_equal(s, np.pi * 0.5) assert_almost_equal(c, 0) s, c = cephes.sici(-np.inf) assert_almost_equal(s, -np.pi * 0.5) assert_(np.isnan(c), "cosine integral(-inf) is not nan") def test_sindg(self): assert_equal(cephes.sindg(90),1.0) def test_smirnov(self): assert_equal(cephes.smirnov(1,.1),0.9) assert_(np.isnan(cephes.smirnov(1,np.nan))) def test_smirnovp(self): assert_equal(cephes._smirnovp(1, .1), -1) assert_equal(cephes._smirnovp(2, 0.75), -2*(0.25)**(2-1)) assert_equal(cephes._smirnovp(3, 0.75), -3*(0.25)**(3-1)) assert_(np.isnan(cephes._smirnovp(1, np.nan))) def test_smirnovc(self): assert_equal(cephes._smirnovc(1,.1),0.1) assert_(np.isnan(cephes._smirnovc(1,np.nan))) x10 = np.linspace(0, 1, 11, endpoint=True) assert_almost_equal(cephes._smirnovc(3, x10), 1-cephes.smirnov(3, x10)) x4 = np.linspace(0, 1, 5, endpoint=True) assert_almost_equal(cephes._smirnovc(4, x4), 1-cephes.smirnov(4, x4)) def test_smirnovi(self): assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) assert_(np.isnan(cephes.smirnovi(1,np.nan))) def test_smirnovci(self): assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.4)),0.4) assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.6)),0.6) assert_(np.isnan(cephes._smirnovci(1,np.nan))) def test_spence(self): assert_equal(cephes.spence(1),0.0) def test_stdtr(self): assert_equal(cephes.stdtr(1,0),0.5) assert_almost_equal(cephes.stdtr(1,1), 0.75) assert_almost_equal(cephes.stdtr(1,2), 0.852416382349) def test_stdtridf(self): cephes.stdtridf(0.7,1) def test_stdtrit(self): cephes.stdtrit(1,0.7) def test_struve(self): assert_equal(cephes.struve(0,0),0.0) def test_tandg(self): assert_equal(cephes.tandg(45),1.0) def test_tklmbda(self): assert_almost_equal(cephes.tklmbda(1,1),1.0) def test_y0(self): cephes.y0(1) def test_y1(self): cephes.y1(1) def test_yn(self): cephes.yn(1,1) def test_yv(self): cephes.yv(1,1) def _check_yve(self): cephes.yve(1,1) def test_wofz(self): z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.), complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.), complex(-0.0000000234545,1.1234), complex(-3.,5.1), complex(-53,30.1), complex(0.0,0.12345), complex(11,1), complex(-22,-2), complex(9,-28), complex(21,-33), complex(1e5,1e5), complex(1e14,1e14) ] w = [ complex(-3.78270245518980507452677445620103199303131110e-7, 0.000903861276433172057331093754199933411710053155), complex(0.1764906227004816847297495349730234591778719532788, -0.02146550539468457616788719893991501311573031095617), complex(0.2410250715772692146133539023007113781272362309451, 0.06087579663428089745895459735240964093522265589350), complex(0.30474420525691259245713884106959496013413834051768, -0.20821893820283162728743734725471561394145872072738), complex(7.317131068972378096865595229600561710140617977e34, 8.321873499714402777186848353320412813066170427e34), complex(0.0615698507236323685519612934241429530190806818395, -0.00676005783716575013073036218018565206070072304635), complex(0.3960793007699874918961319170187598400134746631, -5.593152259116644920546186222529802777409274656e-9), complex(0.08217199226739447943295069917990417630675021771804, -0.04701291087643609891018366143118110965272615832184), complex(0.00457246000350281640952328010227885008541748668738, -0.00804900791411691821818731763401840373998654987934), complex(0.8746342859608052666092782112565360755791467973338452, 0.), complex(0.00468190164965444174367477874864366058339647648741, 0.0510735563901306197993676329845149741675029197050), complex(-0.0023193175200187620902125853834909543869428763219, -0.025460054739731556004902057663500272721780776336), complex(9.11463368405637174660562096516414499772662584e304, 3.97101807145263333769664875189354358563218932e305), complex(-4.4927207857715598976165541011143706155432296e281, -2.8019591213423077494444700357168707775769028e281), complex(2.820947917809305132678577516325951485807107151e-6, 2.820947917668257736791638444590253942253354058e-6), complex(2.82094791773878143474039725787438662716372268e-15, 2.82094791773878143474039725773333923127678361e-15) ] assert_func_equal(cephes.wofz, w, z, rtol=1e-13) class TestAiry(object): def test_airy(self): # This tests the airy function to ensure 8 place accuracy in computation x = special.airy(.99) assert_array_almost_equal(x,array([0.13689066,-0.16050153,1.19815925,0.92046818]),8) x = special.airy(.41) assert_array_almost_equal(x,array([0.25238916,-.23480512,0.80686202,0.51053919]),8) x = special.airy(-.36) assert_array_almost_equal(x,array([0.44508477,-0.23186773,0.44939534,0.48105354]),8) def test_airye(self): a = special.airye(0.01) b = special.airy(0.01) b1 = [None]*4 for n in range(2): b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01)) for n in range(2,4): b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) assert_array_almost_equal(a,b1,6) def test_bi_zeros(self): bi = special.bi_zeros(2) bia = (array([-1.17371322, -3.2710930]), array([-2.29443968, -4.07315509]), array([-0.45494438, 0.39652284]), array([0.60195789, -0.76031014])) assert_array_almost_equal(bi,bia,4) bi = special.bi_zeros(5) assert_array_almost_equal(bi[0],array([-1.173713222709127, -3.271093302836352, -4.830737841662016, -6.169852128310251, -7.376762079367764]),11) assert_array_almost_equal(bi[1],array([-2.294439682614122, -4.073155089071828, -5.512395729663599, -6.781294445990305, -7.940178689168587]),10) assert_array_almost_equal(bi[2],array([-0.454944383639657, 0.396522836094465, -0.367969161486959, 0.349499116831805, -0.336026240133662]),11) assert_array_almost_equal(bi[3],array([0.601957887976239, -0.760310141492801, 0.836991012619261, -0.88947990142654, 0.929983638568022]),10) def test_ai_zeros(self): ai = special.ai_zeros(1) assert_array_almost_equal(ai,(array([-2.33810741]), array([-1.01879297]), array([0.5357]), array([0.7012])),4) def test_ai_zeros_big(self): z, zp, ai_zpx, aip_zx = special.ai_zeros(50000) ai_z, aip_z, _, _ = special.airy(z) ai_zp, aip_zp, _, _ = special.airy(zp) ai_envelope = 1/abs(z)**(1./4) aip_envelope = abs(zp)**(1./4) # Check values assert_allclose(ai_zpx, ai_zp, rtol=1e-10) assert_allclose(aip_zx, aip_z, rtol=1e-10) # Check they are zeros assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0) assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.1 assert_allclose(z[:6], [-2.3381074105, -4.0879494441, -5.5205598281, -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10) assert_allclose(zp[:6], [-1.0187929716, -3.2481975822, -4.8200992112, -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10) def test_bi_zeros_big(self): z, zp, bi_zpx, bip_zx = special.bi_zeros(50000) _, _, bi_z, bip_z = special.airy(z) _, _, bi_zp, bip_zp = special.airy(zp) bi_envelope = 1/abs(z)**(1./4) bip_envelope = abs(zp)**(1./4) # Check values assert_allclose(bi_zpx, bi_zp, rtol=1e-10) assert_allclose(bip_zx, bip_z, rtol=1e-10) # Check they are zeros assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0) assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.2 assert_allclose(z[:6], [-1.1737132227, -3.2710933028, -4.8307378417, -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10) assert_allclose(zp[:6], [-2.2944396826, -4.0731550891, -5.5123957297, -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10) class TestAssocLaguerre(object): def test_assoc_laguerre(self): a1 = special.genlaguerre(11,1) a2 = special.assoc_laguerre(.2,11,1) assert_array_almost_equal(a2,a1(.2),8) a2 = special.assoc_laguerre(1,11,1) assert_array_almost_equal(a2,a1(1),8) class TestBesselpoly(object): def test_besselpoly(self): pass class TestKelvin(object): def test_bei(self): mbei = special.bei(2) assert_almost_equal(mbei, 0.9722916273066613,5) # this may not be exact def test_beip(self): mbeip = special.beip(2) assert_almost_equal(mbeip,0.91701361338403631,5) # this may not be exact def test_ber(self): mber = special.ber(2) assert_almost_equal(mber,0.75173418271380821,5) # this may not be exact def test_berp(self): mberp = special.berp(2) assert_almost_equal(mberp,-0.49306712470943909,5) # this may not be exact def test_bei_zeros(self): # Abramowitz & Stegun, Table 9.12 bi = special.bei_zeros(5) assert_array_almost_equal(bi,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) def test_beip_zeros(self): bip = special.beip_zeros(5) assert_array_almost_equal(bip,array([3.772673304934953, 8.280987849760042, 12.742147523633703, 17.193431752512542, 21.641143941167325]),8) def test_ber_zeros(self): ber = special.ber_zeros(5) assert_array_almost_equal(ber,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) def test_berp_zeros(self): brp = special.berp_zeros(5) assert_array_almost_equal(brp,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) def test_kelvin(self): mkelv = special.kelvin(2) assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j, special.ker(2) + special.kei(2)*1j, special.berp(2) + special.beip(2)*1j, special.kerp(2) + special.keip(2)*1j),8) def test_kei(self): mkei = special.kei(2) assert_almost_equal(mkei,-0.20240006776470432,5) def test_keip(self): mkeip = special.keip(2) assert_almost_equal(mkeip,0.21980790991960536,5) def test_ker(self): mker = special.ker(2) assert_almost_equal(mker,-0.041664513991509472,5) def test_kerp(self): mkerp = special.kerp(2) assert_almost_equal(mkerp,-0.10660096588105264,5) def test_kei_zeros(self): kei = special.kei_zeros(5) assert_array_almost_equal(kei,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) def test_keip_zeros(self): keip = special.keip_zeros(5) assert_array_almost_equal(keip,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) # numbers come from 9.9 of A&S pg. 381 def test_kelvin_zeros(self): tmp = special.kelvin_zeros(5) berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp assert_array_almost_equal(berz,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) assert_array_almost_equal(beiz,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) assert_array_almost_equal(kerz,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44382]),4) assert_array_almost_equal(keiz,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) assert_array_almost_equal(berpz,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) assert_array_almost_equal(beipz,array([3.77267, # table from 1927 had 3.77320 # but this is more accurate 8.28099, 12.74215, 17.19343, 21.64114]),4) assert_array_almost_equal(kerpz,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) assert_array_almost_equal(keipz,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) def test_ker_zeros(self): ker = special.ker_zeros(5) assert_array_almost_equal(ker,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44381]),4) def test_kerp_zeros(self): kerp = special.kerp_zeros(5) assert_array_almost_equal(kerp,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) class TestBernoulli(object): def test_bernoulli(self): brn = special.bernoulli(5) assert_array_almost_equal(brn,array([1.0000, -0.5000, 0.1667, 0.0000, -0.0333, 0.0000]),4) class TestBeta(object): def test_beta(self): bet = special.beta(2,4) betg = (special.gamma(2)*special.gamma(4))/special.gamma(6) assert_almost_equal(bet,betg,8) def test_betaln(self): betln = special.betaln(2,4) bet = log(abs(special.beta(2,4))) assert_almost_equal(betln,bet,8) def test_betainc(self): btinc = special.betainc(1,1,.2) assert_almost_equal(btinc,0.2,8) def test_betaincinv(self): y = special.betaincinv(2,4,.5) comp = special.betainc(2,4,y) assert_almost_equal(comp,.5,5) class TestCombinatorics(object): def test_comb(self): assert_array_almost_equal(special.comb([10, 10], [3, 4]), [120., 210.]) assert_almost_equal(special.comb(10, 3), 120.) assert_equal(special.comb(10, 3, exact=True), 120) assert_equal(special.comb(10, 3, exact=True, repetition=True), 220) assert_allclose([special.comb(20, k, exact=True) for k in range(21)], special.comb(20, list(range(21))), atol=1e-15) ii = np.iinfo(int).max + 1 assert_equal(special.comb(ii, ii-1, exact=True), ii) expected = 100891344545564193334812497256 assert_equal(special.comb(100, 50, exact=True), expected) def test_comb_with_np_int64(self): n = 70 k = 30 np_n = np.int64(n) np_k = np.int64(k) assert_equal(special.comb(np_n, np_k, exact=True), special.comb(n, k, exact=True)) def test_comb_zeros(self): assert_equal(special.comb(2, 3, exact=True), 0) assert_equal(special.comb(-1, 3, exact=True), 0) assert_equal(special.comb(2, -1, exact=True), 0) assert_equal(special.comb(2, -1, exact=False), 0) assert_array_almost_equal(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 120.]) def test_perm(self): assert_array_almost_equal(special.perm([10, 10], [3, 4]), [720., 5040.]) assert_almost_equal(special.perm(10, 3), 720.) assert_equal(special.perm(10, 3, exact=True), 720) def test_perm_zeros(self): assert_equal(special.perm(2, 3, exact=True), 0) assert_equal(special.perm(-1, 3, exact=True), 0) assert_equal(special.perm(2, -1, exact=True), 0) assert_equal(special.perm(2, -1, exact=False), 0) assert_array_almost_equal(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 720.]) class TestTrigonometric(object): def test_cbrt(self): cb = special.cbrt(27) cbrl = 27**(1.0/3.0) assert_approx_equal(cb,cbrl) def test_cbrtmore(self): cb1 = special.cbrt(27.9) cbrl1 = 27.9**(1.0/3.0) assert_almost_equal(cb1,cbrl1,8) def test_cosdg(self): cdg = special.cosdg(90) cdgrl = cos(pi/2.0) assert_almost_equal(cdg,cdgrl,8) def test_cosdgmore(self): cdgm = special.cosdg(30) cdgmrl = cos(pi/6.0) assert_almost_equal(cdgm,cdgmrl,8) def test_cosm1(self): cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10)) csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) assert_array_almost_equal(cs,csrl,8) def test_cotdg(self): ct = special.cotdg(30) ctrl = tan(pi/6.0)**(-1) assert_almost_equal(ct,ctrl,8) def test_cotdgmore(self): ct1 = special.cotdg(45) ctrl1 = tan(pi/4.0)**(-1) assert_almost_equal(ct1,ctrl1,8) def test_specialpoints(self): assert_almost_equal(special.cotdg(45), 1.0, 14) assert_almost_equal(special.cotdg(-45), -1.0, 14) assert_almost_equal(special.cotdg(90), 0.0, 14) assert_almost_equal(special.cotdg(-90), 0.0, 14) assert_almost_equal(special.cotdg(135), -1.0, 14) assert_almost_equal(special.cotdg(-135), 1.0, 14) assert_almost_equal(special.cotdg(225), 1.0, 14) assert_almost_equal(special.cotdg(-225), -1.0, 14) assert_almost_equal(special.cotdg(270), 0.0, 14) assert_almost_equal(special.cotdg(-270), 0.0, 14) assert_almost_equal(special.cotdg(315), -1.0, 14) assert_almost_equal(special.cotdg(-315), 1.0, 14) assert_almost_equal(special.cotdg(765), 1.0, 14) def test_sinc(self): # the sinc implementation and more extensive sinc tests are in numpy assert_array_equal(special.sinc([0]), 1) assert_equal(special.sinc(0.0), 1.0) def test_sindg(self): sn = special.sindg(90) assert_equal(sn,1.0) def test_sindgmore(self): snm = special.sindg(30) snmrl = sin(pi/6.0) assert_almost_equal(snm,snmrl,8) snm1 = special.sindg(45) snmrl1 = sin(pi/4.0) assert_almost_equal(snm1,snmrl1,8) class TestTandg(object): def test_tandg(self): tn = special.tandg(30) tnrl = tan(pi/6.0) assert_almost_equal(tn,tnrl,8) def test_tandgmore(self): tnm = special.tandg(45) tnmrl = tan(pi/4.0) assert_almost_equal(tnm,tnmrl,8) tnm1 = special.tandg(60) tnmrl1 = tan(pi/3.0) assert_almost_equal(tnm1,tnmrl1,8) def test_specialpoints(self): assert_almost_equal(special.tandg(0), 0.0, 14) assert_almost_equal(special.tandg(45), 1.0, 14) assert_almost_equal(special.tandg(-45), -1.0, 14) assert_almost_equal(special.tandg(135), -1.0, 14) assert_almost_equal(special.tandg(-135), 1.0, 14) assert_almost_equal(special.tandg(180), 0.0, 14) assert_almost_equal(special.tandg(-180), 0.0, 14) assert_almost_equal(special.tandg(225), 1.0, 14) assert_almost_equal(special.tandg(-225), -1.0, 14) assert_almost_equal(special.tandg(315), -1.0, 14) assert_almost_equal(special.tandg(-315), 1.0, 14) class TestEllip(object): def test_ellipj_nan(self): """Regression test for #912.""" special.ellipj(0.5, np.nan) def test_ellipj(self): el = special.ellipj(0.2,0) rel = [sin(0.2),cos(0.2),1.0,0.20] assert_array_almost_equal(el,rel,13) def test_ellipk(self): elk = special.ellipk(.2) assert_almost_equal(elk,1.659623598610528,11) assert_equal(special.ellipkm1(0.0), np.inf) assert_equal(special.ellipkm1(1.0), pi/2) assert_equal(special.ellipkm1(np.inf), 0.0) assert_equal(special.ellipkm1(np.nan), np.nan) assert_equal(special.ellipkm1(-1), np.nan) assert_allclose(special.ellipk(-10), 0.7908718902387385) def test_ellipkinc(self): elkinc = special.ellipkinc(pi/2,.2) elk = special.ellipk(0.2) assert_almost_equal(elkinc,elk,15) alpha = 20*pi/180 phi = 45*pi/180 m = sin(alpha)**2 elkinc = special.ellipkinc(phi,m) assert_almost_equal(elkinc,0.79398143,8) # From pg. 614 of A & S assert_equal(special.ellipkinc(pi/2, 0.0), pi/2) assert_equal(special.ellipkinc(pi/2, 1.0), np.inf) assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0) assert_equal(special.ellipkinc(pi/2, np.nan), np.nan) assert_equal(special.ellipkinc(pi/2, 2), np.nan) assert_equal(special.ellipkinc(0, 0.5), 0.0) assert_equal(special.ellipkinc(np.inf, 0.5), np.inf) assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipkinc(np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.nan, 0.5), np.nan) assert_equal(special.ellipkinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14) assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946) def test_ellipkinc_2(self): # Regression test for gh-3550 # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipkinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 1.0259330100195334), 1) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipkinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 5.1296650500976675), 2) def test_ellipkinc_singular(self): # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2) xlog = np.logspace(-300, -17, 25) xlin = np.linspace(1e-17, 0.1, 25) xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False) assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)), rtol=1e14) assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)), rtol=1e14) assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)), rtol=1e14) assert_equal(special.ellipkinc(np.pi/2, 1), np.inf) assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)), rtol=1e14) assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf) def test_ellipe(self): ele = special.ellipe(.2) assert_almost_equal(ele,1.4890350580958529,8) assert_equal(special.ellipe(0.0), pi/2) assert_equal(special.ellipe(1.0), 1.0) assert_equal(special.ellipe(-np.inf), np.inf) assert_equal(special.ellipe(np.nan), np.nan) assert_equal(special.ellipe(2), np.nan) assert_allclose(special.ellipe(-10), 3.6391380384177689) def test_ellipeinc(self): eleinc = special.ellipeinc(pi/2,.2) ele = special.ellipe(0.2) assert_almost_equal(eleinc,ele,14) # pg 617 of A & S alpha, phi = 52*pi/180,35*pi/180 m = sin(alpha)**2 eleinc = special.ellipeinc(phi,m) assert_almost_equal(eleinc, 0.58823065, 8) assert_equal(special.ellipeinc(pi/2, 0.0), pi/2) assert_equal(special.ellipeinc(pi/2, 1.0), 1.0) assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf) assert_equal(special.ellipeinc(pi/2, np.nan), np.nan) assert_equal(special.ellipeinc(pi/2, 2), np.nan) assert_equal(special.ellipeinc(0, 0.5), 0.0) assert_equal(special.ellipeinc(np.inf, 0.5), np.inf) assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf) assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf) assert_equal(special.ellipeinc(np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(np.nan, 0.5), np.nan) assert_equal(special.ellipeinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876) def test_ellipeinc_2(self): # Regression test for gh-3550 # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipeinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 0.84442884574781019), 2) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipeinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 3.3471442287390509), 4) class TestErf(object): def test_erf(self): er = special.erf(.25) assert_almost_equal(er,0.2763263902,8) def test_erf_zeros(self): erz = special.erf_zeros(5) erzr = array([1.45061616+1.88094300j, 2.24465928+2.61657514j, 2.83974105+3.17562810j, 3.33546074+3.64617438j, 3.76900557+4.06069723j]) assert_array_almost_equal(erz,erzr,4) def _check_variant_func(self, func, other_func, rtol, atol=0): np.random.seed(1234) n = 10000 x = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) y = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) z = x + 1j*y old_errors = np.seterr(all='ignore') try: w = other_func(z) w_real = other_func(x).real mask = np.isfinite(w) w = w[mask] z = z[mask] mask = np.isfinite(w_real) w_real = w_real[mask] x = x[mask] # test both real and complex variants assert_func_equal(func, w, z, rtol=rtol, atol=atol) assert_func_equal(func, w_real, x, rtol=rtol, atol=atol) finally: np.seterr(**old_errors) def test_erfc_consistent(self): self._check_variant_func( cephes.erfc, lambda z: 1 - cephes.erf(z), rtol=1e-12, atol=1e-14 # <- the test function loses precision ) def test_erfcx_consistent(self): self._check_variant_func( cephes.erfcx, lambda z: np.exp(z*z) * cephes.erfc(z), rtol=1e-12 ) def test_erfi_consistent(self): self._check_variant_func( cephes.erfi, lambda z: -1j * cephes.erf(1j*z), rtol=1e-12 ) def test_dawsn_consistent(self): self._check_variant_func( cephes.dawsn, lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z), rtol=1e-12 ) def test_erf_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -1, 1] assert_allclose(special.erf(vals), expected, rtol=1e-15) def test_erfc_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, 2, 0] assert_allclose(special.erfc(vals), expected, rtol=1e-15) def test_erfcx_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, np.inf, 0] assert_allclose(special.erfcx(vals), expected, rtol=1e-15) def test_erfi_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -np.inf, np.inf] assert_allclose(special.erfi(vals), expected, rtol=1e-15) def test_dawsn_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -0.0, 0.0] assert_allclose(special.dawsn(vals), expected, rtol=1e-15) def test_wofz_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan + np.nan * 1.j, 0.-0.j, 0.+0.j] assert_allclose(special.wofz(vals), expected, rtol=1e-15) class TestEuler(object): def test_euler(self): eu0 = special.euler(0) eu1 = special.euler(1) eu2 = special.euler(2) # just checking segfaults assert_allclose(eu0, [1], rtol=1e-15) assert_allclose(eu1, [1, 0], rtol=1e-15) assert_allclose(eu2, [1, 0, -1], rtol=1e-15) eu24 = special.euler(24) mathworld = [1,1,5,61,1385,50521,2702765,199360981, 19391512145,2404879675441, 370371188237525,69348874393137901, 15514534163557086905] correct = zeros((25,),'d') for k in range(0,13): if (k % 2): correct[2*k] = -float(mathworld[k]) else: correct[2*k] = float(mathworld[k]) olderr = np.seterr(all='ignore') try: err = nan_to_num((eu24-correct)/correct) errmax = max(err) finally: np.seterr(**olderr) assert_almost_equal(errmax, 0.0, 14) class TestExp(object): def test_exp2(self): ex = special.exp2(2) exrl = 2**2 assert_equal(ex,exrl) def test_exp2more(self): exm = special.exp2(2.5) exmrl = 2**(2.5) assert_almost_equal(exm,exmrl,8) def test_exp10(self): ex = special.exp10(2) exrl = 10**2 assert_approx_equal(ex,exrl) def test_exp10more(self): exm = special.exp10(2.5) exmrl = 10**(2.5) assert_almost_equal(exm,exmrl,8) def test_expm1(self): ex = (special.expm1(2),special.expm1(3),special.expm1(4)) exrl = (exp(2)-1,exp(3)-1,exp(4)-1) assert_array_almost_equal(ex,exrl,8) def test_expm1more(self): ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2)) exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) assert_array_almost_equal(ex1,exrl1,8) class TestFactorialFunctions(object): def test_factorial(self): # Some known values, float math assert_array_almost_equal(special.factorial(0), 1) assert_array_almost_equal(special.factorial(1), 1) assert_array_almost_equal(special.factorial(2), 2) assert_array_almost_equal([6., 24., 120.], special.factorial([3, 4, 5], exact=False)) assert_array_almost_equal(special.factorial([[5, 3], [4, 3]]), [[120, 6], [24, 6]]) # Some known values, integer math assert_equal(special.factorial(0, exact=True), 1) assert_equal(special.factorial(1, exact=True), 1) assert_equal(special.factorial(2, exact=True), 2) assert_equal(special.factorial(5, exact=True), 120) assert_equal(special.factorial(15, exact=True), 1307674368000) # ndarray shape is maintained assert_equal(special.factorial([7, 4, 15, 10], exact=True), [5040, 24, 1307674368000, 3628800]) assert_equal(special.factorial([[5, 3], [4, 3]], True), [[120, 6], [24, 6]]) # object arrays assert_equal(special.factorial(np.arange(-3, 22), True), special.factorial(np.arange(-3, 22), False)) # int64 array assert_equal(special.factorial(np.arange(-3, 15), True), special.factorial(np.arange(-3, 15), False)) # int32 array assert_equal(special.factorial(np.arange(-3, 5), True), special.factorial(np.arange(-3, 5), False)) # Consistent output for n < 0 for exact in (True, False): assert_array_equal(0, special.factorial(-3, exact)) assert_array_equal([1, 2, 0, 0], special.factorial([1, 2, -5, -4], exact)) for n in range(0, 22): # Compare all with math.factorial correct = math.factorial(n) assert_array_equal(correct, special.factorial(n, True)) assert_array_equal(correct, special.factorial([n], True)[0]) assert_allclose(float(correct), special.factorial(n, False)) assert_allclose(float(correct), special.factorial([n], False)[0]) # Compare exact=True vs False, scalar vs array assert_array_equal(special.factorial(n, True), special.factorial(n, False)) assert_array_equal(special.factorial([n], True), special.factorial([n], False)) @pytest.mark.parametrize('x, exact', [ (1, True), (1, False), (np.array(1), True), (np.array(1), False), ]) def test_factorial_0d_return_type(self, x, exact): assert np.isscalar(special.factorial(x, exact=exact)) def test_factorial2(self): assert_array_almost_equal([105., 384., 945.], special.factorial2([7, 8, 9], exact=False)) assert_equal(special.factorial2(7, exact=True), 105) def test_factorialk(self): assert_equal(special.factorialk(5, 1, exact=True), 120) assert_equal(special.factorialk(5, 3, exact=True), 10) @pytest.mark.parametrize('x, exact', [ (np.nan, True), (np.nan, False), (np.array([np.nan]), True), (np.array([np.nan]), False), ]) def test_nan_inputs(self, x, exact): result = special.factorial(x, exact=exact) assert_(np.isnan(result)) def test_mixed_nan_inputs(self): x = np.array([np.nan, 1, 2, 3, np.nan]) result = special.factorial(x, exact=True) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) result = special.factorial(x, exact=False) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) class TestFresnel(object): def test_fresnel(self): frs = array(special.fresnel(.5)) assert_array_almost_equal(frs,array([0.064732432859999287, 0.49234422587144644]),8) def test_fresnel_inf1(self): frs = special.fresnel(np.inf) assert_equal(frs, (0.5, 0.5)) def test_fresnel_inf2(self): frs = special.fresnel(-np.inf) assert_equal(frs, (-0.5, -0.5)) # values from pg 329 Table 7.11 of A & S # slightly corrected in 4th decimal place def test_fresnel_zeros(self): szo, czo = special.fresnel_zeros(5) assert_array_almost_equal(szo, array([2.0093+0.2885j, 2.8335+0.2443j, 3.4675+0.2185j, 4.0026+0.2009j, 4.4742+0.1877j]),3) assert_array_almost_equal(czo, array([1.7437+0.3057j, 2.6515+0.2529j, 3.3204+0.2240j, 3.8757+0.2047j, 4.3611+0.1907j]),3) vals1 = special.fresnel(szo)[0] vals2 = special.fresnel(czo)[1] assert_array_almost_equal(vals1,0,14) assert_array_almost_equal(vals2,0,14) def test_fresnelc_zeros(self): szo, czo = special.fresnel_zeros(6) frc = special.fresnelc_zeros(6) assert_array_almost_equal(frc,czo,12) def test_fresnels_zeros(self): szo, czo = special.fresnel_zeros(5) frs = special.fresnels_zeros(5) assert_array_almost_equal(frs,szo,12) class TestGamma(object): def test_gamma(self): gam = special.gamma(5) assert_equal(gam,24.0) def test_gammaln(self): gamln = special.gammaln(3) lngam = log(special.gamma(3)) assert_almost_equal(gamln,lngam,8) def test_gammainccinv(self): gccinv = special.gammainccinv(.5,.5) gcinv = special.gammaincinv(.5,.5) assert_almost_equal(gccinv,gcinv,8) @with_special_errors def test_gammaincinv(self): y = special.gammaincinv(.4,.4) x = special.gammainc(.4,y) assert_almost_equal(x,0.4,1) y = special.gammainc(10, 0.05) x = special.gammaincinv(10, 2.5715803516000736e-20) assert_almost_equal(0.05, x, decimal=10) assert_almost_equal(y, 2.5715803516000736e-20, decimal=10) x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18) assert_almost_equal(11.0, x, decimal=10) @with_special_errors def test_975(self): # Regression test for ticket #975 -- switch point in algorithm # check that things work OK at the point, immediately next floats # around it, and a bit further away pts = [0.25, np.nextafter(0.25, 0), 0.25 - 1e-12, np.nextafter(0.25, 1), 0.25 + 1e-12] for xp in pts: y = special.gammaincinv(.4, xp) x = special.gammainc(0.4, y) assert_allclose(x, xp, rtol=1e-12) def test_rgamma(self): rgam = special.rgamma(8) rlgam = 1/special.gamma(8) assert_almost_equal(rgam,rlgam,8) def test_infinity(self): assert_(np.isinf(special.gamma(-1))) assert_equal(special.rgamma(-1), 0) class TestHankel(object): def test_negv1(self): assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14) def test_hankel1(self): hank1 = special.hankel1(1,.1) hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j) assert_almost_equal(hank1,hankrl,8) def test_negv1e(self): assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14) def test_hankel1e(self): hank1e = special.hankel1e(1,.1) hankrle = special.hankel1(1,.1)*exp(-.1j) assert_almost_equal(hank1e,hankrle,8) def test_negv2(self): assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14) def test_hankel2(self): hank2 = special.hankel2(1,.1) hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j) assert_almost_equal(hank2,hankrl2,8) def test_neg2e(self): assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14) def test_hankl2e(self): hank2e = special.hankel2e(1,.1) hankrl2e = special.hankel2e(1,.1) assert_almost_equal(hank2e,hankrl2e,8) class TestHyper(object): def test_h1vp(self): h1 = special.h1vp(1,.1) h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j) assert_almost_equal(h1,h1real,8) def test_h2vp(self): h2 = special.h2vp(1,.1) h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j) assert_almost_equal(h2,h2real,8) def test_hyp0f1(self): # scalar input assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12) assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15) # float input, expected values match mpmath x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5]) expected = np.array([0.58493659229143, 0.70566805723127, 1.0, 1.37789689539747, 1.60373685288480]) assert_allclose(x, expected, rtol=1e-12) # complex input x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j) assert_allclose(x, expected.astype(complex), rtol=1e-12) # test broadcasting x1 = [0.5, 1.5, 2.5] x2 = [0, 1, 0.5] x = special.hyp0f1(x1, x2) expected = [1.0, 1.8134302039235093, 1.21482702689997] assert_allclose(x, expected, rtol=1e-12) x = special.hyp0f1(np.row_stack([x1] * 2), x2) assert_allclose(x, np.row_stack([expected] * 2), rtol=1e-12) assert_raises(ValueError, special.hyp0f1, np.row_stack([x1] * 3), [0, 1]) def test_hyp0f1_gh5764(self): # Just checks the point that failed; there's a more systematic # test in test_mpmath res = special.hyp0f1(0.8, 0.5 + 0.5*1J) # The expected value was generated using mpmath assert_almost_equal(res, 1.6139719776441115 + 1J*0.80893054061790665) def test_hyp1f1(self): hyp1 = special.hyp1f1(.1,.1,.3) assert_almost_equal(hyp1, 1.3498588075760032,7) # test contributed by Moritz Deger (2008-05-29) # https://github.com/scipy/scipy/issues/1186 (Trac #659) # reference data obtained from mathematica [ a, b, x, m(a,b,x)]: # produced with test_hyp1f1.nb ref_data = array([[-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04], [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00], [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05], [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08], [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24], [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21], [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13], [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13], [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02], [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10], [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01], [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21], [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20], [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07], [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03], [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02], [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11], [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03], [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17], [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01], [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00], [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00], [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23], [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01], [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04], [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08], [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01], [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07], [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03], [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09], [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06], [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00], [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01], [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02], [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02], [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02], [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00], [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09], [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01], [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00], [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02], [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05], [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05], [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02], [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02], [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13], [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05], [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12], [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01], [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16], [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37], [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06], [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02], [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12], [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27], [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04], [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06], [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07], [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03], [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07], [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27], [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12], [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32], [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04], [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01], [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02], [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19], [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09], [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31], [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01], [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02], [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08], [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09], [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33], [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01], [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29], [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01], [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29], [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02], [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00], [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08], [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01], [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01], [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01], [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13], [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11], [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02], [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02], [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01], [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31], [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04], [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25], [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01], [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00], [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02], [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05], [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02], [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01], [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01], [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00]]) for a,b,c,expected in ref_data: result = special.hyp1f1(a,b,c) assert_(abs(expected - result)/expected < 1e-4) def test_hyp1f1_gh2957(self): hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933) hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934) assert_almost_equal(hyp1, hyp2, 12) def test_hyp1f1_gh2282(self): hyp = special.hyp1f1(0.5, 1.5, -1000) assert_almost_equal(hyp, 0.028024956081989643, 12) def test_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], [3, 4, 8, 1, special.gamma(8)*special.gamma(8-4-3)/special.gamma(8-3)/special.gamma(8-4)], [3, 2, 3-2+1, -1, 1./2**3*sqrt(pi) * special.gamma(1+3-2)/special.gamma(1+0.5*3-2)/special.gamma(0.5+0.5*3)], [5, 2, 5-2+1, -1, 1./2**5*sqrt(pi) * special.gamma(1+5-2)/special.gamma(1+0.5*5-2)/special.gamma(0.5+0.5*5)], [4, 0.5+4, 1.5-2*4, -1./3, (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4)/special.gamma(3./2)/special.gamma(4./3-2*4)], # and some others # ticket #424 [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484], # negative integer a or b, with c-a-b integer and x > 0.9 [-2,3,1,0.95,0.715], [2,-3,1,0.95,-0.007], [-6,3,1,0.95,0.0000810625], [2,-5,1,0.95,-0.000029375], # huge negative integers (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24), (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18), ] for i, (a, b, c, x, v) in enumerate(values): cv = special.hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_hyperu(self): val1 = special.hyperu(1,0.1,100) assert_almost_equal(val1,0.0098153,7) a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] a,b = asarray(a), asarray(b) z = 0.5 hypu = special.hyperu(a,b,z) hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) / (special.gamma(1+a-b)*special.gamma(b)) - z**(1-b)*special.hyp1f1(1+a-b,2-b,z) / (special.gamma(a)*special.gamma(2-b))) assert_array_almost_equal(hypu,hprl,12) def test_hyperu_gh2287(self): assert_almost_equal(special.hyperu(1, 1.5, 20.2), 0.048360918656699191, 12) class TestBessel(object): def test_itj0y0(self): it0 = array(special.itj0y0(.2)) assert_array_almost_equal(it0,array([0.19933433254006822, -0.34570883800412566]),8) def test_it2j0y0(self): it2 = array(special.it2j0y0(.2)) assert_array_almost_equal(it2,array([0.0049937546274601858, -0.43423067011231614]),8) def test_negv_iv(self): assert_equal(special.iv(3,2), special.iv(-3,2)) def test_j0(self): oz = special.j0(.1) ozr = special.jn(0,.1) assert_almost_equal(oz,ozr,8) def test_j1(self): o1 = special.j1(.1) o1r = special.jn(1,.1) assert_almost_equal(o1,o1r,8) def test_jn(self): jnnr = special.jn(1,.2) assert_almost_equal(jnnr,0.099500832639235995,8) def test_negv_jv(self): assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14) def test_jv(self): values = [[0, 0.1, 0.99750156206604002], [2./3, 1e-8, 0.3239028506761532e-5], [2./3, 1e-10, 0.1503423854873779e-6], [3.1, 1e-10, 0.1711956265409013e-32], [2./3, 4.0, -0.2325440850267039], ] for i, (v, x, y) in enumerate(values): yc = special.jv(v, x) assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) def test_negv_jve(self): assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14) def test_jve(self): jvexp = special.jve(1,.2) assert_almost_equal(jvexp,0.099500832639235995,8) jvexp1 = special.jve(1,.2+1j) z = .2+1j jvexpr = special.jv(1,z)*exp(-abs(z.imag)) assert_almost_equal(jvexp1,jvexpr,8) def test_jn_zeros(self): jn0 = special.jn_zeros(0,5) jn1 = special.jn_zeros(1,5) assert_array_almost_equal(jn0,array([2.4048255577, 5.5200781103, 8.6537279129, 11.7915344391, 14.9309177086]),4) assert_array_almost_equal(jn1,array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]),4) jn102 = special.jn_zeros(102,5) assert_allclose(jn102, array([110.89174935992040343, 117.83464175788308398, 123.70194191713507279, 129.02417238949092824, 134.00114761868422559]), rtol=1e-13) jn301 = special.jn_zeros(301,5) assert_allclose(jn301, array([313.59097866698830153, 323.21549776096288280, 331.22338738656748796, 338.39676338872084500, 345.03284233056064157]), rtol=1e-13) def test_jn_zeros_slow(self): jn0 = special.jn_zeros(0, 300) assert_allclose(jn0[260-1], 816.02884495068867280, rtol=1e-13) assert_allclose(jn0[280-1], 878.86068707124422606, rtol=1e-13) assert_allclose(jn0[300-1], 941.69253065317954064, rtol=1e-13) jn10 = special.jn_zeros(10, 300) assert_allclose(jn10[260-1], 831.67668514305631151, rtol=1e-13) assert_allclose(jn10[280-1], 894.51275095371316931, rtol=1e-13) assert_allclose(jn10[300-1], 957.34826370866539775, rtol=1e-13) jn3010 = special.jn_zeros(3010,5) assert_allclose(jn3010, array([3036.86590780927, 3057.06598526482, 3073.66360690272, 3088.37736494778, 3101.86438139042]), rtol=1e-8) def test_jnjnp_zeros(self): jn = special.jn def jnp(n, x): return (jn(n-1,x) - jn(n+1,x))/2 for nt in range(1, 30): z, n, m, t = special.jnjnp_zeros(nt) for zz, nn, tt in zip(z, n, t): if tt == 0: assert_allclose(jn(nn, zz), 0, atol=1e-6) elif tt == 1: assert_allclose(jnp(nn, zz), 0, atol=1e-6) else: raise AssertionError("Invalid t return for nt=%d" % nt) def test_jnp_zeros(self): jnp = special.jnp_zeros(1,5) assert_array_almost_equal(jnp, array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]),4) jnp = special.jnp_zeros(443,5) assert_allclose(special.jvp(443, jnp), 0, atol=1e-15) def test_jnyn_zeros(self): jnz = special.jnyn_zeros(1,5) assert_array_almost_equal(jnz,(array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]), array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]), array([2.19714, 5.42968, 8.59601, 11.74915, 14.89744]), array([3.68302, 6.94150, 10.12340, 13.28576, 16.44006])),5) def test_jvp(self): jvprim = special.jvp(2,2) jv0 = (special.jv(1,2)-special.jv(3,2))/2 assert_almost_equal(jvprim,jv0,10) def test_k0(self): ozk = special.k0(.1) ozkr = special.kv(0,.1) assert_almost_equal(ozk,ozkr,8) def test_k0e(self): ozke = special.k0e(.1) ozker = special.kve(0,.1) assert_almost_equal(ozke,ozker,8) def test_k1(self): o1k = special.k1(.1) o1kr = special.kv(1,.1) assert_almost_equal(o1k,o1kr,8) def test_k1e(self): o1ke = special.k1e(.1) o1ker = special.kve(1,.1) assert_almost_equal(o1ke,o1ker,8) def test_jacobi(self): a = 5*np.random.random() - 1 b = 5*np.random.random() - 1 P0 = special.jacobi(0,a,b) P1 = special.jacobi(1,a,b) P2 = special.jacobi(2,a,b) P3 = special.jacobi(3,a,b) assert_array_almost_equal(P0.c,[1],13) assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13) cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)] p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]] assert_array_almost_equal(P2.c,array(p2c)/8.0,13) cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3), 12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)] p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] assert_array_almost_equal(P3.c,array(p3c)/48.0,13) def test_kn(self): kn1 = special.kn(0,.2) assert_almost_equal(kn1,1.7527038555281462,8) def test_negv_kv(self): assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2)) def test_kv0(self): kv0 = special.kv(0,.2) assert_almost_equal(kv0, 1.7527038555281462, 10) def test_kv1(self): kv1 = special.kv(1,0.2) assert_almost_equal(kv1, 4.775972543220472, 10) def test_kv2(self): kv2 = special.kv(2,0.2) assert_almost_equal(kv2, 49.51242928773287, 10) def test_kn_largeorder(self): assert_allclose(special.kn(32, 1), 1.7516596664574289e+43) def test_kv_largearg(self): assert_equal(special.kv(0, 1e19), 0) def test_negv_kve(self): assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2)) def test_kve(self): kve1 = special.kve(0,.2) kv1 = special.kv(0,.2)*exp(.2) assert_almost_equal(kve1,kv1,8) z = .2+1j kve2 = special.kve(0,z) kv2 = special.kv(0,z)*exp(z) assert_almost_equal(kve2,kv2,8) def test_kvp_v0n1(self): z = 2.2 assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10) def test_kvp_n1(self): v = 3. z = 2.2 xc = -special.kv(v+1,z) + v/z*special.kv(v,z) x = special.kvp(v,z, n=1) assert_almost_equal(xc, x, 10) # this function (kvp) is broken def test_kvp_n2(self): v = 3. z = 2.2 xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z x = special.kvp(v, z, n=2) assert_almost_equal(xc, x, 10) def test_y0(self): oz = special.y0(.1) ozr = special.yn(0,.1) assert_almost_equal(oz,ozr,8) def test_y1(self): o1 = special.y1(.1) o1r = special.yn(1,.1) assert_almost_equal(o1,o1r,8) def test_y0_zeros(self): yo,ypo = special.y0_zeros(2) zo,zpo = special.y0_zeros(2,complex=1) all = r_[yo,zo] allval = r_[ypo,zpo] assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11) assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11) def test_y1_zeros(self): y1 = special.y1_zeros(1) assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) def test_y1p_zeros(self): y1p = special.y1p_zeros(1,complex=1) assert_array_almost_equal(y1p,(array([0.5768+0.904j]), array([-0.7635+0.5892j])),3) def test_yn_zeros(self): an = special.yn_zeros(4,2) assert_array_almost_equal(an,array([5.64515, 9.36162]),5) an = special.yn_zeros(443,5) assert_allclose(an, [450.13573091578090314, 463.05692376675001542, 472.80651546418663566, 481.27353184725625838, 488.98055964441374646], rtol=1e-15) def test_ynp_zeros(self): ao = special.ynp_zeros(0,2) assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6) ao = special.ynp_zeros(43,5) assert_allclose(special.yvp(43, ao), 0, atol=1e-15) ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-9) def test_ynp_zeros_large_order(self): ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-14) def test_yn(self): yn2n = special.yn(1,.2) assert_almost_equal(yn2n,-3.3238249881118471,8) def test_negv_yv(self): assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14) def test_yv(self): yv2 = special.yv(1,.2) assert_almost_equal(yv2,-3.3238249881118471,8) def test_negv_yve(self): assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14) def test_yve(self): yve2 = special.yve(1,.2) assert_almost_equal(yve2,-3.3238249881118471,8) yve2r = special.yv(1,.2+1j)*exp(-1) yve22 = special.yve(1,.2+1j) assert_almost_equal(yve22,yve2r,8) def test_yvp(self): yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0 yvp1 = special.yvp(2,.2) assert_array_almost_equal(yvp1,yvpr,10) def _cephes_vs_amos_points(self): """Yield points at which to compare Cephes implementation to AMOS""" # check several points, including large-amplitude ones for v in [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301]: for z in [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300, 10003]: yield v, z # check half-integers; these are problematic points at least # for cephes/iv for v in 0.5 + arange(-60, 60): yield v, 3.5 def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None): for v, z in self._cephes_vs_amos_points(): if skip is not None and skip(v, z): continue c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z) if np.isinf(c1): assert_(np.abs(c2) >= 1e300, (v, z)) elif np.isnan(c1): assert_(c2.imag != 0, (v, z)) else: assert_allclose(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol) if v == int(v): assert_allclose(c3, c2, err_msg=(v, z), rtol=rtol, atol=atol) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_jv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_yv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305) def test_yv_cephes_vs_amos_only_small_orders(self): skipper = lambda v, z: (abs(v) > 50) self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305, skip=skipper) def test_iv_cephes_vs_amos(self): olderr = np.seterr(all='ignore') try: self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305) finally: np.seterr(**olderr) @pytest.mark.slow def test_iv_cephes_vs_amos_mass_test(self): N = 1000000 np.random.seed(1) v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N) x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N) imsk = (np.random.randint(8, size=N) == 0) v[imsk] = v[imsk].astype(int) old_err = np.seterr(all='ignore') try: c1 = special.iv(v, x) c2 = special.iv(v, x+0j) # deal with differences in the inf and zero cutoffs c1[abs(c1) > 1e300] = np.inf c2[abs(c2) > 1e300] = np.inf c1[abs(c1) < 1e-300] = 0 c2[abs(c2) < 1e-300] = 0 dc = abs(c1/c2 - 1) dc[np.isnan(dc)] = 0 finally: np.seterr(**old_err) k = np.argmax(dc) # Most error apparently comes from AMOS and not our implementation; # there are some problems near integer orders there assert_(dc[k] < 2e-7, (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j))) def test_kv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305) self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305) def test_ticket_623(self): assert_allclose(special.jv(3, 4), 0.43017147387562193) assert_allclose(special.jv(301, 1300), 0.0183487151115275) assert_allclose(special.jv(301, 1296.0682), -0.0224174325312048) def test_ticket_853(self): """Negative-order Bessels""" # cephes assert_allclose(special.jv(-1, 1), -0.4400505857449335) assert_allclose(special.jv(-2, 1), 0.1149034849319005) assert_allclose(special.yv(-1, 1), 0.7812128213002887) assert_allclose(special.yv(-2, 1), -1.650682606816255) assert_allclose(special.iv(-1, 1), 0.5651591039924851) assert_allclose(special.iv(-2, 1), 0.1357476697670383) assert_allclose(special.kv(-1, 1), 0.6019072301972347) assert_allclose(special.kv(-2, 1), 1.624838898635178) assert_allclose(special.jv(-0.5, 1), 0.43109886801837607952) assert_allclose(special.yv(-0.5, 1), 0.6713967071418031) assert_allclose(special.iv(-0.5, 1), 1.231200214592967) assert_allclose(special.kv(-0.5, 1), 0.4610685044478945) # amos assert_allclose(special.jv(-1, 1+0j), -0.4400505857449335) assert_allclose(special.jv(-2, 1+0j), 0.1149034849319005) assert_allclose(special.yv(-1, 1+0j), 0.7812128213002887) assert_allclose(special.yv(-2, 1+0j), -1.650682606816255) assert_allclose(special.iv(-1, 1+0j), 0.5651591039924851) assert_allclose(special.iv(-2, 1+0j), 0.1357476697670383) assert_allclose(special.kv(-1, 1+0j), 0.6019072301972347) assert_allclose(special.kv(-2, 1+0j), 1.624838898635178) assert_allclose(special.jv(-0.5, 1+0j), 0.43109886801837607952) assert_allclose(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j) assert_allclose(special.yv(-0.5, 1+0j), 0.6713967071418031) assert_allclose(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j) assert_allclose(special.iv(-0.5, 1+0j), 1.231200214592967) assert_allclose(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j) assert_allclose(special.kv(-0.5, 1+0j), 0.4610685044478945) assert_allclose(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j) assert_allclose(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3)) assert_allclose(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j)) assert_allclose(special.hankel1(-0.5, 1+1j), special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j)) assert_allclose(special.hankel2(-0.5, 1+1j), special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j)) def test_ticket_854(self): """Real-valued Bessel domains""" assert_(isnan(special.jv(0.5, -1))) assert_(isnan(special.iv(0.5, -1))) assert_(isnan(special.yv(0.5, -1))) assert_(isnan(special.yv(1, -1))) assert_(isnan(special.kv(0.5, -1))) assert_(isnan(special.kv(1, -1))) assert_(isnan(special.jve(0.5, -1))) assert_(isnan(special.ive(0.5, -1))) assert_(isnan(special.yve(0.5, -1))) assert_(isnan(special.yve(1, -1))) assert_(isnan(special.kve(0.5, -1))) assert_(isnan(special.kve(1, -1))) assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1)) assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1)) def test_gh_7909(self): assert_(special.kv(1.5, 0) == np.inf) assert_(special.kve(1.5, 0) == np.inf) def test_ticket_503(self): """Real-valued Bessel I overflow""" assert_allclose(special.iv(1, 700), 1.528500390233901e302) assert_allclose(special.iv(1000, 1120), 1.301564549405821e301) def test_iv_hyperg_poles(self): assert_allclose(special.iv(-0.5, 1), 1.231200214592967) def iv_series(self, v, z, n=200): k = arange(0, n).astype(float_) r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1) r[isnan(r)] = inf r = exp(r) err = abs(r).max() * finfo(float_).eps * n + abs(r[-1])*10 return r.sum(), err def test_i0_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(0, z) assert_allclose(special.i0(z), value, atol=err, err_msg=z) def test_i1_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(1, z) assert_allclose(special.i1(z), value, atol=err, err_msg=z) def test_iv_series(self): for v in [-20., -10., -1., 0., 1., 12.49, 120.]: for z in [1., 10., 200.5, -1+2j]: value, err = self.iv_series(v, z) assert_allclose(special.iv(v, z), value, atol=err, err_msg=(v, z)) def test_i0(self): values = [[0.0, 1.0], [1e-10, 1.0], [0.1, 0.9071009258], [0.5, 0.6450352706], [1.0, 0.4657596077], [2.5, 0.2700464416], [5.0, 0.1835408126], [20.0, 0.0897803119], ] for i, (x, v) in enumerate(values): cv = special.i0(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i0e(self): oize = special.i0e(.1) oizer = special.ive(0,.1) assert_almost_equal(oize,oizer,8) def test_i1(self): values = [[0.0, 0.0], [1e-10, 0.4999999999500000e-10], [0.1, 0.0452984468], [0.5, 0.1564208032], [1.0, 0.2079104154], [5.0, 0.1639722669], [20.0, 0.0875062222], ] for i, (x, v) in enumerate(values): cv = special.i1(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i1e(self): oi1e = special.i1e(.1) oi1er = special.ive(1,.1) assert_almost_equal(oi1e,oi1er,8) def test_iti0k0(self): iti0 = array(special.iti0k0(5)) assert_array_almost_equal(iti0,array([31.848667776169801, 1.5673873907283657]),5) def test_it2i0k0(self): it2k = special.it2i0k0(.1) assert_array_almost_equal(it2k,array([0.0012503906973464409, 3.3309450354686687]),6) def test_iv(self): iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(iv1,0.90710092578230106,10) def test_negv_ive(self): assert_equal(special.ive(3,2), special.ive(-3,2)) def test_ive(self): ive1 = special.ive(0,.1) iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(ive1,iv1,10) def test_ivp0(self): assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10) def test_ivp(self): y = (special.iv(0,2) + special.iv(2,2))/2 x = special.ivp(1,2) assert_almost_equal(x,y,10) class TestLaguerre(object): def test_laguerre(self): lag0 = special.laguerre(0) lag1 = special.laguerre(1) lag2 = special.laguerre(2) lag3 = special.laguerre(3) lag4 = special.laguerre(4) lag5 = special.laguerre(5) assert_array_almost_equal(lag0.c,[1],13) assert_array_almost_equal(lag1.c,[-1,1],13) assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13) assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13) assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) def test_genlaguerre(self): k = 5*np.random.random() - 0.9 lag0 = special.genlaguerre(0,k) lag1 = special.genlaguerre(1,k) lag2 = special.genlaguerre(2,k) lag3 = special.genlaguerre(3,k) assert_equal(lag0.c,[1]) assert_equal(lag1.c,[-1,k+1]) assert_almost_equal(lag2.c,array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0) assert_almost_equal(lag3.c,array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0) # Base polynomials come from Abrahmowitz and Stegan class TestLegendre(object): def test_legendre(self): leg0 = special.legendre(0) leg1 = special.legendre(1) leg2 = special.legendre(2) leg3 = special.legendre(3) leg4 = special.legendre(4) leg5 = special.legendre(5) assert_equal(leg0.c, [1]) assert_equal(leg1.c, [1,0]) assert_almost_equal(leg2.c, array([3,0,-1])/2.0, decimal=13) assert_almost_equal(leg3.c, array([5,0,-3,0])/2.0) assert_almost_equal(leg4.c, array([35,0,-30,0,3])/8.0) assert_almost_equal(leg5.c, array([63,0,-70,0,15,0])/8.0) class TestLambda(object): def test_lmbda(self): lam = special.lmbda(1,.1) lamr = (array([special.jn(0,.1), 2*special.jn(1,.1)/.1]), array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])) assert_array_almost_equal(lam,lamr,8) class TestLog1p(object): def test_log1p(self): l1p = (special.log1p(10), special.log1p(11), special.log1p(12)) l1prl = (log(11), log(12), log(13)) assert_array_almost_equal(l1p,l1prl,8) def test_log1pmore(self): l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2)) l1pmrl = (log(2),log(2.1),log(2.2)) assert_array_almost_equal(l1pm,l1pmrl,8) class TestLegendreFunctions(object): def test_clpmn(self): z = 0.5+0.3j clp = special.clpmn(2, 2, z, 3) assert_array_almost_equal(clp, (array([[1.0000, z, 0.5*(3*z*z-1)], [0.0000, sqrt(z*z-1), 3*z*sqrt(z*z-1)], [0.0000, 0.0000, 3*(z*z-1)]]), array([[0.0000, 1.0000, 3*z], [0.0000, z/sqrt(z*z-1), 3*(2*z*z-1)/sqrt(z*z-1)], [0.0000, 0.0000, 6*z]])), 7) def test_clpmn_close_to_real_2(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x), special.lpmv(m, n, x)]), 7) def test_clpmn_close_to_real_3(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi), special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]), 7) def test_clpmn_across_unit_circle(self): eps = 1e-7 m = 1 n = 1 x = 1j for type in [2, 3]: assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n], special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6) def test_inf(self): for z in (1, -1): for n in range(4): for m in range(1, n): lp = special.clpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) lp = special.lpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) def test_deriv_clpmn(self): # data inside and outside of the unit circle zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j, 1+1j, -1+1j, -1-1j, 1-1j] m = 2 n = 3 for type in [2, 3]: for z in zvals: for h in [1e-3, 1e-3j]: approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0] - special.clpmn(m, n, z-0.5*h, type)[0])/h assert_allclose(special.clpmn(m, n, z, type)[1], approx_derivative, rtol=1e-4) def test_lpmn(self): lp = special.lpmn(0,2,.5) assert_array_almost_equal(lp,(array([[1.00000, 0.50000, -0.12500]]), array([[0.00000, 1.00000, 1.50000]])),4) def test_lpn(self): lpnf = special.lpn(2,.5) assert_array_almost_equal(lpnf,(array([1.00000, 0.50000, -0.12500]), array([0.00000, 1.00000, 1.50000])),4) def test_lpmv(self): lp = special.lpmv(0,2,.5) assert_almost_equal(lp,-0.125,7) lp = special.lpmv(0,40,.001) assert_almost_equal(lp,0.1252678976534484,7) # XXX: this is outside the domain of the current implementation, # so ensure it returns a NaN rather than a wrong answer. olderr = np.seterr(all='ignore') try: lp = special.lpmv(-1,-1,.001) finally: np.seterr(**olderr) assert_(lp != 0 or np.isnan(lp)) def test_lqmn(self): lqmnf = special.lqmn(0,2,.5) lqf = special.lqn(2,.5) assert_array_almost_equal(lqmnf[0][0],lqf[0],4) assert_array_almost_equal(lqmnf[1][0],lqf[1],4) def test_lqmn_gt1(self): """algorithm for real arguments changes at 1.0001 test against analytical result for m=2, n=1 """ x0 = 1.0001 delta = 0.00002 for x in (x0-delta, x0+delta): lq = special.lqmn(2, 1, x)[0][-1, -1] expected = 2/(x*x-1) assert_almost_equal(lq, expected) def test_lqmn_shape(self): a, b = special.lqmn(4, 4, 1.1) assert_equal(a.shape, (5, 5)) assert_equal(b.shape, (5, 5)) a, b = special.lqmn(4, 0, 1.1) assert_equal(a.shape, (5, 1)) assert_equal(b.shape, (5, 1)) def test_lqn(self): lqf = special.lqn(2,.5) assert_array_almost_equal(lqf,(array([0.5493, -0.7253, -0.8187]), array([1.3333, 1.216, -0.8427])),4) class TestMathieu(object): def test_mathieu_a(self): pass def test_mathieu_even_coef(self): special.mathieu_even_coef(2,5) # Q not defined broken and cannot figure out proper reporting order def test_mathieu_odd_coef(self): # same problem as above pass class TestFresnelIntegral(object): def test_modfresnelp(self): pass def test_modfresnelm(self): pass class TestOblCvSeq(object): def test_obl_cv_seq(self): obl = special.obl_cv_seq(0,3,1) assert_array_almost_equal(obl,array([-0.348602, 1.393206, 5.486800, 11.492120]),5) class TestParabolicCylinder(object): def test_pbdn_seq(self): pb = special.pbdn_seq(1,.1) assert_array_almost_equal(pb,(array([0.9975, 0.0998]), array([-0.0499, 0.9925])),4) def test_pbdv(self): special.pbdv(1,.2) 1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0] def test_pbdv_seq(self): pbn = special.pbdn_seq(1,.1) pbv = special.pbdv_seq(1,.1) assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) def test_pbdv_points(self): # simple case eta = np.linspace(-10, 10, 5) z = 2**(eta/2)*np.sqrt(np.pi)/special.gamma(.5-.5*eta) assert_allclose(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14) # some points assert_allclose(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12) assert_allclose(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12) def test_pbdv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbdv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) def test_pbvv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbvv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) class TestPolygamma(object): # from Table 6.2 (pg. 271) of A&S def test_polygamma(self): poly2 = special.polygamma(2,1) poly3 = special.polygamma(3,1) assert_almost_equal(poly2,-2.4041138063,10) assert_almost_equal(poly3,6.4939394023,10) # Test polygamma(0, x) == psi(x) x = [2, 3, 1.1e14] assert_almost_equal(special.polygamma(0, x), special.psi(x)) # Test broadcasting n = [0, 1, 2] x = [0.5, 1.5, 2.5] expected = [-1.9635100260214238, 0.93480220054467933, -0.23620405164172739] assert_almost_equal(special.polygamma(n, x), expected) expected = np.row_stack([expected]*2) assert_almost_equal(special.polygamma(n, np.row_stack([x]*2)), expected) assert_almost_equal(special.polygamma(np.row_stack([n]*2), x), expected) class TestProCvSeq(object): def test_pro_cv_seq(self): prol = special.pro_cv_seq(0,3,1) assert_array_almost_equal(prol,array([0.319000, 2.593084, 6.533471, 12.514462]),5) class TestPsi(object): def test_psi(self): ps = special.psi(1) assert_almost_equal(ps,-0.57721566490153287,8) class TestRadian(object): def test_radian(self): rad = special.radian(90,0,0) assert_almost_equal(rad,pi/2.0,5) def test_radianmore(self): rad1 = special.radian(90,1,60) assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) class TestRiccati(object): def test_riccati_jn(self): N, x = 2, 0.2 S = np.empty((N, N)) for n in range(N): j = special.spherical_jn(n, x) jp = special.spherical_jn(n, x, derivative=True) S[0,n] = x*j S[1,n] = x*jp + j assert_array_almost_equal(S, special.riccati_jn(n, x), 8) def test_riccati_yn(self): N, x = 2, 0.2 C = np.empty((N, N)) for n in range(N): y = special.spherical_yn(n, x) yp = special.spherical_yn(n, x, derivative=True) C[0,n] = x*y C[1,n] = x*yp + y assert_array_almost_equal(C, special.riccati_yn(n, x), 8) class TestRound(object): def test_round(self): rnd = list(map(int,(special.round(10.1),special.round(10.4),special.round(10.5),special.round(10.6)))) # Note: According to the documentation, scipy.special.round is # supposed to round to the nearest even number if the fractional # part is exactly 0.5. On some platforms, this does not appear # to work and thus this test may fail. However, this unit test is # correctly written. rndrl = (10,10,10,11) assert_array_equal(rnd,rndrl) def test_sph_harm(): # Tests derived from tables in # https://en.wikipedia.org/wiki/Table_of_spherical_harmonics sh = special.sph_harm pi = np.pi exp = np.exp sqrt = np.sqrt sin = np.sin cos = np.cos assert_array_almost_equal(sh(0,0,0,0), 0.5/sqrt(pi)) assert_array_almost_equal(sh(-2,2,0.,pi/4), 0.25*sqrt(15./(2.*pi)) * (sin(pi/4))**2.) assert_array_almost_equal(sh(-2,2,0.,pi/2), 0.25*sqrt(15./(2.*pi))) assert_array_almost_equal(sh(2,2,pi,pi/2), 0.25*sqrt(15/(2.*pi)) * exp(0+2.*pi*1j)*sin(pi/2.)**2.) assert_array_almost_equal(sh(2,4,pi/4.,pi/3.), (3./8.)*sqrt(5./(2.*pi)) * exp(0+2.*pi/4.*1j) * sin(pi/3.)**2. * (7.*cos(pi/3.)**2.-1)) assert_array_almost_equal(sh(4,4,pi/8.,pi/6.), (3./16.)*sqrt(35./(2.*pi)) * exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.) def test_sph_harm_ufunc_loop_selection(): # see https://github.com/scipy/scipy/issues/4895 dt = np.dtype(np.complex128) assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt) assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt) assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt) assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt) assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt) assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt) class TestStruve(object): def _series(self, v, z, n=100): """Compute Struve function & error estimate from its power series.""" k = arange(0, n) r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5) err = abs(r).max() * finfo(float_).eps * n return r.sum(), err def test_vs_series(self): """Check Struve function versus its power series""" for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]: for z in [1, 10, 19, 21, 30]: value, err = self._series(v, z) assert_allclose(special.struve(v, z), value, rtol=0, atol=err), (v, z) def test_some_values(self): assert_allclose(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7) assert_allclose(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8) assert_allclose(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12) assert_allclose(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11) assert_equal(special.struve(-12, -41), -special.struve(-12, 41)) assert_equal(special.struve(+12, -41), -special.struve(+12, 41)) assert_equal(special.struve(-11, -41), +special.struve(-11, 41)) assert_equal(special.struve(+11, -41), +special.struve(+11, 41)) assert_(isnan(special.struve(-7.1, -1))) assert_(isnan(special.struve(-10.1, -1))) def test_regression_679(self): """Regression test for #679""" assert_allclose(special.struve(-1.0, 20 - 1e-8), special.struve(-1.0, 20 + 1e-8)) assert_allclose(special.struve(-2.0, 20 - 1e-8), special.struve(-2.0, 20 + 1e-8)) assert_allclose(special.struve(-4.3, 20 - 1e-8), special.struve(-4.3, 20 + 1e-8)) def test_chi2_smalldf(): assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110) def test_ch2_inf(): assert_equal(special.chdtr(0.7,np.inf), 1.0) def test_chi2c_smalldf(): assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110) def test_chi2_inv_smalldf(): assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3) def test_agm_simple(): rtol = 1e-13 # Gauss's constant assert_allclose(1/special.agm(1, np.sqrt(2)), 0.834626841674073186, rtol=rtol) # These values were computed using Wolfram Alpha, with the # function ArithmeticGeometricMean[a, b]. agm13 = 1.863616783244897 agm15 = 2.604008190530940 agm35 = 3.936235503649555 assert_allclose(special.agm([[1], [3]], [1, 3, 5]), [[1, agm13, agm15], [agm13, 3, agm35]], rtol=rtol) # Computed by the iteration formula using mpmath, # with mpmath.mp.prec = 1000: agm12 = 1.4567910310469068 assert_allclose(special.agm(1, 2), agm12, rtol=rtol) assert_allclose(special.agm(2, 1), agm12, rtol=rtol) assert_allclose(special.agm(-1, -2), -agm12, rtol=rtol) assert_allclose(special.agm(24, 6), 13.458171481725614, rtol=rtol) assert_allclose(special.agm(13, 123456789.5), 11111458.498599306, rtol=rtol) assert_allclose(special.agm(1e30, 1), 2.229223055945383e+28, rtol=rtol) assert_allclose(special.agm(1e-22, 1), 0.030182566420169886, rtol=rtol) assert_allclose(special.agm(1e150, 1e180), 2.229223055945383e+178, rtol=rtol) assert_allclose(special.agm(1e180, 1e-150), 2.0634722510162677e+177, rtol=rtol) assert_allclose(special.agm(1e-150, 1e-170), 3.3112619670463756e-152, rtol=rtol) fi = np.finfo(1.0) assert_allclose(special.agm(fi.tiny, fi.max), 1.9892072050015473e+305, rtol=rtol) assert_allclose(special.agm(0.75*fi.max, fi.max), 1.564904312298045e+308, rtol=rtol) assert_allclose(special.agm(fi.tiny, 3*fi.tiny), 4.1466849866735005e-308, rtol=rtol) # zero, nan and inf cases. assert_equal(special.agm(0, 0), 0) assert_equal(special.agm(99, 0), 0) assert_equal(special.agm(-1, 10), np.nan) assert_equal(special.agm(0, np.inf), np.nan) assert_equal(special.agm(np.inf, 0), np.nan) assert_equal(special.agm(0, -np.inf), np.nan) assert_equal(special.agm(-np.inf, 0), np.nan) assert_equal(special.agm(np.inf, -np.inf), np.nan) assert_equal(special.agm(-np.inf, np.inf), np.nan) assert_equal(special.agm(1, np.nan), np.nan) assert_equal(special.agm(np.nan, -1), np.nan) assert_equal(special.agm(1, np.inf), np.inf) assert_equal(special.agm(np.inf, 1), np.inf) assert_equal(special.agm(-1, -np.inf), -np.inf) assert_equal(special.agm(-np.inf, -1), -np.inf) def test_legacy(): # Legacy behavior: truncating arguments to integers with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3)) assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3)) assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3)) assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3)) assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3)) assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3)) assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3)) assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3)) assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3)) @with_special_errors def test_error_raising(): assert_raises(special.SpecialFunctionError, special.iv, 1, 1e99j) def test_xlogy(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x*np.log(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float) z2 = np.r_[z1, [(0, 1j), (1, 1j)]] w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13) w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1]) assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13) def test_xlog1py(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x * np.log1p(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0), (1, 1e-30)], dtype=float) w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13) def test_entr(): def xfunc(x): if x < 0: return -np.inf else: return -special.xlogy(x, x) values = (0, 0.5, 1.0, np.inf) signs = [-1, 1] arr = [] for sgn, v in itertools.product(signs, values): arr.append(sgn * v) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z) assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13) def test_kl_div(): def xfunc(x, y): if x < 0 or y < 0 or (y == 0 and x != 0): # extension of natural domain to preserve convexity return np.inf elif np.isposinf(x) or np.isposinf(y): # limits within the natural domain return np.inf elif x == 0: return y else: return special.xlogy(x, x/y) - x + y values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13) def test_rel_entr(): def xfunc(x, y): if x > 0 and y > 0: return special.xlogy(x, x/y) elif x == 0 and y >= 0: return 0 else: return np.inf values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13) def test_huber(): assert_equal(special.huber(-1, 1.5), np.inf) assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5)) assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2)) def xfunc(delta, r): if delta < 0: return np.inf elif np.abs(r) < delta: return 0.5 * np.square(r) else: return delta * (np.abs(r) - 0.5 * delta) z = np.random.randn(10, 2) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13) def test_pseudo_huber(): def xfunc(delta, r): if delta < 0: return np.inf elif (not delta) or (not r): return 0 else: return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1) z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]]) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13)
aeklant/scipy
scipy/special/tests/test_basic.py
scipy/ndimage/filters.py
"""Precompute series coefficients for log-Gamma.""" try: import mpmath except ImportError: pass def stirling_series(N): with mpmath.workdps(100): coeffs = [mpmath.bernoulli(2*n)/(2*n*(2*n - 1)) for n in range(1, N + 1)] return coeffs def taylor_series_at_1(N): coeffs = [] with mpmath.workdps(100): coeffs.append(-mpmath.euler) for n in range(2, N + 1): coeffs.append((-1)**n*mpmath.zeta(n)/n) return coeffs def main(): print(__doc__) print() stirling_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) for x in stirling_series(8)[::-1]] taylor_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) for x in taylor_series_at_1(23)[::-1]] print("Stirling series coefficients") print("----------------------------") print("\n".join(stirling_coeffs)) print() print("Taylor series coefficients") print("--------------------------") print("\n".join(taylor_coeffs)) print() if __name__ == '__main__': main()
# this program corresponds to special.py ### Means test is not done yet # E Means test is giving error (E) # F Means test is failing (F) # EF Means test is giving error and Failing #! Means test is segfaulting # 8 Means test runs forever ### test_besselpoly ### test_mathieu_a ### test_mathieu_even_coef ### test_mathieu_odd_coef ### test_modfresnelp ### test_modfresnelm # test_pbdv_seq ### test_pbvv_seq ### test_sph_harm import itertools import platform import numpy as np from numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp, log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, float_) import pytest from pytest import raises as assert_raises from numpy.testing import (assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_approx_equal, assert_, assert_allclose, assert_array_almost_equal_nulp, suppress_warnings) from scipy import special import scipy.special._ufuncs as cephes from scipy.special import ellipk from scipy.special._testutils import with_special_errors, \ assert_func_equal, FuncData import math class TestCephes(object): def test_airy(self): cephes.airy(0) def test_airye(self): cephes.airye(0) def test_binom(self): n = np.array([0.264, 4, 5.2, 17]) k = np.array([2, 0.4, 7, 3.3]) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389, -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846], [10.92, 2.22993515861399, -0.00585728, 10.468891352063146], [136, 3.5252179590758828, 19448, 1024.5526916174495]]) assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13) # Test branches in implementation np.random.seed(1234) n = np.r_[np.arange(-7, 30), 1000*np.random.rand(30) - 500] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_2(self): # Test branches in implementation np.random.seed(1234) n = np.r_[np.logspace(1, 300, 20)] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_exact(self): @np.vectorize def binom_int(n, k): n = int(n) k = int(k) num = int(1) den = int(1) for i in range(1, k+1): num *= i + n - k den *= i return float(num/den) np.random.seed(1234) n = np.arange(1, 15) k = np.arange(0, 15) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T nk = nk[nk[:,0] >= nk[:,1]] assert_func_equal(cephes.binom, binom_int(nk[:,0], nk[:,1]), nk, atol=0, rtol=0) def test_binom_nooverflow_8346(self): # Test (binom(n, k) doesn't overflow prematurely */ dataset = [ (1000, 500, 2.70288240945436551e+299), (1002, 501, 1.08007396880791225e+300), (1004, 502, 4.31599279169058121e+300), (1006, 503, 1.72468101616263781e+301), (1008, 504, 6.89188009236419153e+301), (1010, 505, 2.75402257948335448e+302), (1012, 506, 1.10052048531923757e+303), (1014, 507, 4.39774063758732849e+303), (1016, 508, 1.75736486108312519e+304), (1018, 509, 7.02255427788423734e+304), (1020, 510, 2.80626776829962255e+305), (1022, 511, 1.12140876377061240e+306), (1024, 512, 4.48125455209897109e+306), (1026, 513, 1.79075474304149900e+307), (1028, 514, 7.15605105487789676e+307) ] dataset = np.asarray(dataset) FuncData(cephes.binom, dataset, (0, 1), 2, rtol=1e-12).check() def test_bdtr(self): assert_equal(cephes.bdtr(1,1,0.5),1.0) def test_bdtri(self): assert_equal(cephes.bdtri(1,3,0.5),0.5) def test_bdtrc(self): assert_equal(cephes.bdtrc(1,3,0.5),0.5) def test_bdtrin(self): assert_equal(cephes.bdtrin(1,0,1),5.0) def test_bdtrik(self): cephes.bdtrik(1,3,0.5) def test_bei(self): assert_equal(cephes.bei(0),0.0) def test_beip(self): assert_equal(cephes.beip(0),0.0) def test_ber(self): assert_equal(cephes.ber(0),1.0) def test_berp(self): assert_equal(cephes.berp(0),0.0) def test_besselpoly(self): assert_equal(cephes.besselpoly(0,0,0),1.0) def test_beta(self): assert_equal(cephes.beta(1,1),1.0) assert_allclose(cephes.beta(-100.3, 1e-200), cephes.gamma(1e-200)) assert_allclose(cephes.beta(0.0342, 171), 24.070498359873497, rtol=1e-13, atol=0) def test_betainc(self): assert_equal(cephes.betainc(1,1,1),1.0) assert_allclose(cephes.betainc(0.0342, 171, 1e-10), 0.55269916901806648) def test_betaln(self): assert_equal(cephes.betaln(1,1),0.0) assert_allclose(cephes.betaln(-100.3, 1e-200), cephes.gammaln(1e-200)) assert_allclose(cephes.betaln(0.0342, 170), 3.1811881124242447, rtol=1e-14, atol=0) def test_betaincinv(self): assert_equal(cephes.betaincinv(1,1,1),1.0) assert_allclose(cephes.betaincinv(0.0342, 171, 0.25), 8.4231316935498957e-21, rtol=3e-12, atol=0) def test_beta_inf(self): assert_(np.isinf(special.beta(-1, 2))) def test_btdtr(self): assert_equal(cephes.btdtr(1,1,1),1.0) def test_btdtri(self): assert_equal(cephes.btdtri(1,1,1),1.0) def test_btdtria(self): assert_equal(cephes.btdtria(1,1,1),5.0) def test_btdtrib(self): assert_equal(cephes.btdtrib(1,1,1),5.0) def test_cbrt(self): assert_approx_equal(cephes.cbrt(1),1.0) def test_chdtr(self): assert_equal(cephes.chdtr(1,0),0.0) def test_chdtrc(self): assert_equal(cephes.chdtrc(1,0),1.0) def test_chdtri(self): assert_equal(cephes.chdtri(1,1),0.0) def test_chdtriv(self): assert_equal(cephes.chdtriv(0,0),5.0) def test_chndtr(self): assert_equal(cephes.chndtr(0,1,0),0.0) # Each row holds (x, nu, lam, expected_value) # These values were computed using Wolfram Alpha with # CDF[NoncentralChiSquareDistribution[nu, lam], x] values = np.array([ [25.00, 20.0, 400, 4.1210655112396197139e-57], [25.00, 8.00, 250, 2.3988026526832425878e-29], [0.001, 8.00, 40., 5.3761806201366039084e-24], [0.010, 8.00, 40., 5.45396231055999457039e-20], [20.00, 2.00, 107, 1.39390743555819597802e-9], [22.50, 2.00, 107, 7.11803307138105870671e-9], [25.00, 2.00, 107, 3.11041244829864897313e-8], [3.000, 2.00, 1.0, 0.62064365321954362734], [350.0, 300., 10., 0.93880128006276407710], [100.0, 13.5, 10., 0.99999999650104210949], [700.0, 20.0, 400, 0.99999999925680650105], [150.0, 13.5, 10., 0.99999999999999983046], [160.0, 13.5, 10., 0.99999999999999999518], # 1.0 ]) cdf = cephes.chndtr(values[:, 0], values[:, 1], values[:, 2]) assert_allclose(cdf, values[:, 3], rtol=1e-12) assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0) assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0) assert_(np.isnan(cephes.chndtr(np.nan, 1, 2))) assert_(np.isnan(cephes.chndtr(5, np.nan, 2))) assert_(np.isnan(cephes.chndtr(5, 1, np.nan))) def test_chndtridf(self): assert_equal(cephes.chndtridf(0,0,1),5.0) def test_chndtrinc(self): assert_equal(cephes.chndtrinc(0,1,0),5.0) def test_chndtrix(self): assert_equal(cephes.chndtrix(0,1,0),0.0) def test_cosdg(self): assert_equal(cephes.cosdg(0),1.0) def test_cosm1(self): assert_equal(cephes.cosm1(0),0.0) def test_cotdg(self): assert_almost_equal(cephes.cotdg(45),1.0) def test_dawsn(self): assert_equal(cephes.dawsn(0),0.0) assert_allclose(cephes.dawsn(1.23), 0.50053727749081767) def test_diric(self): # Test behavior near multiples of 2pi. Regression test for issue # described in gh-4001. n_odd = [1, 5, 25] x = np.array(2*np.pi + 5e-5).astype(np.float32) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7) x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) x = np.array(2*np.pi + 1e-15).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) if hasattr(np, 'float128'): # No float128 available in 32-bit numpy x = np.array(2*np.pi + 1e-12).astype(np.float128) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19) n_even = [2, 4, 24] x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15) # Test at some values not near a multiple of pi x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi) octave_result = [0.872677996249965, 0.539344662916632, 0.127322003750035, -0.206011329583298] assert_almost_equal(special.diric(x, 3), octave_result, decimal=15) def test_diric_broadcasting(self): x = np.arange(5) n = np.array([1, 3, 7]) assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size)) def test_ellipe(self): assert_equal(cephes.ellipe(1),1.0) def test_ellipeinc(self): assert_equal(cephes.ellipeinc(0,1),0.0) def test_ellipj(self): cephes.ellipj(0,1) def test_ellipk(self): assert_allclose(ellipk(0), pi/2) def test_ellipkinc(self): assert_equal(cephes.ellipkinc(0,0),0.0) def test_erf(self): assert_equal(cephes.erf(0), 0.0) def test_erf_symmetry(self): x = 5.905732037710919 assert_equal(cephes.erf(x) + cephes.erf(-x), 0.0) def test_erfc(self): assert_equal(cephes.erfc(0), 1.0) def test_exp10(self): assert_approx_equal(cephes.exp10(2),100.0) def test_exp2(self): assert_equal(cephes.exp2(2),4.0) def test_expm1(self): assert_equal(cephes.expm1(0),0.0) assert_equal(cephes.expm1(np.inf), np.inf) assert_equal(cephes.expm1(-np.inf), -1) assert_equal(cephes.expm1(np.nan), np.nan) def test_expm1_complex(self): expm1 = cephes.expm1 assert_equal(expm1(0 + 0j), 0 + 0j) assert_equal(expm1(complex(np.inf, 0)), complex(np.inf, 0)) assert_equal(expm1(complex(np.inf, 1)), complex(np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 2)), complex(-np.inf, np.inf)) assert_equal(expm1(complex(np.inf, 4)), complex(-np.inf, -np.inf)) assert_equal(expm1(complex(np.inf, 5)), complex(np.inf, -np.inf)) assert_equal(expm1(complex(1, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(0, np.inf)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.inf, np.inf)), complex(np.inf, np.nan)) assert_equal(expm1(complex(-np.inf, np.inf)), complex(-1, 0)) assert_equal(expm1(complex(-np.inf, np.nan)), complex(-1, 0)) assert_equal(expm1(complex(np.inf, np.nan)), complex(np.inf, np.nan)) assert_equal(expm1(complex(0, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(1, np.nan)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, 1)), complex(np.nan, np.nan)) assert_equal(expm1(complex(np.nan, np.nan)), complex(np.nan, np.nan)) @pytest.mark.xfail(reason='The real part of expm1(z) bad at these points') def test_expm1_complex_hard(self): # The real part of this function is difficult to evaluate when # z.real = -log(cos(z.imag)). y = np.array([0.1, 0.2, 0.3, 5, 11, 20]) x = -np.log(np.cos(y)) z = x + 1j*y # evaluate using mpmath.expm1 with dps=1000 expected = np.array([-5.5507901846769623e-17+0.10033467208545054j, 2.4289354732893695e-18+0.20271003550867248j, 4.5235500262585768e-17+0.30933624960962319j, 7.8234305217489006e-17-3.3805150062465863j, -1.3685191953697676e-16-225.95084645419513j, 8.7175620481291045e-17+2.2371609442247422j]) found = cephes.expm1(z) # this passes. assert_array_almost_equal_nulp(found.imag, expected.imag, 3) # this fails. assert_array_almost_equal_nulp(found.real, expected.real, 20) def test_fdtr(self): assert_equal(cephes.fdtr(1, 1, 0), 0.0) # Computed using Wolfram Alpha: CDF[FRatioDistribution[1e-6, 5], 10] assert_allclose(cephes.fdtr(1e-6, 5, 10), 0.9999940790193488, rtol=1e-12) def test_fdtrc(self): assert_equal(cephes.fdtrc(1, 1, 0), 1.0) # Computed using Wolfram Alpha: # 1 - CDF[FRatioDistribution[2, 1/10], 1e10] assert_allclose(cephes.fdtrc(2, 0.1, 1e10), 0.27223784621293512, rtol=1e-12) def test_fdtri(self): assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]), array([0.9937365, 1.00630298]), rtol=1e-6) # From Wolfram Alpha: # CDF[FRatioDistribution[1/10, 1], 3] = 0.8756751669632105666874... p = 0.8756751669632105666874 assert_allclose(cephes.fdtri(0.1, 1, p), 3, rtol=1e-12) @pytest.mark.xfail(reason='Returns nan on i686.') def test_fdtri_mysterious_failure(self): assert_allclose(cephes.fdtri(1, 1, 0.5), 1) def test_fdtridfd(self): assert_equal(cephes.fdtridfd(1,0,0),5.0) def test_fresnel(self): assert_equal(cephes.fresnel(0),(0.0,0.0)) def test_gamma(self): assert_equal(cephes.gamma(5),24.0) def test_gammainccinv(self): assert_equal(cephes.gammainccinv(5,1),0.0) def test_gammaln(self): cephes.gammaln(10) def test_gammasgn(self): vals = np.array([-4, -3.5, -2.3, 1, 4.2], np.float64) assert_array_equal(cephes.gammasgn(vals), np.sign(cephes.rgamma(vals))) def test_gdtr(self): assert_equal(cephes.gdtr(1,1,0),0.0) def test_gdtr_inf(self): assert_equal(cephes.gdtr(1,1,np.inf),1.0) def test_gdtrc(self): assert_equal(cephes.gdtrc(1,1,0),1.0) def test_gdtria(self): assert_equal(cephes.gdtria(0,1,1),0.0) def test_gdtrib(self): cephes.gdtrib(1,0,1) # assert_equal(cephes.gdtrib(1,0,1),5.0) def test_gdtrix(self): cephes.gdtrix(1,1,.1) def test_hankel1(self): cephes.hankel1(1,1) def test_hankel1e(self): cephes.hankel1e(1,1) def test_hankel2(self): cephes.hankel2(1,1) def test_hankel2e(self): cephes.hankel2e(1,1) def test_hyp1f1(self): assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) cephes.hyp1f1(1,1,1) def test_hyp2f1(self): assert_equal(cephes.hyp2f1(1,1,1,0),1.0) def test_i0(self): assert_equal(cephes.i0(0),1.0) def test_i0e(self): assert_equal(cephes.i0e(0),1.0) def test_i1(self): assert_equal(cephes.i1(0),0.0) def test_i1e(self): assert_equal(cephes.i1e(0),0.0) def test_it2i0k0(self): cephes.it2i0k0(1) def test_it2j0y0(self): cephes.it2j0y0(1) def test_it2struve0(self): cephes.it2struve0(1) def test_itairy(self): cephes.itairy(1) def test_iti0k0(self): assert_equal(cephes.iti0k0(0),(0.0,0.0)) def test_itj0y0(self): assert_equal(cephes.itj0y0(0),(0.0,0.0)) def test_itmodstruve0(self): assert_equal(cephes.itmodstruve0(0),0.0) def test_itstruve0(self): assert_equal(cephes.itstruve0(0),0.0) def test_iv(self): assert_equal(cephes.iv(1,0),0.0) def _check_ive(self): assert_equal(cephes.ive(1,0),0.0) def test_j0(self): assert_equal(cephes.j0(0),1.0) def test_j1(self): assert_equal(cephes.j1(0),0.0) def test_jn(self): assert_equal(cephes.jn(0,0),1.0) def test_jv(self): assert_equal(cephes.jv(0,0),1.0) def _check_jve(self): assert_equal(cephes.jve(0,0),1.0) def test_k0(self): cephes.k0(2) def test_k0e(self): cephes.k0e(2) def test_k1(self): cephes.k1(2) def test_k1e(self): cephes.k1e(2) def test_kei(self): cephes.kei(2) def test_keip(self): assert_equal(cephes.keip(0),0.0) def test_ker(self): cephes.ker(2) def test_kerp(self): cephes.kerp(2) def _check_kelvin(self): cephes.kelvin(2) def test_kn(self): cephes.kn(1,1) def test_kolmogi(self): assert_equal(cephes.kolmogi(1),0.0) assert_(np.isnan(cephes.kolmogi(np.nan))) def test_kolmogorov(self): assert_equal(cephes.kolmogorov(0), 1.0) def test_kolmogp(self): assert_equal(cephes._kolmogp(0), -0.0) def test_kolmogc(self): assert_equal(cephes._kolmogc(0), 0.0) def test_kolmogci(self): assert_equal(cephes._kolmogci(0), 0.0) assert_(np.isnan(cephes._kolmogci(np.nan))) def _check_kv(self): cephes.kv(1,1) def _check_kve(self): cephes.kve(1,1) def test_log1p(self): log1p = cephes.log1p assert_equal(log1p(0), 0.0) assert_equal(log1p(-1), -np.inf) assert_equal(log1p(-2), np.nan) assert_equal(log1p(np.inf), np.inf) def test_log1p_complex(self): log1p = cephes.log1p c = complex assert_equal(log1p(0 + 0j), 0 + 0j) assert_equal(log1p(c(-1, 0)), c(-np.inf, 0)) with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in multiply") assert_allclose(log1p(c(1, np.inf)), c(np.inf, np.pi/2)) assert_equal(log1p(c(1, np.nan)), c(np.nan, np.nan)) assert_allclose(log1p(c(-np.inf, 1)), c(np.inf, np.pi)) assert_equal(log1p(c(np.inf, 1)), c(np.inf, 0)) assert_allclose(log1p(c(-np.inf, np.inf)), c(np.inf, 3*np.pi/4)) assert_allclose(log1p(c(np.inf, np.inf)), c(np.inf, np.pi/4)) assert_equal(log1p(c(np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(-np.inf, np.nan)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, np.inf)), c(np.inf, np.nan)) assert_equal(log1p(c(np.nan, 1)), c(np.nan, np.nan)) assert_equal(log1p(c(np.nan, np.nan)), c(np.nan, np.nan)) def test_lpmv(self): assert_equal(cephes.lpmv(0,0,1),1.0) def test_mathieu_a(self): assert_equal(cephes.mathieu_a(1,0),1.0) def test_mathieu_b(self): assert_equal(cephes.mathieu_b(1,0),1.0) def test_mathieu_cem(self): assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) # Test AMS 20.2.27 @np.vectorize def ce_smallq(m, q, z): z *= np.pi/180 if m == 0: return 2**(-0.5) * (1 - .5*q*cos(2*z)) # + O(q^2) elif m == 1: return cos(z) - q/8 * cos(3*z) # + O(q^2) elif m == 2: return cos(2*z) - q*(cos(4*z)/12 - 1/4) # + O(q^2) else: return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(0, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0], ce_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_sem(self): assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) # Test AMS 20.2.27 @np.vectorize def se_smallq(m, q, z): z *= np.pi/180 if m == 1: return sin(z) - q/8 * sin(3*z) # + O(q^2) elif m == 2: return sin(2*z) - q*sin(4*z)/12 # + O(q^2) else: return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(1, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0], se_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_modcem1(self): assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) def test_mathieu_modcem2(self): cephes.mathieu_modcem2(1,1,1) # Test reflection relation AMS 20.6.19 m = np.arange(0, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modcem2(m, q, -z)[0] fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0] y2 = -cephes.mathieu_modcem2(m, q, z)[0] - 2*fr*cephes.mathieu_modcem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_modsem1(self): assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) def test_mathieu_modsem2(self): cephes.mathieu_modsem2(1,1,1) # Test reflection relation AMS 20.6.20 m = np.arange(1, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modsem2(m, q, -z)[0] fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1] y2 = cephes.mathieu_modsem2(m, q, z)[0] - 2*fr*cephes.mathieu_modsem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_overflow(self): # Check that these return NaNs instead of causing a SEGV assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan)) def test_mathieu_ticket_1847(self): # Regression test --- this call had some out-of-bounds access # and could return nan occasionally for k in range(60): v = cephes.mathieu_modsem2(2, 100, -1) # Values from ACM TOMS 804 (derivate by numerical differentiation) assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10) assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4) def test_modfresnelm(self): cephes.modfresnelm(0) def test_modfresnelp(self): cephes.modfresnelp(0) def _check_modstruve(self): assert_equal(cephes.modstruve(1,0),0.0) def test_nbdtr(self): assert_equal(cephes.nbdtr(1,1,1),1.0) def test_nbdtrc(self): assert_equal(cephes.nbdtrc(1,1,1),0.0) def test_nbdtri(self): assert_equal(cephes.nbdtri(1,1,1),1.0) def __check_nbdtrik(self): cephes.nbdtrik(1,.4,.5) def test_nbdtrin(self): assert_equal(cephes.nbdtrin(1,0,0),5.0) def test_ncfdtr(self): assert_equal(cephes.ncfdtr(1,1,1,0),0.0) def test_ncfdtri(self): assert_equal(cephes.ncfdtri(1, 1, 1, 0), 0.0) f = [0.5, 1, 1.5] p = cephes.ncfdtr(2, 3, 1.5, f) assert_allclose(cephes.ncfdtri(2, 3, 1.5, p), f) def test_ncfdtridfd(self): dfd = [1, 2, 3] p = cephes.ncfdtr(2, dfd, 0.25, 15) assert_allclose(cephes.ncfdtridfd(2, p, 0.25, 15), dfd) def test_ncfdtridfn(self): dfn = [0.1, 1, 2, 3, 1e4] p = cephes.ncfdtr(dfn, 2, 0.25, 15) assert_allclose(cephes.ncfdtridfn(p, 2, 0.25, 15), dfn, rtol=1e-5) def test_ncfdtrinc(self): nc = [0.5, 1.5, 2.0] p = cephes.ncfdtr(2, 3, nc, 15) assert_allclose(cephes.ncfdtrinc(2, 3, p, 15), nc) def test_nctdtr(self): assert_equal(cephes.nctdtr(1,0,0),0.5) assert_equal(cephes.nctdtr(9, 65536, 45), 0.0) assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5) assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.))) assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.) assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.))) assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.))) assert_(np.isnan(cephes.nctdtr(2., 1., np.nan))) def __check_nctdtridf(self): cephes.nctdtridf(1,0.5,0) def test_nctdtrinc(self): cephes.nctdtrinc(1,0,0) def test_nctdtrit(self): cephes.nctdtrit(.1,0.2,.5) def test_nrdtrimn(self): assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) def test_nrdtrisd(self): assert_allclose(cephes.nrdtrisd(0.5,0.5,0.5), 0.0, atol=0, rtol=0) def test_obl_ang1(self): cephes.obl_ang1(1,1,1,0) def test_obl_ang1_cv(self): result = cephes.obl_ang1_cv(1,1,1,1,0) assert_almost_equal(result[0],1.0) assert_almost_equal(result[1],0.0) def _check_obl_cv(self): assert_equal(cephes.obl_cv(1,1,0),2.0) def test_obl_rad1(self): cephes.obl_rad1(1,1,1,0) def test_obl_rad1_cv(self): cephes.obl_rad1_cv(1,1,1,1,0) def test_obl_rad2(self): cephes.obl_rad2(1,1,1,0) def test_obl_rad2_cv(self): cephes.obl_rad2_cv(1,1,1,1,0) def test_pbdv(self): assert_equal(cephes.pbdv(1,0),(0.0,1.0)) def test_pbvv(self): cephes.pbvv(1,0) def test_pbwa(self): cephes.pbwa(1,0) def test_pdtr(self): val = cephes.pdtr(0, 1) assert_almost_equal(val, np.exp(-1)) # Edge case: m = 0. val = cephes.pdtr([0, 1, 2], 0) assert_array_equal(val, [1, 1, 1]) def test_pdtrc(self): val = cephes.pdtrc(0, 1) assert_almost_equal(val, 1 - np.exp(-1)) # Edge case: m = 0. val = cephes.pdtrc([0, 1, 2], 0.0) assert_array_equal(val, [0, 0, 0]) def test_pdtri(self): with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") cephes.pdtri(0.5,0.5) def test_pdtrik(self): k = cephes.pdtrik(0.5, 1) assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5) # Edge case: m = 0 or very small. k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6]) assert_array_equal(k, np.zeros((3, 3))) def test_pro_ang1(self): cephes.pro_ang1(1,1,1,0) def test_pro_ang1_cv(self): assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), array((1.0,0.0))) def _check_pro_cv(self): assert_equal(cephes.pro_cv(1,1,0),2.0) def test_pro_rad1(self): cephes.pro_rad1(1,1,1,0.1) def test_pro_rad1_cv(self): cephes.pro_rad1_cv(1,1,1,1,0) def test_pro_rad2(self): cephes.pro_rad2(1,1,1,0) def test_pro_rad2_cv(self): cephes.pro_rad2_cv(1,1,1,1,0) def test_psi(self): cephes.psi(1) def test_radian(self): assert_equal(cephes.radian(0,0,0),0) def test_rgamma(self): assert_equal(cephes.rgamma(1),1.0) def test_round(self): assert_equal(cephes.round(3.4),3.0) assert_equal(cephes.round(-3.4),-3.0) assert_equal(cephes.round(3.6),4.0) assert_equal(cephes.round(-3.6),-4.0) assert_equal(cephes.round(3.5),4.0) assert_equal(cephes.round(-3.5),-4.0) def test_shichi(self): cephes.shichi(1) def test_sici(self): cephes.sici(1) s, c = cephes.sici(np.inf) assert_almost_equal(s, np.pi * 0.5) assert_almost_equal(c, 0) s, c = cephes.sici(-np.inf) assert_almost_equal(s, -np.pi * 0.5) assert_(np.isnan(c), "cosine integral(-inf) is not nan") def test_sindg(self): assert_equal(cephes.sindg(90),1.0) def test_smirnov(self): assert_equal(cephes.smirnov(1,.1),0.9) assert_(np.isnan(cephes.smirnov(1,np.nan))) def test_smirnovp(self): assert_equal(cephes._smirnovp(1, .1), -1) assert_equal(cephes._smirnovp(2, 0.75), -2*(0.25)**(2-1)) assert_equal(cephes._smirnovp(3, 0.75), -3*(0.25)**(3-1)) assert_(np.isnan(cephes._smirnovp(1, np.nan))) def test_smirnovc(self): assert_equal(cephes._smirnovc(1,.1),0.1) assert_(np.isnan(cephes._smirnovc(1,np.nan))) x10 = np.linspace(0, 1, 11, endpoint=True) assert_almost_equal(cephes._smirnovc(3, x10), 1-cephes.smirnov(3, x10)) x4 = np.linspace(0, 1, 5, endpoint=True) assert_almost_equal(cephes._smirnovc(4, x4), 1-cephes.smirnov(4, x4)) def test_smirnovi(self): assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) assert_(np.isnan(cephes.smirnovi(1,np.nan))) def test_smirnovci(self): assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.4)),0.4) assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.6)),0.6) assert_(np.isnan(cephes._smirnovci(1,np.nan))) def test_spence(self): assert_equal(cephes.spence(1),0.0) def test_stdtr(self): assert_equal(cephes.stdtr(1,0),0.5) assert_almost_equal(cephes.stdtr(1,1), 0.75) assert_almost_equal(cephes.stdtr(1,2), 0.852416382349) def test_stdtridf(self): cephes.stdtridf(0.7,1) def test_stdtrit(self): cephes.stdtrit(1,0.7) def test_struve(self): assert_equal(cephes.struve(0,0),0.0) def test_tandg(self): assert_equal(cephes.tandg(45),1.0) def test_tklmbda(self): assert_almost_equal(cephes.tklmbda(1,1),1.0) def test_y0(self): cephes.y0(1) def test_y1(self): cephes.y1(1) def test_yn(self): cephes.yn(1,1) def test_yv(self): cephes.yv(1,1) def _check_yve(self): cephes.yve(1,1) def test_wofz(self): z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.), complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.), complex(-0.0000000234545,1.1234), complex(-3.,5.1), complex(-53,30.1), complex(0.0,0.12345), complex(11,1), complex(-22,-2), complex(9,-28), complex(21,-33), complex(1e5,1e5), complex(1e14,1e14) ] w = [ complex(-3.78270245518980507452677445620103199303131110e-7, 0.000903861276433172057331093754199933411710053155), complex(0.1764906227004816847297495349730234591778719532788, -0.02146550539468457616788719893991501311573031095617), complex(0.2410250715772692146133539023007113781272362309451, 0.06087579663428089745895459735240964093522265589350), complex(0.30474420525691259245713884106959496013413834051768, -0.20821893820283162728743734725471561394145872072738), complex(7.317131068972378096865595229600561710140617977e34, 8.321873499714402777186848353320412813066170427e34), complex(0.0615698507236323685519612934241429530190806818395, -0.00676005783716575013073036218018565206070072304635), complex(0.3960793007699874918961319170187598400134746631, -5.593152259116644920546186222529802777409274656e-9), complex(0.08217199226739447943295069917990417630675021771804, -0.04701291087643609891018366143118110965272615832184), complex(0.00457246000350281640952328010227885008541748668738, -0.00804900791411691821818731763401840373998654987934), complex(0.8746342859608052666092782112565360755791467973338452, 0.), complex(0.00468190164965444174367477874864366058339647648741, 0.0510735563901306197993676329845149741675029197050), complex(-0.0023193175200187620902125853834909543869428763219, -0.025460054739731556004902057663500272721780776336), complex(9.11463368405637174660562096516414499772662584e304, 3.97101807145263333769664875189354358563218932e305), complex(-4.4927207857715598976165541011143706155432296e281, -2.8019591213423077494444700357168707775769028e281), complex(2.820947917809305132678577516325951485807107151e-6, 2.820947917668257736791638444590253942253354058e-6), complex(2.82094791773878143474039725787438662716372268e-15, 2.82094791773878143474039725773333923127678361e-15) ] assert_func_equal(cephes.wofz, w, z, rtol=1e-13) class TestAiry(object): def test_airy(self): # This tests the airy function to ensure 8 place accuracy in computation x = special.airy(.99) assert_array_almost_equal(x,array([0.13689066,-0.16050153,1.19815925,0.92046818]),8) x = special.airy(.41) assert_array_almost_equal(x,array([0.25238916,-.23480512,0.80686202,0.51053919]),8) x = special.airy(-.36) assert_array_almost_equal(x,array([0.44508477,-0.23186773,0.44939534,0.48105354]),8) def test_airye(self): a = special.airye(0.01) b = special.airy(0.01) b1 = [None]*4 for n in range(2): b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01)) for n in range(2,4): b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) assert_array_almost_equal(a,b1,6) def test_bi_zeros(self): bi = special.bi_zeros(2) bia = (array([-1.17371322, -3.2710930]), array([-2.29443968, -4.07315509]), array([-0.45494438, 0.39652284]), array([0.60195789, -0.76031014])) assert_array_almost_equal(bi,bia,4) bi = special.bi_zeros(5) assert_array_almost_equal(bi[0],array([-1.173713222709127, -3.271093302836352, -4.830737841662016, -6.169852128310251, -7.376762079367764]),11) assert_array_almost_equal(bi[1],array([-2.294439682614122, -4.073155089071828, -5.512395729663599, -6.781294445990305, -7.940178689168587]),10) assert_array_almost_equal(bi[2],array([-0.454944383639657, 0.396522836094465, -0.367969161486959, 0.349499116831805, -0.336026240133662]),11) assert_array_almost_equal(bi[3],array([0.601957887976239, -0.760310141492801, 0.836991012619261, -0.88947990142654, 0.929983638568022]),10) def test_ai_zeros(self): ai = special.ai_zeros(1) assert_array_almost_equal(ai,(array([-2.33810741]), array([-1.01879297]), array([0.5357]), array([0.7012])),4) def test_ai_zeros_big(self): z, zp, ai_zpx, aip_zx = special.ai_zeros(50000) ai_z, aip_z, _, _ = special.airy(z) ai_zp, aip_zp, _, _ = special.airy(zp) ai_envelope = 1/abs(z)**(1./4) aip_envelope = abs(zp)**(1./4) # Check values assert_allclose(ai_zpx, ai_zp, rtol=1e-10) assert_allclose(aip_zx, aip_z, rtol=1e-10) # Check they are zeros assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0) assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.1 assert_allclose(z[:6], [-2.3381074105, -4.0879494441, -5.5205598281, -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10) assert_allclose(zp[:6], [-1.0187929716, -3.2481975822, -4.8200992112, -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10) def test_bi_zeros_big(self): z, zp, bi_zpx, bip_zx = special.bi_zeros(50000) _, _, bi_z, bip_z = special.airy(z) _, _, bi_zp, bip_zp = special.airy(zp) bi_envelope = 1/abs(z)**(1./4) bip_envelope = abs(zp)**(1./4) # Check values assert_allclose(bi_zpx, bi_zp, rtol=1e-10) assert_allclose(bip_zx, bip_z, rtol=1e-10) # Check they are zeros assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0) assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.2 assert_allclose(z[:6], [-1.1737132227, -3.2710933028, -4.8307378417, -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10) assert_allclose(zp[:6], [-2.2944396826, -4.0731550891, -5.5123957297, -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10) class TestAssocLaguerre(object): def test_assoc_laguerre(self): a1 = special.genlaguerre(11,1) a2 = special.assoc_laguerre(.2,11,1) assert_array_almost_equal(a2,a1(.2),8) a2 = special.assoc_laguerre(1,11,1) assert_array_almost_equal(a2,a1(1),8) class TestBesselpoly(object): def test_besselpoly(self): pass class TestKelvin(object): def test_bei(self): mbei = special.bei(2) assert_almost_equal(mbei, 0.9722916273066613,5) # this may not be exact def test_beip(self): mbeip = special.beip(2) assert_almost_equal(mbeip,0.91701361338403631,5) # this may not be exact def test_ber(self): mber = special.ber(2) assert_almost_equal(mber,0.75173418271380821,5) # this may not be exact def test_berp(self): mberp = special.berp(2) assert_almost_equal(mberp,-0.49306712470943909,5) # this may not be exact def test_bei_zeros(self): # Abramowitz & Stegun, Table 9.12 bi = special.bei_zeros(5) assert_array_almost_equal(bi,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) def test_beip_zeros(self): bip = special.beip_zeros(5) assert_array_almost_equal(bip,array([3.772673304934953, 8.280987849760042, 12.742147523633703, 17.193431752512542, 21.641143941167325]),8) def test_ber_zeros(self): ber = special.ber_zeros(5) assert_array_almost_equal(ber,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) def test_berp_zeros(self): brp = special.berp_zeros(5) assert_array_almost_equal(brp,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) def test_kelvin(self): mkelv = special.kelvin(2) assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j, special.ker(2) + special.kei(2)*1j, special.berp(2) + special.beip(2)*1j, special.kerp(2) + special.keip(2)*1j),8) def test_kei(self): mkei = special.kei(2) assert_almost_equal(mkei,-0.20240006776470432,5) def test_keip(self): mkeip = special.keip(2) assert_almost_equal(mkeip,0.21980790991960536,5) def test_ker(self): mker = special.ker(2) assert_almost_equal(mker,-0.041664513991509472,5) def test_kerp(self): mkerp = special.kerp(2) assert_almost_equal(mkerp,-0.10660096588105264,5) def test_kei_zeros(self): kei = special.kei_zeros(5) assert_array_almost_equal(kei,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) def test_keip_zeros(self): keip = special.keip_zeros(5) assert_array_almost_equal(keip,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) # numbers come from 9.9 of A&S pg. 381 def test_kelvin_zeros(self): tmp = special.kelvin_zeros(5) berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp assert_array_almost_equal(berz,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) assert_array_almost_equal(beiz,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) assert_array_almost_equal(kerz,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44382]),4) assert_array_almost_equal(keiz,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) assert_array_almost_equal(berpz,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) assert_array_almost_equal(beipz,array([3.77267, # table from 1927 had 3.77320 # but this is more accurate 8.28099, 12.74215, 17.19343, 21.64114]),4) assert_array_almost_equal(kerpz,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) assert_array_almost_equal(keipz,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) def test_ker_zeros(self): ker = special.ker_zeros(5) assert_array_almost_equal(ker,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44381]),4) def test_kerp_zeros(self): kerp = special.kerp_zeros(5) assert_array_almost_equal(kerp,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) class TestBernoulli(object): def test_bernoulli(self): brn = special.bernoulli(5) assert_array_almost_equal(brn,array([1.0000, -0.5000, 0.1667, 0.0000, -0.0333, 0.0000]),4) class TestBeta(object): def test_beta(self): bet = special.beta(2,4) betg = (special.gamma(2)*special.gamma(4))/special.gamma(6) assert_almost_equal(bet,betg,8) def test_betaln(self): betln = special.betaln(2,4) bet = log(abs(special.beta(2,4))) assert_almost_equal(betln,bet,8) def test_betainc(self): btinc = special.betainc(1,1,.2) assert_almost_equal(btinc,0.2,8) def test_betaincinv(self): y = special.betaincinv(2,4,.5) comp = special.betainc(2,4,y) assert_almost_equal(comp,.5,5) class TestCombinatorics(object): def test_comb(self): assert_array_almost_equal(special.comb([10, 10], [3, 4]), [120., 210.]) assert_almost_equal(special.comb(10, 3), 120.) assert_equal(special.comb(10, 3, exact=True), 120) assert_equal(special.comb(10, 3, exact=True, repetition=True), 220) assert_allclose([special.comb(20, k, exact=True) for k in range(21)], special.comb(20, list(range(21))), atol=1e-15) ii = np.iinfo(int).max + 1 assert_equal(special.comb(ii, ii-1, exact=True), ii) expected = 100891344545564193334812497256 assert_equal(special.comb(100, 50, exact=True), expected) def test_comb_with_np_int64(self): n = 70 k = 30 np_n = np.int64(n) np_k = np.int64(k) assert_equal(special.comb(np_n, np_k, exact=True), special.comb(n, k, exact=True)) def test_comb_zeros(self): assert_equal(special.comb(2, 3, exact=True), 0) assert_equal(special.comb(-1, 3, exact=True), 0) assert_equal(special.comb(2, -1, exact=True), 0) assert_equal(special.comb(2, -1, exact=False), 0) assert_array_almost_equal(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 120.]) def test_perm(self): assert_array_almost_equal(special.perm([10, 10], [3, 4]), [720., 5040.]) assert_almost_equal(special.perm(10, 3), 720.) assert_equal(special.perm(10, 3, exact=True), 720) def test_perm_zeros(self): assert_equal(special.perm(2, 3, exact=True), 0) assert_equal(special.perm(-1, 3, exact=True), 0) assert_equal(special.perm(2, -1, exact=True), 0) assert_equal(special.perm(2, -1, exact=False), 0) assert_array_almost_equal(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 720.]) class TestTrigonometric(object): def test_cbrt(self): cb = special.cbrt(27) cbrl = 27**(1.0/3.0) assert_approx_equal(cb,cbrl) def test_cbrtmore(self): cb1 = special.cbrt(27.9) cbrl1 = 27.9**(1.0/3.0) assert_almost_equal(cb1,cbrl1,8) def test_cosdg(self): cdg = special.cosdg(90) cdgrl = cos(pi/2.0) assert_almost_equal(cdg,cdgrl,8) def test_cosdgmore(self): cdgm = special.cosdg(30) cdgmrl = cos(pi/6.0) assert_almost_equal(cdgm,cdgmrl,8) def test_cosm1(self): cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10)) csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) assert_array_almost_equal(cs,csrl,8) def test_cotdg(self): ct = special.cotdg(30) ctrl = tan(pi/6.0)**(-1) assert_almost_equal(ct,ctrl,8) def test_cotdgmore(self): ct1 = special.cotdg(45) ctrl1 = tan(pi/4.0)**(-1) assert_almost_equal(ct1,ctrl1,8) def test_specialpoints(self): assert_almost_equal(special.cotdg(45), 1.0, 14) assert_almost_equal(special.cotdg(-45), -1.0, 14) assert_almost_equal(special.cotdg(90), 0.0, 14) assert_almost_equal(special.cotdg(-90), 0.0, 14) assert_almost_equal(special.cotdg(135), -1.0, 14) assert_almost_equal(special.cotdg(-135), 1.0, 14) assert_almost_equal(special.cotdg(225), 1.0, 14) assert_almost_equal(special.cotdg(-225), -1.0, 14) assert_almost_equal(special.cotdg(270), 0.0, 14) assert_almost_equal(special.cotdg(-270), 0.0, 14) assert_almost_equal(special.cotdg(315), -1.0, 14) assert_almost_equal(special.cotdg(-315), 1.0, 14) assert_almost_equal(special.cotdg(765), 1.0, 14) def test_sinc(self): # the sinc implementation and more extensive sinc tests are in numpy assert_array_equal(special.sinc([0]), 1) assert_equal(special.sinc(0.0), 1.0) def test_sindg(self): sn = special.sindg(90) assert_equal(sn,1.0) def test_sindgmore(self): snm = special.sindg(30) snmrl = sin(pi/6.0) assert_almost_equal(snm,snmrl,8) snm1 = special.sindg(45) snmrl1 = sin(pi/4.0) assert_almost_equal(snm1,snmrl1,8) class TestTandg(object): def test_tandg(self): tn = special.tandg(30) tnrl = tan(pi/6.0) assert_almost_equal(tn,tnrl,8) def test_tandgmore(self): tnm = special.tandg(45) tnmrl = tan(pi/4.0) assert_almost_equal(tnm,tnmrl,8) tnm1 = special.tandg(60) tnmrl1 = tan(pi/3.0) assert_almost_equal(tnm1,tnmrl1,8) def test_specialpoints(self): assert_almost_equal(special.tandg(0), 0.0, 14) assert_almost_equal(special.tandg(45), 1.0, 14) assert_almost_equal(special.tandg(-45), -1.0, 14) assert_almost_equal(special.tandg(135), -1.0, 14) assert_almost_equal(special.tandg(-135), 1.0, 14) assert_almost_equal(special.tandg(180), 0.0, 14) assert_almost_equal(special.tandg(-180), 0.0, 14) assert_almost_equal(special.tandg(225), 1.0, 14) assert_almost_equal(special.tandg(-225), -1.0, 14) assert_almost_equal(special.tandg(315), -1.0, 14) assert_almost_equal(special.tandg(-315), 1.0, 14) class TestEllip(object): def test_ellipj_nan(self): """Regression test for #912.""" special.ellipj(0.5, np.nan) def test_ellipj(self): el = special.ellipj(0.2,0) rel = [sin(0.2),cos(0.2),1.0,0.20] assert_array_almost_equal(el,rel,13) def test_ellipk(self): elk = special.ellipk(.2) assert_almost_equal(elk,1.659623598610528,11) assert_equal(special.ellipkm1(0.0), np.inf) assert_equal(special.ellipkm1(1.0), pi/2) assert_equal(special.ellipkm1(np.inf), 0.0) assert_equal(special.ellipkm1(np.nan), np.nan) assert_equal(special.ellipkm1(-1), np.nan) assert_allclose(special.ellipk(-10), 0.7908718902387385) def test_ellipkinc(self): elkinc = special.ellipkinc(pi/2,.2) elk = special.ellipk(0.2) assert_almost_equal(elkinc,elk,15) alpha = 20*pi/180 phi = 45*pi/180 m = sin(alpha)**2 elkinc = special.ellipkinc(phi,m) assert_almost_equal(elkinc,0.79398143,8) # From pg. 614 of A & S assert_equal(special.ellipkinc(pi/2, 0.0), pi/2) assert_equal(special.ellipkinc(pi/2, 1.0), np.inf) assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0) assert_equal(special.ellipkinc(pi/2, np.nan), np.nan) assert_equal(special.ellipkinc(pi/2, 2), np.nan) assert_equal(special.ellipkinc(0, 0.5), 0.0) assert_equal(special.ellipkinc(np.inf, 0.5), np.inf) assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipkinc(np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.nan, 0.5), np.nan) assert_equal(special.ellipkinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14) assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946) def test_ellipkinc_2(self): # Regression test for gh-3550 # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipkinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 1.0259330100195334), 1) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipkinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 5.1296650500976675), 2) def test_ellipkinc_singular(self): # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2) xlog = np.logspace(-300, -17, 25) xlin = np.linspace(1e-17, 0.1, 25) xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False) assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)), rtol=1e14) assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)), rtol=1e14) assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)), rtol=1e14) assert_equal(special.ellipkinc(np.pi/2, 1), np.inf) assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)), rtol=1e14) assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf) def test_ellipe(self): ele = special.ellipe(.2) assert_almost_equal(ele,1.4890350580958529,8) assert_equal(special.ellipe(0.0), pi/2) assert_equal(special.ellipe(1.0), 1.0) assert_equal(special.ellipe(-np.inf), np.inf) assert_equal(special.ellipe(np.nan), np.nan) assert_equal(special.ellipe(2), np.nan) assert_allclose(special.ellipe(-10), 3.6391380384177689) def test_ellipeinc(self): eleinc = special.ellipeinc(pi/2,.2) ele = special.ellipe(0.2) assert_almost_equal(eleinc,ele,14) # pg 617 of A & S alpha, phi = 52*pi/180,35*pi/180 m = sin(alpha)**2 eleinc = special.ellipeinc(phi,m) assert_almost_equal(eleinc, 0.58823065, 8) assert_equal(special.ellipeinc(pi/2, 0.0), pi/2) assert_equal(special.ellipeinc(pi/2, 1.0), 1.0) assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf) assert_equal(special.ellipeinc(pi/2, np.nan), np.nan) assert_equal(special.ellipeinc(pi/2, 2), np.nan) assert_equal(special.ellipeinc(0, 0.5), 0.0) assert_equal(special.ellipeinc(np.inf, 0.5), np.inf) assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf) assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf) assert_equal(special.ellipeinc(np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(np.nan, 0.5), np.nan) assert_equal(special.ellipeinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876) def test_ellipeinc_2(self): # Regression test for gh-3550 # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipeinc(phi, mvals) assert_array_almost_equal_nulp(f, np.full_like(f, 0.84442884574781019), 2) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipeinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, np.full_like(f1, 3.3471442287390509), 4) class TestErf(object): def test_erf(self): er = special.erf(.25) assert_almost_equal(er,0.2763263902,8) def test_erf_zeros(self): erz = special.erf_zeros(5) erzr = array([1.45061616+1.88094300j, 2.24465928+2.61657514j, 2.83974105+3.17562810j, 3.33546074+3.64617438j, 3.76900557+4.06069723j]) assert_array_almost_equal(erz,erzr,4) def _check_variant_func(self, func, other_func, rtol, atol=0): np.random.seed(1234) n = 10000 x = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) y = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) z = x + 1j*y old_errors = np.seterr(all='ignore') try: w = other_func(z) w_real = other_func(x).real mask = np.isfinite(w) w = w[mask] z = z[mask] mask = np.isfinite(w_real) w_real = w_real[mask] x = x[mask] # test both real and complex variants assert_func_equal(func, w, z, rtol=rtol, atol=atol) assert_func_equal(func, w_real, x, rtol=rtol, atol=atol) finally: np.seterr(**old_errors) def test_erfc_consistent(self): self._check_variant_func( cephes.erfc, lambda z: 1 - cephes.erf(z), rtol=1e-12, atol=1e-14 # <- the test function loses precision ) def test_erfcx_consistent(self): self._check_variant_func( cephes.erfcx, lambda z: np.exp(z*z) * cephes.erfc(z), rtol=1e-12 ) def test_erfi_consistent(self): self._check_variant_func( cephes.erfi, lambda z: -1j * cephes.erf(1j*z), rtol=1e-12 ) def test_dawsn_consistent(self): self._check_variant_func( cephes.dawsn, lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z), rtol=1e-12 ) def test_erf_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -1, 1] assert_allclose(special.erf(vals), expected, rtol=1e-15) def test_erfc_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, 2, 0] assert_allclose(special.erfc(vals), expected, rtol=1e-15) def test_erfcx_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, np.inf, 0] assert_allclose(special.erfcx(vals), expected, rtol=1e-15) def test_erfi_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -np.inf, np.inf] assert_allclose(special.erfi(vals), expected, rtol=1e-15) def test_dawsn_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan, -0.0, 0.0] assert_allclose(special.dawsn(vals), expected, rtol=1e-15) def test_wofz_nan_inf(self): vals = [np.nan, -np.inf, np.inf] expected = [np.nan + np.nan * 1.j, 0.-0.j, 0.+0.j] assert_allclose(special.wofz(vals), expected, rtol=1e-15) class TestEuler(object): def test_euler(self): eu0 = special.euler(0) eu1 = special.euler(1) eu2 = special.euler(2) # just checking segfaults assert_allclose(eu0, [1], rtol=1e-15) assert_allclose(eu1, [1, 0], rtol=1e-15) assert_allclose(eu2, [1, 0, -1], rtol=1e-15) eu24 = special.euler(24) mathworld = [1,1,5,61,1385,50521,2702765,199360981, 19391512145,2404879675441, 370371188237525,69348874393137901, 15514534163557086905] correct = zeros((25,),'d') for k in range(0,13): if (k % 2): correct[2*k] = -float(mathworld[k]) else: correct[2*k] = float(mathworld[k]) olderr = np.seterr(all='ignore') try: err = nan_to_num((eu24-correct)/correct) errmax = max(err) finally: np.seterr(**olderr) assert_almost_equal(errmax, 0.0, 14) class TestExp(object): def test_exp2(self): ex = special.exp2(2) exrl = 2**2 assert_equal(ex,exrl) def test_exp2more(self): exm = special.exp2(2.5) exmrl = 2**(2.5) assert_almost_equal(exm,exmrl,8) def test_exp10(self): ex = special.exp10(2) exrl = 10**2 assert_approx_equal(ex,exrl) def test_exp10more(self): exm = special.exp10(2.5) exmrl = 10**(2.5) assert_almost_equal(exm,exmrl,8) def test_expm1(self): ex = (special.expm1(2),special.expm1(3),special.expm1(4)) exrl = (exp(2)-1,exp(3)-1,exp(4)-1) assert_array_almost_equal(ex,exrl,8) def test_expm1more(self): ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2)) exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) assert_array_almost_equal(ex1,exrl1,8) class TestFactorialFunctions(object): def test_factorial(self): # Some known values, float math assert_array_almost_equal(special.factorial(0), 1) assert_array_almost_equal(special.factorial(1), 1) assert_array_almost_equal(special.factorial(2), 2) assert_array_almost_equal([6., 24., 120.], special.factorial([3, 4, 5], exact=False)) assert_array_almost_equal(special.factorial([[5, 3], [4, 3]]), [[120, 6], [24, 6]]) # Some known values, integer math assert_equal(special.factorial(0, exact=True), 1) assert_equal(special.factorial(1, exact=True), 1) assert_equal(special.factorial(2, exact=True), 2) assert_equal(special.factorial(5, exact=True), 120) assert_equal(special.factorial(15, exact=True), 1307674368000) # ndarray shape is maintained assert_equal(special.factorial([7, 4, 15, 10], exact=True), [5040, 24, 1307674368000, 3628800]) assert_equal(special.factorial([[5, 3], [4, 3]], True), [[120, 6], [24, 6]]) # object arrays assert_equal(special.factorial(np.arange(-3, 22), True), special.factorial(np.arange(-3, 22), False)) # int64 array assert_equal(special.factorial(np.arange(-3, 15), True), special.factorial(np.arange(-3, 15), False)) # int32 array assert_equal(special.factorial(np.arange(-3, 5), True), special.factorial(np.arange(-3, 5), False)) # Consistent output for n < 0 for exact in (True, False): assert_array_equal(0, special.factorial(-3, exact)) assert_array_equal([1, 2, 0, 0], special.factorial([1, 2, -5, -4], exact)) for n in range(0, 22): # Compare all with math.factorial correct = math.factorial(n) assert_array_equal(correct, special.factorial(n, True)) assert_array_equal(correct, special.factorial([n], True)[0]) assert_allclose(float(correct), special.factorial(n, False)) assert_allclose(float(correct), special.factorial([n], False)[0]) # Compare exact=True vs False, scalar vs array assert_array_equal(special.factorial(n, True), special.factorial(n, False)) assert_array_equal(special.factorial([n], True), special.factorial([n], False)) @pytest.mark.parametrize('x, exact', [ (1, True), (1, False), (np.array(1), True), (np.array(1), False), ]) def test_factorial_0d_return_type(self, x, exact): assert np.isscalar(special.factorial(x, exact=exact)) def test_factorial2(self): assert_array_almost_equal([105., 384., 945.], special.factorial2([7, 8, 9], exact=False)) assert_equal(special.factorial2(7, exact=True), 105) def test_factorialk(self): assert_equal(special.factorialk(5, 1, exact=True), 120) assert_equal(special.factorialk(5, 3, exact=True), 10) @pytest.mark.parametrize('x, exact', [ (np.nan, True), (np.nan, False), (np.array([np.nan]), True), (np.array([np.nan]), False), ]) def test_nan_inputs(self, x, exact): result = special.factorial(x, exact=exact) assert_(np.isnan(result)) def test_mixed_nan_inputs(self): x = np.array([np.nan, 1, 2, 3, np.nan]) result = special.factorial(x, exact=True) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) result = special.factorial(x, exact=False) assert_equal(np.array([np.nan, 1, 2, 6, np.nan]), result) class TestFresnel(object): def test_fresnel(self): frs = array(special.fresnel(.5)) assert_array_almost_equal(frs,array([0.064732432859999287, 0.49234422587144644]),8) def test_fresnel_inf1(self): frs = special.fresnel(np.inf) assert_equal(frs, (0.5, 0.5)) def test_fresnel_inf2(self): frs = special.fresnel(-np.inf) assert_equal(frs, (-0.5, -0.5)) # values from pg 329 Table 7.11 of A & S # slightly corrected in 4th decimal place def test_fresnel_zeros(self): szo, czo = special.fresnel_zeros(5) assert_array_almost_equal(szo, array([2.0093+0.2885j, 2.8335+0.2443j, 3.4675+0.2185j, 4.0026+0.2009j, 4.4742+0.1877j]),3) assert_array_almost_equal(czo, array([1.7437+0.3057j, 2.6515+0.2529j, 3.3204+0.2240j, 3.8757+0.2047j, 4.3611+0.1907j]),3) vals1 = special.fresnel(szo)[0] vals2 = special.fresnel(czo)[1] assert_array_almost_equal(vals1,0,14) assert_array_almost_equal(vals2,0,14) def test_fresnelc_zeros(self): szo, czo = special.fresnel_zeros(6) frc = special.fresnelc_zeros(6) assert_array_almost_equal(frc,czo,12) def test_fresnels_zeros(self): szo, czo = special.fresnel_zeros(5) frs = special.fresnels_zeros(5) assert_array_almost_equal(frs,szo,12) class TestGamma(object): def test_gamma(self): gam = special.gamma(5) assert_equal(gam,24.0) def test_gammaln(self): gamln = special.gammaln(3) lngam = log(special.gamma(3)) assert_almost_equal(gamln,lngam,8) def test_gammainccinv(self): gccinv = special.gammainccinv(.5,.5) gcinv = special.gammaincinv(.5,.5) assert_almost_equal(gccinv,gcinv,8) @with_special_errors def test_gammaincinv(self): y = special.gammaincinv(.4,.4) x = special.gammainc(.4,y) assert_almost_equal(x,0.4,1) y = special.gammainc(10, 0.05) x = special.gammaincinv(10, 2.5715803516000736e-20) assert_almost_equal(0.05, x, decimal=10) assert_almost_equal(y, 2.5715803516000736e-20, decimal=10) x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18) assert_almost_equal(11.0, x, decimal=10) @with_special_errors def test_975(self): # Regression test for ticket #975 -- switch point in algorithm # check that things work OK at the point, immediately next floats # around it, and a bit further away pts = [0.25, np.nextafter(0.25, 0), 0.25 - 1e-12, np.nextafter(0.25, 1), 0.25 + 1e-12] for xp in pts: y = special.gammaincinv(.4, xp) x = special.gammainc(0.4, y) assert_allclose(x, xp, rtol=1e-12) def test_rgamma(self): rgam = special.rgamma(8) rlgam = 1/special.gamma(8) assert_almost_equal(rgam,rlgam,8) def test_infinity(self): assert_(np.isinf(special.gamma(-1))) assert_equal(special.rgamma(-1), 0) class TestHankel(object): def test_negv1(self): assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14) def test_hankel1(self): hank1 = special.hankel1(1,.1) hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j) assert_almost_equal(hank1,hankrl,8) def test_negv1e(self): assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14) def test_hankel1e(self): hank1e = special.hankel1e(1,.1) hankrle = special.hankel1(1,.1)*exp(-.1j) assert_almost_equal(hank1e,hankrle,8) def test_negv2(self): assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14) def test_hankel2(self): hank2 = special.hankel2(1,.1) hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j) assert_almost_equal(hank2,hankrl2,8) def test_neg2e(self): assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14) def test_hankl2e(self): hank2e = special.hankel2e(1,.1) hankrl2e = special.hankel2e(1,.1) assert_almost_equal(hank2e,hankrl2e,8) class TestHyper(object): def test_h1vp(self): h1 = special.h1vp(1,.1) h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j) assert_almost_equal(h1,h1real,8) def test_h2vp(self): h2 = special.h2vp(1,.1) h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j) assert_almost_equal(h2,h2real,8) def test_hyp0f1(self): # scalar input assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12) assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15) # float input, expected values match mpmath x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5]) expected = np.array([0.58493659229143, 0.70566805723127, 1.0, 1.37789689539747, 1.60373685288480]) assert_allclose(x, expected, rtol=1e-12) # complex input x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j) assert_allclose(x, expected.astype(complex), rtol=1e-12) # test broadcasting x1 = [0.5, 1.5, 2.5] x2 = [0, 1, 0.5] x = special.hyp0f1(x1, x2) expected = [1.0, 1.8134302039235093, 1.21482702689997] assert_allclose(x, expected, rtol=1e-12) x = special.hyp0f1(np.row_stack([x1] * 2), x2) assert_allclose(x, np.row_stack([expected] * 2), rtol=1e-12) assert_raises(ValueError, special.hyp0f1, np.row_stack([x1] * 3), [0, 1]) def test_hyp0f1_gh5764(self): # Just checks the point that failed; there's a more systematic # test in test_mpmath res = special.hyp0f1(0.8, 0.5 + 0.5*1J) # The expected value was generated using mpmath assert_almost_equal(res, 1.6139719776441115 + 1J*0.80893054061790665) def test_hyp1f1(self): hyp1 = special.hyp1f1(.1,.1,.3) assert_almost_equal(hyp1, 1.3498588075760032,7) # test contributed by Moritz Deger (2008-05-29) # https://github.com/scipy/scipy/issues/1186 (Trac #659) # reference data obtained from mathematica [ a, b, x, m(a,b,x)]: # produced with test_hyp1f1.nb ref_data = array([[-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04], [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00], [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05], [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08], [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24], [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21], [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13], [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13], [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02], [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10], [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01], [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21], [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20], [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07], [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03], [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02], [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11], [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03], [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17], [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01], [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00], [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00], [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23], [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01], [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04], [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08], [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01], [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07], [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03], [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09], [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06], [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00], [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01], [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02], [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02], [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02], [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00], [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09], [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01], [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00], [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02], [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05], [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05], [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02], [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02], [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13], [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05], [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12], [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01], [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16], [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37], [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06], [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02], [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12], [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27], [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04], [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06], [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07], [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03], [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07], [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27], [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12], [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32], [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04], [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01], [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02], [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19], [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09], [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31], [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01], [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02], [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08], [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09], [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33], [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01], [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29], [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01], [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29], [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02], [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00], [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08], [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01], [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01], [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01], [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13], [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11], [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02], [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02], [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01], [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31], [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04], [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25], [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01], [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00], [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02], [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05], [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02], [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01], [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01], [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00]]) for a,b,c,expected in ref_data: result = special.hyp1f1(a,b,c) assert_(abs(expected - result)/expected < 1e-4) def test_hyp1f1_gh2957(self): hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933) hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934) assert_almost_equal(hyp1, hyp2, 12) def test_hyp1f1_gh2282(self): hyp = special.hyp1f1(0.5, 1.5, -1000) assert_almost_equal(hyp, 0.028024956081989643, 12) def test_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], [3, 4, 8, 1, special.gamma(8)*special.gamma(8-4-3)/special.gamma(8-3)/special.gamma(8-4)], [3, 2, 3-2+1, -1, 1./2**3*sqrt(pi) * special.gamma(1+3-2)/special.gamma(1+0.5*3-2)/special.gamma(0.5+0.5*3)], [5, 2, 5-2+1, -1, 1./2**5*sqrt(pi) * special.gamma(1+5-2)/special.gamma(1+0.5*5-2)/special.gamma(0.5+0.5*5)], [4, 0.5+4, 1.5-2*4, -1./3, (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4)/special.gamma(3./2)/special.gamma(4./3-2*4)], # and some others # ticket #424 [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484], # negative integer a or b, with c-a-b integer and x > 0.9 [-2,3,1,0.95,0.715], [2,-3,1,0.95,-0.007], [-6,3,1,0.95,0.0000810625], [2,-5,1,0.95,-0.000029375], # huge negative integers (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24), (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18), ] for i, (a, b, c, x, v) in enumerate(values): cv = special.hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_hyperu(self): val1 = special.hyperu(1,0.1,100) assert_almost_equal(val1,0.0098153,7) a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] a,b = asarray(a), asarray(b) z = 0.5 hypu = special.hyperu(a,b,z) hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) / (special.gamma(1+a-b)*special.gamma(b)) - z**(1-b)*special.hyp1f1(1+a-b,2-b,z) / (special.gamma(a)*special.gamma(2-b))) assert_array_almost_equal(hypu,hprl,12) def test_hyperu_gh2287(self): assert_almost_equal(special.hyperu(1, 1.5, 20.2), 0.048360918656699191, 12) class TestBessel(object): def test_itj0y0(self): it0 = array(special.itj0y0(.2)) assert_array_almost_equal(it0,array([0.19933433254006822, -0.34570883800412566]),8) def test_it2j0y0(self): it2 = array(special.it2j0y0(.2)) assert_array_almost_equal(it2,array([0.0049937546274601858, -0.43423067011231614]),8) def test_negv_iv(self): assert_equal(special.iv(3,2), special.iv(-3,2)) def test_j0(self): oz = special.j0(.1) ozr = special.jn(0,.1) assert_almost_equal(oz,ozr,8) def test_j1(self): o1 = special.j1(.1) o1r = special.jn(1,.1) assert_almost_equal(o1,o1r,8) def test_jn(self): jnnr = special.jn(1,.2) assert_almost_equal(jnnr,0.099500832639235995,8) def test_negv_jv(self): assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14) def test_jv(self): values = [[0, 0.1, 0.99750156206604002], [2./3, 1e-8, 0.3239028506761532e-5], [2./3, 1e-10, 0.1503423854873779e-6], [3.1, 1e-10, 0.1711956265409013e-32], [2./3, 4.0, -0.2325440850267039], ] for i, (v, x, y) in enumerate(values): yc = special.jv(v, x) assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) def test_negv_jve(self): assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14) def test_jve(self): jvexp = special.jve(1,.2) assert_almost_equal(jvexp,0.099500832639235995,8) jvexp1 = special.jve(1,.2+1j) z = .2+1j jvexpr = special.jv(1,z)*exp(-abs(z.imag)) assert_almost_equal(jvexp1,jvexpr,8) def test_jn_zeros(self): jn0 = special.jn_zeros(0,5) jn1 = special.jn_zeros(1,5) assert_array_almost_equal(jn0,array([2.4048255577, 5.5200781103, 8.6537279129, 11.7915344391, 14.9309177086]),4) assert_array_almost_equal(jn1,array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]),4) jn102 = special.jn_zeros(102,5) assert_allclose(jn102, array([110.89174935992040343, 117.83464175788308398, 123.70194191713507279, 129.02417238949092824, 134.00114761868422559]), rtol=1e-13) jn301 = special.jn_zeros(301,5) assert_allclose(jn301, array([313.59097866698830153, 323.21549776096288280, 331.22338738656748796, 338.39676338872084500, 345.03284233056064157]), rtol=1e-13) def test_jn_zeros_slow(self): jn0 = special.jn_zeros(0, 300) assert_allclose(jn0[260-1], 816.02884495068867280, rtol=1e-13) assert_allclose(jn0[280-1], 878.86068707124422606, rtol=1e-13) assert_allclose(jn0[300-1], 941.69253065317954064, rtol=1e-13) jn10 = special.jn_zeros(10, 300) assert_allclose(jn10[260-1], 831.67668514305631151, rtol=1e-13) assert_allclose(jn10[280-1], 894.51275095371316931, rtol=1e-13) assert_allclose(jn10[300-1], 957.34826370866539775, rtol=1e-13) jn3010 = special.jn_zeros(3010,5) assert_allclose(jn3010, array([3036.86590780927, 3057.06598526482, 3073.66360690272, 3088.37736494778, 3101.86438139042]), rtol=1e-8) def test_jnjnp_zeros(self): jn = special.jn def jnp(n, x): return (jn(n-1,x) - jn(n+1,x))/2 for nt in range(1, 30): z, n, m, t = special.jnjnp_zeros(nt) for zz, nn, tt in zip(z, n, t): if tt == 0: assert_allclose(jn(nn, zz), 0, atol=1e-6) elif tt == 1: assert_allclose(jnp(nn, zz), 0, atol=1e-6) else: raise AssertionError("Invalid t return for nt=%d" % nt) def test_jnp_zeros(self): jnp = special.jnp_zeros(1,5) assert_array_almost_equal(jnp, array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]),4) jnp = special.jnp_zeros(443,5) assert_allclose(special.jvp(443, jnp), 0, atol=1e-15) def test_jnyn_zeros(self): jnz = special.jnyn_zeros(1,5) assert_array_almost_equal(jnz,(array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]), array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]), array([2.19714, 5.42968, 8.59601, 11.74915, 14.89744]), array([3.68302, 6.94150, 10.12340, 13.28576, 16.44006])),5) def test_jvp(self): jvprim = special.jvp(2,2) jv0 = (special.jv(1,2)-special.jv(3,2))/2 assert_almost_equal(jvprim,jv0,10) def test_k0(self): ozk = special.k0(.1) ozkr = special.kv(0,.1) assert_almost_equal(ozk,ozkr,8) def test_k0e(self): ozke = special.k0e(.1) ozker = special.kve(0,.1) assert_almost_equal(ozke,ozker,8) def test_k1(self): o1k = special.k1(.1) o1kr = special.kv(1,.1) assert_almost_equal(o1k,o1kr,8) def test_k1e(self): o1ke = special.k1e(.1) o1ker = special.kve(1,.1) assert_almost_equal(o1ke,o1ker,8) def test_jacobi(self): a = 5*np.random.random() - 1 b = 5*np.random.random() - 1 P0 = special.jacobi(0,a,b) P1 = special.jacobi(1,a,b) P2 = special.jacobi(2,a,b) P3 = special.jacobi(3,a,b) assert_array_almost_equal(P0.c,[1],13) assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13) cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)] p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]] assert_array_almost_equal(P2.c,array(p2c)/8.0,13) cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3), 12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)] p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] assert_array_almost_equal(P3.c,array(p3c)/48.0,13) def test_kn(self): kn1 = special.kn(0,.2) assert_almost_equal(kn1,1.7527038555281462,8) def test_negv_kv(self): assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2)) def test_kv0(self): kv0 = special.kv(0,.2) assert_almost_equal(kv0, 1.7527038555281462, 10) def test_kv1(self): kv1 = special.kv(1,0.2) assert_almost_equal(kv1, 4.775972543220472, 10) def test_kv2(self): kv2 = special.kv(2,0.2) assert_almost_equal(kv2, 49.51242928773287, 10) def test_kn_largeorder(self): assert_allclose(special.kn(32, 1), 1.7516596664574289e+43) def test_kv_largearg(self): assert_equal(special.kv(0, 1e19), 0) def test_negv_kve(self): assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2)) def test_kve(self): kve1 = special.kve(0,.2) kv1 = special.kv(0,.2)*exp(.2) assert_almost_equal(kve1,kv1,8) z = .2+1j kve2 = special.kve(0,z) kv2 = special.kv(0,z)*exp(z) assert_almost_equal(kve2,kv2,8) def test_kvp_v0n1(self): z = 2.2 assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10) def test_kvp_n1(self): v = 3. z = 2.2 xc = -special.kv(v+1,z) + v/z*special.kv(v,z) x = special.kvp(v,z, n=1) assert_almost_equal(xc, x, 10) # this function (kvp) is broken def test_kvp_n2(self): v = 3. z = 2.2 xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z x = special.kvp(v, z, n=2) assert_almost_equal(xc, x, 10) def test_y0(self): oz = special.y0(.1) ozr = special.yn(0,.1) assert_almost_equal(oz,ozr,8) def test_y1(self): o1 = special.y1(.1) o1r = special.yn(1,.1) assert_almost_equal(o1,o1r,8) def test_y0_zeros(self): yo,ypo = special.y0_zeros(2) zo,zpo = special.y0_zeros(2,complex=1) all = r_[yo,zo] allval = r_[ypo,zpo] assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11) assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11) def test_y1_zeros(self): y1 = special.y1_zeros(1) assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) def test_y1p_zeros(self): y1p = special.y1p_zeros(1,complex=1) assert_array_almost_equal(y1p,(array([0.5768+0.904j]), array([-0.7635+0.5892j])),3) def test_yn_zeros(self): an = special.yn_zeros(4,2) assert_array_almost_equal(an,array([5.64515, 9.36162]),5) an = special.yn_zeros(443,5) assert_allclose(an, [450.13573091578090314, 463.05692376675001542, 472.80651546418663566, 481.27353184725625838, 488.98055964441374646], rtol=1e-15) def test_ynp_zeros(self): ao = special.ynp_zeros(0,2) assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6) ao = special.ynp_zeros(43,5) assert_allclose(special.yvp(43, ao), 0, atol=1e-15) ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-9) def test_ynp_zeros_large_order(self): ao = special.ynp_zeros(443,5) assert_allclose(special.yvp(443, ao), 0, atol=1e-14) def test_yn(self): yn2n = special.yn(1,.2) assert_almost_equal(yn2n,-3.3238249881118471,8) def test_negv_yv(self): assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14) def test_yv(self): yv2 = special.yv(1,.2) assert_almost_equal(yv2,-3.3238249881118471,8) def test_negv_yve(self): assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14) def test_yve(self): yve2 = special.yve(1,.2) assert_almost_equal(yve2,-3.3238249881118471,8) yve2r = special.yv(1,.2+1j)*exp(-1) yve22 = special.yve(1,.2+1j) assert_almost_equal(yve22,yve2r,8) def test_yvp(self): yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0 yvp1 = special.yvp(2,.2) assert_array_almost_equal(yvp1,yvpr,10) def _cephes_vs_amos_points(self): """Yield points at which to compare Cephes implementation to AMOS""" # check several points, including large-amplitude ones for v in [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301]: for z in [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300, 10003]: yield v, z # check half-integers; these are problematic points at least # for cephes/iv for v in 0.5 + arange(-60, 60): yield v, 3.5 def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None): for v, z in self._cephes_vs_amos_points(): if skip is not None and skip(v, z): continue c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z) if np.isinf(c1): assert_(np.abs(c2) >= 1e300, (v, z)) elif np.isnan(c1): assert_(c2.imag != 0, (v, z)) else: assert_allclose(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol) if v == int(v): assert_allclose(c3, c2, err_msg=(v, z), rtol=rtol, atol=atol) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_jv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305) @pytest.mark.xfail(platform.machine() == 'ppc64le', reason="fails on ppc64le") def test_yv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305) def test_yv_cephes_vs_amos_only_small_orders(self): skipper = lambda v, z: (abs(v) > 50) self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305, skip=skipper) def test_iv_cephes_vs_amos(self): olderr = np.seterr(all='ignore') try: self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305) finally: np.seterr(**olderr) @pytest.mark.slow def test_iv_cephes_vs_amos_mass_test(self): N = 1000000 np.random.seed(1) v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N) x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N) imsk = (np.random.randint(8, size=N) == 0) v[imsk] = v[imsk].astype(int) old_err = np.seterr(all='ignore') try: c1 = special.iv(v, x) c2 = special.iv(v, x+0j) # deal with differences in the inf and zero cutoffs c1[abs(c1) > 1e300] = np.inf c2[abs(c2) > 1e300] = np.inf c1[abs(c1) < 1e-300] = 0 c2[abs(c2) < 1e-300] = 0 dc = abs(c1/c2 - 1) dc[np.isnan(dc)] = 0 finally: np.seterr(**old_err) k = np.argmax(dc) # Most error apparently comes from AMOS and not our implementation; # there are some problems near integer orders there assert_(dc[k] < 2e-7, (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j))) def test_kv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305) self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305) def test_ticket_623(self): assert_allclose(special.jv(3, 4), 0.43017147387562193) assert_allclose(special.jv(301, 1300), 0.0183487151115275) assert_allclose(special.jv(301, 1296.0682), -0.0224174325312048) def test_ticket_853(self): """Negative-order Bessels""" # cephes assert_allclose(special.jv(-1, 1), -0.4400505857449335) assert_allclose(special.jv(-2, 1), 0.1149034849319005) assert_allclose(special.yv(-1, 1), 0.7812128213002887) assert_allclose(special.yv(-2, 1), -1.650682606816255) assert_allclose(special.iv(-1, 1), 0.5651591039924851) assert_allclose(special.iv(-2, 1), 0.1357476697670383) assert_allclose(special.kv(-1, 1), 0.6019072301972347) assert_allclose(special.kv(-2, 1), 1.624838898635178) assert_allclose(special.jv(-0.5, 1), 0.43109886801837607952) assert_allclose(special.yv(-0.5, 1), 0.6713967071418031) assert_allclose(special.iv(-0.5, 1), 1.231200214592967) assert_allclose(special.kv(-0.5, 1), 0.4610685044478945) # amos assert_allclose(special.jv(-1, 1+0j), -0.4400505857449335) assert_allclose(special.jv(-2, 1+0j), 0.1149034849319005) assert_allclose(special.yv(-1, 1+0j), 0.7812128213002887) assert_allclose(special.yv(-2, 1+0j), -1.650682606816255) assert_allclose(special.iv(-1, 1+0j), 0.5651591039924851) assert_allclose(special.iv(-2, 1+0j), 0.1357476697670383) assert_allclose(special.kv(-1, 1+0j), 0.6019072301972347) assert_allclose(special.kv(-2, 1+0j), 1.624838898635178) assert_allclose(special.jv(-0.5, 1+0j), 0.43109886801837607952) assert_allclose(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j) assert_allclose(special.yv(-0.5, 1+0j), 0.6713967071418031) assert_allclose(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j) assert_allclose(special.iv(-0.5, 1+0j), 1.231200214592967) assert_allclose(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j) assert_allclose(special.kv(-0.5, 1+0j), 0.4610685044478945) assert_allclose(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j) assert_allclose(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3)) assert_allclose(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3)) assert_allclose(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j)) assert_allclose(special.hankel1(-0.5, 1+1j), special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j)) assert_allclose(special.hankel2(-0.5, 1+1j), special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j)) def test_ticket_854(self): """Real-valued Bessel domains""" assert_(isnan(special.jv(0.5, -1))) assert_(isnan(special.iv(0.5, -1))) assert_(isnan(special.yv(0.5, -1))) assert_(isnan(special.yv(1, -1))) assert_(isnan(special.kv(0.5, -1))) assert_(isnan(special.kv(1, -1))) assert_(isnan(special.jve(0.5, -1))) assert_(isnan(special.ive(0.5, -1))) assert_(isnan(special.yve(0.5, -1))) assert_(isnan(special.yve(1, -1))) assert_(isnan(special.kve(0.5, -1))) assert_(isnan(special.kve(1, -1))) assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1)) assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1)) def test_gh_7909(self): assert_(special.kv(1.5, 0) == np.inf) assert_(special.kve(1.5, 0) == np.inf) def test_ticket_503(self): """Real-valued Bessel I overflow""" assert_allclose(special.iv(1, 700), 1.528500390233901e302) assert_allclose(special.iv(1000, 1120), 1.301564549405821e301) def test_iv_hyperg_poles(self): assert_allclose(special.iv(-0.5, 1), 1.231200214592967) def iv_series(self, v, z, n=200): k = arange(0, n).astype(float_) r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1) r[isnan(r)] = inf r = exp(r) err = abs(r).max() * finfo(float_).eps * n + abs(r[-1])*10 return r.sum(), err def test_i0_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(0, z) assert_allclose(special.i0(z), value, atol=err, err_msg=z) def test_i1_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(1, z) assert_allclose(special.i1(z), value, atol=err, err_msg=z) def test_iv_series(self): for v in [-20., -10., -1., 0., 1., 12.49, 120.]: for z in [1., 10., 200.5, -1+2j]: value, err = self.iv_series(v, z) assert_allclose(special.iv(v, z), value, atol=err, err_msg=(v, z)) def test_i0(self): values = [[0.0, 1.0], [1e-10, 1.0], [0.1, 0.9071009258], [0.5, 0.6450352706], [1.0, 0.4657596077], [2.5, 0.2700464416], [5.0, 0.1835408126], [20.0, 0.0897803119], ] for i, (x, v) in enumerate(values): cv = special.i0(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i0e(self): oize = special.i0e(.1) oizer = special.ive(0,.1) assert_almost_equal(oize,oizer,8) def test_i1(self): values = [[0.0, 0.0], [1e-10, 0.4999999999500000e-10], [0.1, 0.0452984468], [0.5, 0.1564208032], [1.0, 0.2079104154], [5.0, 0.1639722669], [20.0, 0.0875062222], ] for i, (x, v) in enumerate(values): cv = special.i1(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i1e(self): oi1e = special.i1e(.1) oi1er = special.ive(1,.1) assert_almost_equal(oi1e,oi1er,8) def test_iti0k0(self): iti0 = array(special.iti0k0(5)) assert_array_almost_equal(iti0,array([31.848667776169801, 1.5673873907283657]),5) def test_it2i0k0(self): it2k = special.it2i0k0(.1) assert_array_almost_equal(it2k,array([0.0012503906973464409, 3.3309450354686687]),6) def test_iv(self): iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(iv1,0.90710092578230106,10) def test_negv_ive(self): assert_equal(special.ive(3,2), special.ive(-3,2)) def test_ive(self): ive1 = special.ive(0,.1) iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(ive1,iv1,10) def test_ivp0(self): assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10) def test_ivp(self): y = (special.iv(0,2) + special.iv(2,2))/2 x = special.ivp(1,2) assert_almost_equal(x,y,10) class TestLaguerre(object): def test_laguerre(self): lag0 = special.laguerre(0) lag1 = special.laguerre(1) lag2 = special.laguerre(2) lag3 = special.laguerre(3) lag4 = special.laguerre(4) lag5 = special.laguerre(5) assert_array_almost_equal(lag0.c,[1],13) assert_array_almost_equal(lag1.c,[-1,1],13) assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13) assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13) assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) def test_genlaguerre(self): k = 5*np.random.random() - 0.9 lag0 = special.genlaguerre(0,k) lag1 = special.genlaguerre(1,k) lag2 = special.genlaguerre(2,k) lag3 = special.genlaguerre(3,k) assert_equal(lag0.c,[1]) assert_equal(lag1.c,[-1,k+1]) assert_almost_equal(lag2.c,array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0) assert_almost_equal(lag3.c,array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0) # Base polynomials come from Abrahmowitz and Stegan class TestLegendre(object): def test_legendre(self): leg0 = special.legendre(0) leg1 = special.legendre(1) leg2 = special.legendre(2) leg3 = special.legendre(3) leg4 = special.legendre(4) leg5 = special.legendre(5) assert_equal(leg0.c, [1]) assert_equal(leg1.c, [1,0]) assert_almost_equal(leg2.c, array([3,0,-1])/2.0, decimal=13) assert_almost_equal(leg3.c, array([5,0,-3,0])/2.0) assert_almost_equal(leg4.c, array([35,0,-30,0,3])/8.0) assert_almost_equal(leg5.c, array([63,0,-70,0,15,0])/8.0) class TestLambda(object): def test_lmbda(self): lam = special.lmbda(1,.1) lamr = (array([special.jn(0,.1), 2*special.jn(1,.1)/.1]), array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])) assert_array_almost_equal(lam,lamr,8) class TestLog1p(object): def test_log1p(self): l1p = (special.log1p(10), special.log1p(11), special.log1p(12)) l1prl = (log(11), log(12), log(13)) assert_array_almost_equal(l1p,l1prl,8) def test_log1pmore(self): l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2)) l1pmrl = (log(2),log(2.1),log(2.2)) assert_array_almost_equal(l1pm,l1pmrl,8) class TestLegendreFunctions(object): def test_clpmn(self): z = 0.5+0.3j clp = special.clpmn(2, 2, z, 3) assert_array_almost_equal(clp, (array([[1.0000, z, 0.5*(3*z*z-1)], [0.0000, sqrt(z*z-1), 3*z*sqrt(z*z-1)], [0.0000, 0.0000, 3*(z*z-1)]]), array([[0.0000, 1.0000, 3*z], [0.0000, z/sqrt(z*z-1), 3*(2*z*z-1)/sqrt(z*z-1)], [0.0000, 0.0000, 6*z]])), 7) def test_clpmn_close_to_real_2(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x), special.lpmv(m, n, x)]), 7) def test_clpmn_close_to_real_3(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi), special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]), 7) def test_clpmn_across_unit_circle(self): eps = 1e-7 m = 1 n = 1 x = 1j for type in [2, 3]: assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n], special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6) def test_inf(self): for z in (1, -1): for n in range(4): for m in range(1, n): lp = special.clpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) lp = special.lpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) def test_deriv_clpmn(self): # data inside and outside of the unit circle zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j, 1+1j, -1+1j, -1-1j, 1-1j] m = 2 n = 3 for type in [2, 3]: for z in zvals: for h in [1e-3, 1e-3j]: approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0] - special.clpmn(m, n, z-0.5*h, type)[0])/h assert_allclose(special.clpmn(m, n, z, type)[1], approx_derivative, rtol=1e-4) def test_lpmn(self): lp = special.lpmn(0,2,.5) assert_array_almost_equal(lp,(array([[1.00000, 0.50000, -0.12500]]), array([[0.00000, 1.00000, 1.50000]])),4) def test_lpn(self): lpnf = special.lpn(2,.5) assert_array_almost_equal(lpnf,(array([1.00000, 0.50000, -0.12500]), array([0.00000, 1.00000, 1.50000])),4) def test_lpmv(self): lp = special.lpmv(0,2,.5) assert_almost_equal(lp,-0.125,7) lp = special.lpmv(0,40,.001) assert_almost_equal(lp,0.1252678976534484,7) # XXX: this is outside the domain of the current implementation, # so ensure it returns a NaN rather than a wrong answer. olderr = np.seterr(all='ignore') try: lp = special.lpmv(-1,-1,.001) finally: np.seterr(**olderr) assert_(lp != 0 or np.isnan(lp)) def test_lqmn(self): lqmnf = special.lqmn(0,2,.5) lqf = special.lqn(2,.5) assert_array_almost_equal(lqmnf[0][0],lqf[0],4) assert_array_almost_equal(lqmnf[1][0],lqf[1],4) def test_lqmn_gt1(self): """algorithm for real arguments changes at 1.0001 test against analytical result for m=2, n=1 """ x0 = 1.0001 delta = 0.00002 for x in (x0-delta, x0+delta): lq = special.lqmn(2, 1, x)[0][-1, -1] expected = 2/(x*x-1) assert_almost_equal(lq, expected) def test_lqmn_shape(self): a, b = special.lqmn(4, 4, 1.1) assert_equal(a.shape, (5, 5)) assert_equal(b.shape, (5, 5)) a, b = special.lqmn(4, 0, 1.1) assert_equal(a.shape, (5, 1)) assert_equal(b.shape, (5, 1)) def test_lqn(self): lqf = special.lqn(2,.5) assert_array_almost_equal(lqf,(array([0.5493, -0.7253, -0.8187]), array([1.3333, 1.216, -0.8427])),4) class TestMathieu(object): def test_mathieu_a(self): pass def test_mathieu_even_coef(self): special.mathieu_even_coef(2,5) # Q not defined broken and cannot figure out proper reporting order def test_mathieu_odd_coef(self): # same problem as above pass class TestFresnelIntegral(object): def test_modfresnelp(self): pass def test_modfresnelm(self): pass class TestOblCvSeq(object): def test_obl_cv_seq(self): obl = special.obl_cv_seq(0,3,1) assert_array_almost_equal(obl,array([-0.348602, 1.393206, 5.486800, 11.492120]),5) class TestParabolicCylinder(object): def test_pbdn_seq(self): pb = special.pbdn_seq(1,.1) assert_array_almost_equal(pb,(array([0.9975, 0.0998]), array([-0.0499, 0.9925])),4) def test_pbdv(self): special.pbdv(1,.2) 1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0] def test_pbdv_seq(self): pbn = special.pbdn_seq(1,.1) pbv = special.pbdv_seq(1,.1) assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) def test_pbdv_points(self): # simple case eta = np.linspace(-10, 10, 5) z = 2**(eta/2)*np.sqrt(np.pi)/special.gamma(.5-.5*eta) assert_allclose(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14) # some points assert_allclose(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12) assert_allclose(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12) def test_pbdv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbdv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) def test_pbvv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbvv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2. assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) class TestPolygamma(object): # from Table 6.2 (pg. 271) of A&S def test_polygamma(self): poly2 = special.polygamma(2,1) poly3 = special.polygamma(3,1) assert_almost_equal(poly2,-2.4041138063,10) assert_almost_equal(poly3,6.4939394023,10) # Test polygamma(0, x) == psi(x) x = [2, 3, 1.1e14] assert_almost_equal(special.polygamma(0, x), special.psi(x)) # Test broadcasting n = [0, 1, 2] x = [0.5, 1.5, 2.5] expected = [-1.9635100260214238, 0.93480220054467933, -0.23620405164172739] assert_almost_equal(special.polygamma(n, x), expected) expected = np.row_stack([expected]*2) assert_almost_equal(special.polygamma(n, np.row_stack([x]*2)), expected) assert_almost_equal(special.polygamma(np.row_stack([n]*2), x), expected) class TestProCvSeq(object): def test_pro_cv_seq(self): prol = special.pro_cv_seq(0,3,1) assert_array_almost_equal(prol,array([0.319000, 2.593084, 6.533471, 12.514462]),5) class TestPsi(object): def test_psi(self): ps = special.psi(1) assert_almost_equal(ps,-0.57721566490153287,8) class TestRadian(object): def test_radian(self): rad = special.radian(90,0,0) assert_almost_equal(rad,pi/2.0,5) def test_radianmore(self): rad1 = special.radian(90,1,60) assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) class TestRiccati(object): def test_riccati_jn(self): N, x = 2, 0.2 S = np.empty((N, N)) for n in range(N): j = special.spherical_jn(n, x) jp = special.spherical_jn(n, x, derivative=True) S[0,n] = x*j S[1,n] = x*jp + j assert_array_almost_equal(S, special.riccati_jn(n, x), 8) def test_riccati_yn(self): N, x = 2, 0.2 C = np.empty((N, N)) for n in range(N): y = special.spherical_yn(n, x) yp = special.spherical_yn(n, x, derivative=True) C[0,n] = x*y C[1,n] = x*yp + y assert_array_almost_equal(C, special.riccati_yn(n, x), 8) class TestRound(object): def test_round(self): rnd = list(map(int,(special.round(10.1),special.round(10.4),special.round(10.5),special.round(10.6)))) # Note: According to the documentation, scipy.special.round is # supposed to round to the nearest even number if the fractional # part is exactly 0.5. On some platforms, this does not appear # to work and thus this test may fail. However, this unit test is # correctly written. rndrl = (10,10,10,11) assert_array_equal(rnd,rndrl) def test_sph_harm(): # Tests derived from tables in # https://en.wikipedia.org/wiki/Table_of_spherical_harmonics sh = special.sph_harm pi = np.pi exp = np.exp sqrt = np.sqrt sin = np.sin cos = np.cos assert_array_almost_equal(sh(0,0,0,0), 0.5/sqrt(pi)) assert_array_almost_equal(sh(-2,2,0.,pi/4), 0.25*sqrt(15./(2.*pi)) * (sin(pi/4))**2.) assert_array_almost_equal(sh(-2,2,0.,pi/2), 0.25*sqrt(15./(2.*pi))) assert_array_almost_equal(sh(2,2,pi,pi/2), 0.25*sqrt(15/(2.*pi)) * exp(0+2.*pi*1j)*sin(pi/2.)**2.) assert_array_almost_equal(sh(2,4,pi/4.,pi/3.), (3./8.)*sqrt(5./(2.*pi)) * exp(0+2.*pi/4.*1j) * sin(pi/3.)**2. * (7.*cos(pi/3.)**2.-1)) assert_array_almost_equal(sh(4,4,pi/8.,pi/6.), (3./16.)*sqrt(35./(2.*pi)) * exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.) def test_sph_harm_ufunc_loop_selection(): # see https://github.com/scipy/scipy/issues/4895 dt = np.dtype(np.complex128) assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt) assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt) assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt) assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt) assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt) assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt) class TestStruve(object): def _series(self, v, z, n=100): """Compute Struve function & error estimate from its power series.""" k = arange(0, n) r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5) err = abs(r).max() * finfo(float_).eps * n return r.sum(), err def test_vs_series(self): """Check Struve function versus its power series""" for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]: for z in [1, 10, 19, 21, 30]: value, err = self._series(v, z) assert_allclose(special.struve(v, z), value, rtol=0, atol=err), (v, z) def test_some_values(self): assert_allclose(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7) assert_allclose(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8) assert_allclose(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12) assert_allclose(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11) assert_equal(special.struve(-12, -41), -special.struve(-12, 41)) assert_equal(special.struve(+12, -41), -special.struve(+12, 41)) assert_equal(special.struve(-11, -41), +special.struve(-11, 41)) assert_equal(special.struve(+11, -41), +special.struve(+11, 41)) assert_(isnan(special.struve(-7.1, -1))) assert_(isnan(special.struve(-10.1, -1))) def test_regression_679(self): """Regression test for #679""" assert_allclose(special.struve(-1.0, 20 - 1e-8), special.struve(-1.0, 20 + 1e-8)) assert_allclose(special.struve(-2.0, 20 - 1e-8), special.struve(-2.0, 20 + 1e-8)) assert_allclose(special.struve(-4.3, 20 - 1e-8), special.struve(-4.3, 20 + 1e-8)) def test_chi2_smalldf(): assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110) def test_ch2_inf(): assert_equal(special.chdtr(0.7,np.inf), 1.0) def test_chi2c_smalldf(): assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110) def test_chi2_inv_smalldf(): assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3) def test_agm_simple(): rtol = 1e-13 # Gauss's constant assert_allclose(1/special.agm(1, np.sqrt(2)), 0.834626841674073186, rtol=rtol) # These values were computed using Wolfram Alpha, with the # function ArithmeticGeometricMean[a, b]. agm13 = 1.863616783244897 agm15 = 2.604008190530940 agm35 = 3.936235503649555 assert_allclose(special.agm([[1], [3]], [1, 3, 5]), [[1, agm13, agm15], [agm13, 3, agm35]], rtol=rtol) # Computed by the iteration formula using mpmath, # with mpmath.mp.prec = 1000: agm12 = 1.4567910310469068 assert_allclose(special.agm(1, 2), agm12, rtol=rtol) assert_allclose(special.agm(2, 1), agm12, rtol=rtol) assert_allclose(special.agm(-1, -2), -agm12, rtol=rtol) assert_allclose(special.agm(24, 6), 13.458171481725614, rtol=rtol) assert_allclose(special.agm(13, 123456789.5), 11111458.498599306, rtol=rtol) assert_allclose(special.agm(1e30, 1), 2.229223055945383e+28, rtol=rtol) assert_allclose(special.agm(1e-22, 1), 0.030182566420169886, rtol=rtol) assert_allclose(special.agm(1e150, 1e180), 2.229223055945383e+178, rtol=rtol) assert_allclose(special.agm(1e180, 1e-150), 2.0634722510162677e+177, rtol=rtol) assert_allclose(special.agm(1e-150, 1e-170), 3.3112619670463756e-152, rtol=rtol) fi = np.finfo(1.0) assert_allclose(special.agm(fi.tiny, fi.max), 1.9892072050015473e+305, rtol=rtol) assert_allclose(special.agm(0.75*fi.max, fi.max), 1.564904312298045e+308, rtol=rtol) assert_allclose(special.agm(fi.tiny, 3*fi.tiny), 4.1466849866735005e-308, rtol=rtol) # zero, nan and inf cases. assert_equal(special.agm(0, 0), 0) assert_equal(special.agm(99, 0), 0) assert_equal(special.agm(-1, 10), np.nan) assert_equal(special.agm(0, np.inf), np.nan) assert_equal(special.agm(np.inf, 0), np.nan) assert_equal(special.agm(0, -np.inf), np.nan) assert_equal(special.agm(-np.inf, 0), np.nan) assert_equal(special.agm(np.inf, -np.inf), np.nan) assert_equal(special.agm(-np.inf, np.inf), np.nan) assert_equal(special.agm(1, np.nan), np.nan) assert_equal(special.agm(np.nan, -1), np.nan) assert_equal(special.agm(1, np.inf), np.inf) assert_equal(special.agm(np.inf, 1), np.inf) assert_equal(special.agm(-1, -np.inf), -np.inf) assert_equal(special.agm(-np.inf, -1), -np.inf) def test_legacy(): # Legacy behavior: truncating arguments to integers with suppress_warnings() as sup: sup.filter(RuntimeWarning, "floating point number truncated to an integer") assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3)) assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3)) assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3)) assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3)) assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3)) assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3)) assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3)) assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3)) assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3)) @with_special_errors def test_error_raising(): assert_raises(special.SpecialFunctionError, special.iv, 1, 1e99j) def test_xlogy(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x*np.log(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float) z2 = np.r_[z1, [(0, 1j), (1, 1j)]] w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13) w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1]) assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13) def test_xlog1py(): def xfunc(x, y): with np.errstate(invalid='ignore'): if x == 0 and not np.isnan(y): return x else: return x * np.log1p(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0), (1, 1e-30)], dtype=float) w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13) def test_entr(): def xfunc(x): if x < 0: return -np.inf else: return -special.xlogy(x, x) values = (0, 0.5, 1.0, np.inf) signs = [-1, 1] arr = [] for sgn, v in itertools.product(signs, values): arr.append(sgn * v) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z) assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13) def test_kl_div(): def xfunc(x, y): if x < 0 or y < 0 or (y == 0 and x != 0): # extension of natural domain to preserve convexity return np.inf elif np.isposinf(x) or np.isposinf(y): # limits within the natural domain return np.inf elif x == 0: return y else: return special.xlogy(x, x/y) - x + y values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13) def test_rel_entr(): def xfunc(x, y): if x > 0 and y > 0: return special.xlogy(x, x/y) elif x == 0 and y >= 0: return 0 else: return np.inf values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13) def test_huber(): assert_equal(special.huber(-1, 1.5), np.inf) assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5)) assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2)) def xfunc(delta, r): if delta < 0: return np.inf elif np.abs(r) < delta: return 0.5 * np.square(r) else: return delta * (np.abs(r) - 0.5 * delta) z = np.random.randn(10, 2) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13) def test_pseudo_huber(): def xfunc(delta, r): if delta < 0: return np.inf elif (not delta) or (not r): return 0 else: return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1) z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]]) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13)
aeklant/scipy
scipy/special/tests/test_basic.py
scipy/special/_precompute/loggamma.py
"""Describe group states.""" from homeassistant.components.group import GroupIntegrationRegistry from homeassistant.const import STATE_LOCKED, STATE_UNLOCKED from homeassistant.core import callback from homeassistant.helpers.typing import HomeAssistantType @callback def async_describe_on_off_states( hass: HomeAssistantType, registry: GroupIntegrationRegistry ) -> None: """Describe group on off states.""" registry.on_off_states({STATE_LOCKED}, STATE_UNLOCKED)
"""The tests for Lock device triggers.""" import pytest import homeassistant.components.automation as automation from homeassistant.components.lock import DOMAIN from homeassistant.const import STATE_LOCKED, STATE_UNLOCKED from homeassistant.helpers import device_registry from homeassistant.setup import async_setup_component from tests.common import ( MockConfigEntry, assert_lists_same, async_get_device_automations, async_mock_service, mock_device_registry, mock_registry, ) @pytest.fixture def device_reg(hass): """Return an empty, loaded, registry.""" return mock_device_registry(hass) @pytest.fixture def entity_reg(hass): """Return an empty, loaded, registry.""" return mock_registry(hass) @pytest.fixture def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation") async def test_get_triggers(hass, device_reg, entity_reg): """Test we get the expected triggers from a lock.""" config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_reg.async_get_or_create(DOMAIN, "test", "5678", device_id=device_entry.id) expected_triggers = [ { "platform": "device", "domain": DOMAIN, "type": "locked", "device_id": device_entry.id, "entity_id": f"{DOMAIN}.test_5678", }, { "platform": "device", "domain": DOMAIN, "type": "unlocked", "device_id": device_entry.id, "entity_id": f"{DOMAIN}.test_5678", }, ] triggers = await async_get_device_automations(hass, "trigger", device_entry.id) assert_lists_same(triggers, expected_triggers) async def test_if_fires_on_state_change(hass, calls): """Test for turn_on and turn_off triggers firing.""" hass.states.async_set("lock.entity", STATE_UNLOCKED) assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": "lock.entity", "type": "locked", }, "action": { "service": "test.automation", "data_template": { "some": ( "locked - {{ trigger.platform}} - " "{{ trigger.entity_id}} - {{ trigger.from_state.state}} - " "{{ trigger.to_state.state}} - {{ trigger.for }}" ) }, }, }, { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": "lock.entity", "type": "unlocked", }, "action": { "service": "test.automation", "data_template": { "some": ( "unlocked - {{ trigger.platform}} - " "{{ trigger.entity_id}} - {{ trigger.from_state.state}} - " "{{ trigger.to_state.state}} - {{ trigger.for }}" ) }, }, }, ] }, ) # Fake that the entity is turning on. hass.states.async_set("lock.entity", STATE_LOCKED) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0].data[ "some" ] == "locked - device - {} - unlocked - locked - None".format("lock.entity") # Fake that the entity is turning off. hass.states.async_set("lock.entity", STATE_UNLOCKED) await hass.async_block_till_done() assert len(calls) == 2 assert calls[1].data[ "some" ] == "unlocked - device - {} - locked - unlocked - None".format("lock.entity")
mezz64/home-assistant
tests/components/lock/test_device_trigger.py
homeassistant/components/lock/group.py
from typing import List, cast import numpy as np from pandas._typing import FilePathOrBuffer, Scalar, StorageOptions from pandas.compat._optional import import_optional_dependency import pandas as pd from pandas.io.excel._base import BaseExcelReader class ODFReader(BaseExcelReader): """ Read tables out of OpenDocument formatted files. Parameters ---------- filepath_or_buffer : string, path to be parsed or an open readable stream. storage_options : dict, optional passed to fsspec for appropriate URLs (see ``_get_filepath_or_buffer``) """ def __init__( self, filepath_or_buffer: FilePathOrBuffer, storage_options: StorageOptions = None, ): import_optional_dependency("odf") super().__init__(filepath_or_buffer, storage_options=storage_options) @property def _workbook_class(self): from odf.opendocument import OpenDocument return OpenDocument def load_workbook(self, filepath_or_buffer: FilePathOrBuffer): from odf.opendocument import load return load(filepath_or_buffer) @property def empty_value(self) -> str: """Property for compat with other readers.""" return "" @property def sheet_names(self) -> List[str]: """Return a list of sheet names present in the document""" from odf.table import Table tables = self.book.getElementsByType(Table) return [t.getAttribute("name") for t in tables] def get_sheet_by_index(self, index: int): from odf.table import Table tables = self.book.getElementsByType(Table) return tables[index] def get_sheet_by_name(self, name: str): from odf.table import Table tables = self.book.getElementsByType(Table) for table in tables: if table.getAttribute("name") == name: return table self.close() raise ValueError(f"sheet {name} not found") def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]: """ Parse an ODF Table into a list of lists """ from odf.table import CoveredTableCell, TableCell, TableRow covered_cell_name = CoveredTableCell().qname table_cell_name = TableCell().qname cell_names = {covered_cell_name, table_cell_name} sheet_rows = sheet.getElementsByType(TableRow) empty_rows = 0 max_row_len = 0 table: List[List[Scalar]] = [] for i, sheet_row in enumerate(sheet_rows): sheet_cells = [x for x in sheet_row.childNodes if x.qname in cell_names] empty_cells = 0 table_row: List[Scalar] = [] for j, sheet_cell in enumerate(sheet_cells): if sheet_cell.qname == table_cell_name: value = self._get_cell_value(sheet_cell, convert_float) else: value = self.empty_value column_repeat = self._get_column_repeat(sheet_cell) # Queue up empty values, writing only if content succeeds them if value == self.empty_value: empty_cells += column_repeat else: table_row.extend([self.empty_value] * empty_cells) empty_cells = 0 table_row.extend([value] * column_repeat) if max_row_len < len(table_row): max_row_len = len(table_row) row_repeat = self._get_row_repeat(sheet_row) if self._is_empty_row(sheet_row): empty_rows += row_repeat else: # add blank rows to our table table.extend([[self.empty_value]] * empty_rows) empty_rows = 0 for _ in range(row_repeat): table.append(table_row) # Make our table square for row in table: if len(row) < max_row_len: row.extend([self.empty_value] * (max_row_len - len(row))) return table def _get_row_repeat(self, row) -> int: """ Return number of times this row was repeated Repeating an empty row appeared to be a common way of representing sparse rows in the table. """ from odf.namespaces import TABLENS return int(row.attributes.get((TABLENS, "number-rows-repeated"), 1)) def _get_column_repeat(self, cell) -> int: from odf.namespaces import TABLENS return int(cell.attributes.get((TABLENS, "number-columns-repeated"), 1)) def _is_empty_row(self, row) -> bool: """ Helper function to find empty rows """ for column in row.childNodes: if len(column.childNodes) > 0: return False return True def _get_cell_value(self, cell, convert_float: bool) -> Scalar: from odf.namespaces import OFFICENS if str(cell) == "#N/A": return np.nan cell_type = cell.attributes.get((OFFICENS, "value-type")) if cell_type == "boolean": if str(cell) == "TRUE": return True return False if cell_type is None: return self.empty_value elif cell_type == "float": # GH5394 cell_value = float(cell.attributes.get((OFFICENS, "value"))) if convert_float: val = int(cell_value) if val == cell_value: return val return cell_value elif cell_type == "percentage": cell_value = cell.attributes.get((OFFICENS, "value")) return float(cell_value) elif cell_type == "string": return self._get_cell_string_value(cell) elif cell_type == "currency": cell_value = cell.attributes.get((OFFICENS, "value")) return float(cell_value) elif cell_type == "date": cell_value = cell.attributes.get((OFFICENS, "date-value")) return pd.to_datetime(cell_value) elif cell_type == "time": result = pd.to_datetime(str(cell)) result = cast(pd.Timestamp, result) return result.time() else: self.close() raise ValueError(f"Unrecognized type {cell_type}") def _get_cell_string_value(self, cell) -> str: """ Find and decode OpenDocument text:s tags that represent a run length encoded sequence of space characters. """ from odf.element import Element from odf.namespaces import TEXTNS from odf.text import S text_s = S().qname value = [] for fragment in cell.childNodes: if isinstance(fragment, Element): if fragment.qname == text_s: spaces = int(fragment.attributes.get((TEXTNS, "c"), 1)) value.append(" " * spaces) else: # recursive impl needed in case of nested fragments # with multiple spaces # https://github.com/pandas-dev/pandas/pull/36175#discussion_r484639704 value.append(self._get_cell_string_value(fragment)) else: value.append(str(fragment)) return "".join(value)
import numpy as np import pytest import pandas as pd import pandas._testing as tm dtypes = [ "int64", "Int64", {"A": "int64", "B": "Int64"}, ] @pytest.mark.parametrize("dtype", dtypes) def test_unary_unary(dtype): # unary input, unary output values = np.array([[-1, -1], [1, 1]], dtype="int64") df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype) result = np.positive(df) expected = pd.DataFrame( np.positive(values), index=df.index, columns=df.columns ).astype(dtype) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", dtypes) def test_unary_binary(request, dtype): # unary input, binary output if pd.api.types.is_extension_array_dtype(dtype) or isinstance(dtype, dict): request.node.add_marker( pytest.mark.xfail( reason="Extension / mixed with multiple outputs not implemented." ) ) values = np.array([[-1, -1], [1, 1]], dtype="int64") df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype) result_pandas = np.modf(df) assert isinstance(result_pandas, tuple) assert len(result_pandas) == 2 expected_numpy = np.modf(values) for result, b in zip(result_pandas, expected_numpy): expected = pd.DataFrame(b, index=df.index, columns=df.columns) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", dtypes) def test_binary_input_dispatch_binop(dtype): # binop ufuncs are dispatched to our dunder methods. values = np.array([[-1, -1], [1, 1]], dtype="int64") df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype) result = np.add(df, df) expected = pd.DataFrame( np.add(values, values), index=df.index, columns=df.columns ).astype(dtype) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype_a", dtypes) @pytest.mark.parametrize("dtype_b", dtypes) def test_binary_input_aligns_columns(request, dtype_a, dtype_b): if ( pd.api.types.is_extension_array_dtype(dtype_a) or isinstance(dtype_a, dict) or pd.api.types.is_extension_array_dtype(dtype_b) or isinstance(dtype_b, dict) ): request.node.add_marker( pytest.mark.xfail( reason="Extension / mixed with multiple inputs not implemented." ) ) df1 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}).astype(dtype_a) if isinstance(dtype_a, dict) and isinstance(dtype_b, dict): dtype_b["C"] = dtype_b.pop("B") df2 = pd.DataFrame({"A": [1, 2], "C": [3, 4]}).astype(dtype_b) result = np.heaviside(df1, df2) expected = np.heaviside( np.array([[1, 3, np.nan], [2, 4, np.nan]]), np.array([[1, np.nan, 3], [2, np.nan, 4]]), ) expected = pd.DataFrame(expected, index=[0, 1], columns=["A", "B", "C"]) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", dtypes) def test_binary_input_aligns_index(request, dtype): if pd.api.types.is_extension_array_dtype(dtype) or isinstance(dtype, dict): request.node.add_marker( pytest.mark.xfail( reason="Extension / mixed with multiple inputs not implemented." ) ) df1 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=["a", "b"]).astype(dtype) df2 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=["a", "c"]).astype(dtype) result = np.heaviside(df1, df2) expected = np.heaviside( np.array([[1, 3], [3, 4], [np.nan, np.nan]]), np.array([[1, 3], [np.nan, np.nan], [3, 4]]), ) # TODO(FloatArray): this will be Float64Dtype. expected = pd.DataFrame(expected, index=["a", "b", "c"], columns=["A", "B"]) tm.assert_frame_equal(result, expected) def test_binary_frame_series_raises(): # We don't currently implement df = pd.DataFrame({"A": [1, 2]}) with pytest.raises(NotImplementedError, match="logaddexp"): np.logaddexp(df, df["A"]) with pytest.raises(NotImplementedError, match="logaddexp"): np.logaddexp(df["A"], df) def test_frame_outer_deprecated(): df = pd.DataFrame({"A": [1, 2]}) with tm.assert_produces_warning(FutureWarning): np.subtract.outer(df, df)
jreback/pandas
pandas/tests/frame/test_ufunc.py
pandas/io/excel/_odfreader.py
""" Helpers for configuring locale settings. Name `localization` is chosen to avoid overlap with builtin `locale` module. """ from contextlib import contextmanager import locale import re import subprocess from pandas._config.config import options @contextmanager def set_locale(new_locale, lc_var: int = locale.LC_ALL): """ Context manager for temporarily setting a locale. Parameters ---------- new_locale : str or tuple A string of the form <language_country>.<encoding>. For example to set the current locale to US English with a UTF8 encoding, you would pass "en_US.UTF-8". lc_var : int, default `locale.LC_ALL` The category of the locale being set. Notes ----- This is useful when you want to run a particular block of code under a particular locale, without globally setting the locale. This probably isn't thread-safe. """ current_locale = locale.getlocale() try: locale.setlocale(lc_var, new_locale) normalized_locale = locale.getlocale() if all(x is not None for x in normalized_locale): yield ".".join(normalized_locale) else: yield new_locale finally: locale.setlocale(lc_var, current_locale) def can_set_locale(lc: str, lc_var: int = locale.LC_ALL) -> bool: """ Check to see if we can set a locale, and subsequently get the locale, without raising an Exception. Parameters ---------- lc : str The locale to attempt to set. lc_var : int, default `locale.LC_ALL` The category of the locale being set. Returns ------- bool Whether the passed locale can be set """ try: with set_locale(lc, lc_var=lc_var): pass except (ValueError, locale.Error): # horrible name for a Exception subclass return False else: return True def _valid_locales(locales, normalize): """ Return a list of normalized locales that do not throw an ``Exception`` when set. Parameters ---------- locales : str A string where each locale is separated by a newline. normalize : bool Whether to call ``locale.normalize`` on each locale. Returns ------- valid_locales : list A list of valid locales. """ return [ loc for loc in ( locale.normalize(loc.strip()) if normalize else loc.strip() for loc in locales ) if can_set_locale(loc) ] def _default_locale_getter(): return subprocess.check_output(["locale -a"], shell=True) def get_locales(prefix=None, normalize=True, locale_getter=_default_locale_getter): """ Get all the locales that are available on the system. Parameters ---------- prefix : str If not ``None`` then return only those locales with the prefix provided. For example to get all English language locales (those that start with ``"en"``), pass ``prefix="en"``. normalize : bool Call ``locale.normalize`` on the resulting list of available locales. If ``True``, only locales that can be set without throwing an ``Exception`` are returned. locale_getter : callable The function to use to retrieve the current locales. This should return a string with each locale separated by a newline character. Returns ------- locales : list of strings A list of locale strings that can be set with ``locale.setlocale()``. For example:: locale.setlocale(locale.LC_ALL, locale_string) On error will return None (no locale available, e.g. Windows) """ try: raw_locales = locale_getter() except subprocess.CalledProcessError: # Raised on (some? all?) Windows platforms because Note: "locale -a" # is not defined return None try: # raw_locales is "\n" separated list of locales # it may contain non-decodable parts, so split # extract what we can and then rejoin. raw_locales = raw_locales.split(b"\n") out_locales = [] for x in raw_locales: try: out_locales.append(str(x, encoding=options.display.encoding)) except UnicodeError: # 'locale -a' is used to populated 'raw_locales' and on # Redhat 7 Linux (and maybe others) prints locale names # using windows-1252 encoding. Bug only triggered by # a few special characters and when there is an # extensive list of installed locales. out_locales.append(str(x, encoding="windows-1252")) except TypeError: pass if prefix is None: return _valid_locales(out_locales, normalize) pattern = re.compile(f"{prefix}.*") found = pattern.findall("\n".join(out_locales)) return _valid_locales(found, normalize)
import numpy as np import pytest import pandas as pd import pandas._testing as tm dtypes = [ "int64", "Int64", {"A": "int64", "B": "Int64"}, ] @pytest.mark.parametrize("dtype", dtypes) def test_unary_unary(dtype): # unary input, unary output values = np.array([[-1, -1], [1, 1]], dtype="int64") df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype) result = np.positive(df) expected = pd.DataFrame( np.positive(values), index=df.index, columns=df.columns ).astype(dtype) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", dtypes) def test_unary_binary(request, dtype): # unary input, binary output if pd.api.types.is_extension_array_dtype(dtype) or isinstance(dtype, dict): request.node.add_marker( pytest.mark.xfail( reason="Extension / mixed with multiple outputs not implemented." ) ) values = np.array([[-1, -1], [1, 1]], dtype="int64") df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype) result_pandas = np.modf(df) assert isinstance(result_pandas, tuple) assert len(result_pandas) == 2 expected_numpy = np.modf(values) for result, b in zip(result_pandas, expected_numpy): expected = pd.DataFrame(b, index=df.index, columns=df.columns) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", dtypes) def test_binary_input_dispatch_binop(dtype): # binop ufuncs are dispatched to our dunder methods. values = np.array([[-1, -1], [1, 1]], dtype="int64") df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype) result = np.add(df, df) expected = pd.DataFrame( np.add(values, values), index=df.index, columns=df.columns ).astype(dtype) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype_a", dtypes) @pytest.mark.parametrize("dtype_b", dtypes) def test_binary_input_aligns_columns(request, dtype_a, dtype_b): if ( pd.api.types.is_extension_array_dtype(dtype_a) or isinstance(dtype_a, dict) or pd.api.types.is_extension_array_dtype(dtype_b) or isinstance(dtype_b, dict) ): request.node.add_marker( pytest.mark.xfail( reason="Extension / mixed with multiple inputs not implemented." ) ) df1 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}).astype(dtype_a) if isinstance(dtype_a, dict) and isinstance(dtype_b, dict): dtype_b["C"] = dtype_b.pop("B") df2 = pd.DataFrame({"A": [1, 2], "C": [3, 4]}).astype(dtype_b) result = np.heaviside(df1, df2) expected = np.heaviside( np.array([[1, 3, np.nan], [2, 4, np.nan]]), np.array([[1, np.nan, 3], [2, np.nan, 4]]), ) expected = pd.DataFrame(expected, index=[0, 1], columns=["A", "B", "C"]) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", dtypes) def test_binary_input_aligns_index(request, dtype): if pd.api.types.is_extension_array_dtype(dtype) or isinstance(dtype, dict): request.node.add_marker( pytest.mark.xfail( reason="Extension / mixed with multiple inputs not implemented." ) ) df1 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=["a", "b"]).astype(dtype) df2 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=["a", "c"]).astype(dtype) result = np.heaviside(df1, df2) expected = np.heaviside( np.array([[1, 3], [3, 4], [np.nan, np.nan]]), np.array([[1, 3], [np.nan, np.nan], [3, 4]]), ) # TODO(FloatArray): this will be Float64Dtype. expected = pd.DataFrame(expected, index=["a", "b", "c"], columns=["A", "B"]) tm.assert_frame_equal(result, expected) def test_binary_frame_series_raises(): # We don't currently implement df = pd.DataFrame({"A": [1, 2]}) with pytest.raises(NotImplementedError, match="logaddexp"): np.logaddexp(df, df["A"]) with pytest.raises(NotImplementedError, match="logaddexp"): np.logaddexp(df["A"], df) def test_frame_outer_deprecated(): df = pd.DataFrame({"A": [1, 2]}) with tm.assert_produces_warning(FutureWarning): np.subtract.outer(df, df)
jreback/pandas
pandas/tests/frame/test_ufunc.py
pandas/_config/localization.py
from typing import Optional, Type import pytest import pandas as pd import pandas._testing as tm from pandas.core import ops from .base import BaseExtensionTests class BaseOpsUtil(BaseExtensionTests): def get_op_from_name(self, op_name): return tm.get_op_from_name(op_name) def check_opname(self, s, op_name, other, exc=Exception): op = self.get_op_from_name(op_name) self._check_op(s, op, other, op_name, exc) def _check_op(self, s, op, other, op_name, exc=NotImplementedError): if exc is None: result = op(s, other) if isinstance(s, pd.DataFrame): if len(s.columns) != 1: raise NotImplementedError expected = s.iloc[:, 0].combine(other, op).to_frame() self.assert_frame_equal(result, expected) else: expected = s.combine(other, op) self.assert_series_equal(result, expected) else: with pytest.raises(exc): op(s, other) def _check_divmod_op(self, s, op, other, exc=Exception): # divmod has multiple return values, so check separately if exc is None: result_div, result_mod = op(s, other) if op is divmod: expected_div, expected_mod = s // other, s % other else: expected_div, expected_mod = other // s, other % s self.assert_series_equal(result_div, expected_div) self.assert_series_equal(result_mod, expected_mod) else: with pytest.raises(exc): divmod(s, other) class BaseArithmeticOpsTests(BaseOpsUtil): """ Various Series and DataFrame arithmetic ops methods. Subclasses supporting various ops should set the class variables to indicate that they support ops of that kind * series_scalar_exc = TypeError * frame_scalar_exc = TypeError * series_array_exc = TypeError * divmod_exc = TypeError """ series_scalar_exc: Optional[Type[TypeError]] = TypeError frame_scalar_exc: Optional[Type[TypeError]] = TypeError series_array_exc: Optional[Type[TypeError]] = TypeError divmod_exc: Optional[Type[TypeError]] = TypeError def test_arith_series_with_scalar(self, data, all_arithmetic_operators): # series & scalar op_name = all_arithmetic_operators s = pd.Series(data) self.check_opname(s, op_name, s.iloc[0], exc=self.series_scalar_exc) @pytest.mark.xfail(run=False, reason="_reduce needs implementation") def test_arith_frame_with_scalar(self, data, all_arithmetic_operators): # frame & scalar op_name = all_arithmetic_operators df = pd.DataFrame({"A": data}) self.check_opname(df, op_name, data[0], exc=self.frame_scalar_exc) def test_arith_series_with_array(self, data, all_arithmetic_operators): # ndarray & other series op_name = all_arithmetic_operators s = pd.Series(data) self.check_opname( s, op_name, pd.Series([s.iloc[0]] * len(s)), exc=self.series_array_exc ) def test_divmod(self, data): s = pd.Series(data) self._check_divmod_op(s, divmod, 1, exc=self.divmod_exc) self._check_divmod_op(1, ops.rdivmod, s, exc=self.divmod_exc) def test_divmod_series_array(self, data, data_for_twos): s = pd.Series(data) self._check_divmod_op(s, divmod, data) other = data_for_twos self._check_divmod_op(other, ops.rdivmod, s) other = pd.Series(other) self._check_divmod_op(other, ops.rdivmod, s) def test_add_series_with_extension_array(self, data): s = pd.Series(data) result = s + data expected = pd.Series(data + data) self.assert_series_equal(result, expected) def test_error(self, data, all_arithmetic_operators): # invalid ops op_name = all_arithmetic_operators with pytest.raises(AttributeError): getattr(data, op_name) @pytest.mark.parametrize("box", [pd.Series, pd.DataFrame]) def test_direct_arith_with_ndframe_returns_not_implemented(self, data, box): # EAs should return NotImplemented for ops with Series/DataFrame # Pandas takes care of unboxing the series and calling the EA's op. other = pd.Series(data) if box is pd.DataFrame: other = other.to_frame() if hasattr(data, "__add__"): result = data.__add__(other) assert result is NotImplemented else: raise pytest.skip(f"{type(data).__name__} does not implement add") class BaseComparisonOpsTests(BaseOpsUtil): """Various Series and DataFrame comparison ops methods.""" def _compare_other(self, s, data, op_name, other): op = self.get_op_from_name(op_name) if op_name == "__eq__": assert not op(s, other).all() elif op_name == "__ne__": assert op(s, other).all() else: # array assert getattr(data, op_name)(other) is NotImplemented # series s = pd.Series(data) with pytest.raises(TypeError): op(s, other) def test_compare_scalar(self, data, all_compare_operators): op_name = all_compare_operators s = pd.Series(data) self._compare_other(s, data, op_name, 0) def test_compare_array(self, data, all_compare_operators): op_name = all_compare_operators s = pd.Series(data) other = pd.Series([data[0]] * len(data)) self._compare_other(s, data, op_name, other) @pytest.mark.parametrize("box", [pd.Series, pd.DataFrame]) def test_direct_arith_with_ndframe_returns_not_implemented(self, data, box): # EAs should return NotImplemented for ops with Series/DataFrame # Pandas takes care of unboxing the series and calling the EA's op. other = pd.Series(data) if box is pd.DataFrame: other = other.to_frame() if hasattr(data, "__eq__"): result = data.__eq__(other) assert result is NotImplemented else: raise pytest.skip(f"{type(data).__name__} does not implement __eq__") if hasattr(data, "__ne__"): result = data.__ne__(other) assert result is NotImplemented else: raise pytest.skip(f"{type(data).__name__} does not implement __ne__") class BaseUnaryOpsTests(BaseOpsUtil): def test_invert(self, data): s = pd.Series(data, name="name") result = ~s expected = pd.Series(~data, name="name") self.assert_series_equal(result, expected)
import numpy as np import pytest import pandas as pd import pandas._testing as tm dtypes = [ "int64", "Int64", {"A": "int64", "B": "Int64"}, ] @pytest.mark.parametrize("dtype", dtypes) def test_unary_unary(dtype): # unary input, unary output values = np.array([[-1, -1], [1, 1]], dtype="int64") df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype) result = np.positive(df) expected = pd.DataFrame( np.positive(values), index=df.index, columns=df.columns ).astype(dtype) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", dtypes) def test_unary_binary(request, dtype): # unary input, binary output if pd.api.types.is_extension_array_dtype(dtype) or isinstance(dtype, dict): request.node.add_marker( pytest.mark.xfail( reason="Extension / mixed with multiple outputs not implemented." ) ) values = np.array([[-1, -1], [1, 1]], dtype="int64") df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype) result_pandas = np.modf(df) assert isinstance(result_pandas, tuple) assert len(result_pandas) == 2 expected_numpy = np.modf(values) for result, b in zip(result_pandas, expected_numpy): expected = pd.DataFrame(b, index=df.index, columns=df.columns) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", dtypes) def test_binary_input_dispatch_binop(dtype): # binop ufuncs are dispatched to our dunder methods. values = np.array([[-1, -1], [1, 1]], dtype="int64") df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype) result = np.add(df, df) expected = pd.DataFrame( np.add(values, values), index=df.index, columns=df.columns ).astype(dtype) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype_a", dtypes) @pytest.mark.parametrize("dtype_b", dtypes) def test_binary_input_aligns_columns(request, dtype_a, dtype_b): if ( pd.api.types.is_extension_array_dtype(dtype_a) or isinstance(dtype_a, dict) or pd.api.types.is_extension_array_dtype(dtype_b) or isinstance(dtype_b, dict) ): request.node.add_marker( pytest.mark.xfail( reason="Extension / mixed with multiple inputs not implemented." ) ) df1 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}).astype(dtype_a) if isinstance(dtype_a, dict) and isinstance(dtype_b, dict): dtype_b["C"] = dtype_b.pop("B") df2 = pd.DataFrame({"A": [1, 2], "C": [3, 4]}).astype(dtype_b) result = np.heaviside(df1, df2) expected = np.heaviside( np.array([[1, 3, np.nan], [2, 4, np.nan]]), np.array([[1, np.nan, 3], [2, np.nan, 4]]), ) expected = pd.DataFrame(expected, index=[0, 1], columns=["A", "B", "C"]) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", dtypes) def test_binary_input_aligns_index(request, dtype): if pd.api.types.is_extension_array_dtype(dtype) or isinstance(dtype, dict): request.node.add_marker( pytest.mark.xfail( reason="Extension / mixed with multiple inputs not implemented." ) ) df1 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=["a", "b"]).astype(dtype) df2 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=["a", "c"]).astype(dtype) result = np.heaviside(df1, df2) expected = np.heaviside( np.array([[1, 3], [3, 4], [np.nan, np.nan]]), np.array([[1, 3], [np.nan, np.nan], [3, 4]]), ) # TODO(FloatArray): this will be Float64Dtype. expected = pd.DataFrame(expected, index=["a", "b", "c"], columns=["A", "B"]) tm.assert_frame_equal(result, expected) def test_binary_frame_series_raises(): # We don't currently implement df = pd.DataFrame({"A": [1, 2]}) with pytest.raises(NotImplementedError, match="logaddexp"): np.logaddexp(df, df["A"]) with pytest.raises(NotImplementedError, match="logaddexp"): np.logaddexp(df["A"], df) def test_frame_outer_deprecated(): df = pd.DataFrame({"A": [1, 2]}) with tm.assert_produces_warning(FutureWarning): np.subtract.outer(df, df)
jreback/pandas
pandas/tests/frame/test_ufunc.py
pandas/tests/extension/base/ops.py
"""Core functionality for starting, restarting, and stopping a selenium browser.""" import atexit import json import os import threading import urllib2 from contextlib import contextmanager from shutil import rmtree from string import Template from tempfile import mkdtemp from threading import Timer import requests from selenium import webdriver from selenium.common.exceptions import UnexpectedAlertPresentException, WebDriverException from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from fixtures.pytest_store import store, write_line from utils import conf, tries from utils.log import logger from utils.path import data_path # Conditional guards against getting a new thread_locals when this module is reloaded. if 'thread_locals' not in globals(): # New threads get their own browser instances thread_locals = threading.local() thread_locals.browser = None thread_locals.wharf = None #: After starting a firefox browser, this will be set to the temporary #: directory where files are downloaded. firefox_profile_tmpdir = None def browser(): """callable that will always return the current browser instance If ``None``, no browser is running. Returns: The current browser instance. """ return thread_locals.browser def wharf(): return thread_locals.wharf def ensure_browser_open(): """Ensures that there is a browser instance currently open Will reuse an existing browser or start a new one as-needed Returns: The current browser instance. """ try: browser().current_url except UnexpectedAlertPresentException: # Try to handle an open alert, restart the browser if possible try: browser().switch_to_alert().dismiss() except: start() except: # If we couldn't poke the browser for any other reason, start a new one start() if thread_locals.wharf: thread_locals.wharf.renew() return browser() def start(webdriver_name=None, base_url=None, **kwargs): """Starts a new web browser If a previous browser was open, it will be closed before starting the new browser Args: webdriver_name: The name of the selenium Webdriver to use. Default: 'Firefox' base_url: Optional, will use ``utils.conf.env['base_url']`` by default **kwargs: Any additional keyword arguments will be passed to the webdriver constructor """ # Try to clean up an existing browser session if starting a new one if thread_locals.browser is not None: quit() browser_conf = conf.env.get('browser', {}) if webdriver_name is None: # If unset, look to the config for the webdriver type # defaults to Firefox webdriver_name = browser_conf.get('webdriver', 'Firefox') webdriver_class = getattr(webdriver, webdriver_name) if base_url is None: base_url = store.base_url # Pull in browser kwargs from browser yaml browser_kwargs = browser_conf.get('webdriver_options', {}) # Handle firefox profile for Firefox or Remote webdriver if webdriver_name == 'Firefox': browser_kwargs['firefox_profile'] = _load_firefox_profile() elif (webdriver_name == 'Remote' and browser_kwargs['desired_capabilities']['browserName'] == 'firefox'): browser_kwargs['browser_profile'] = _load_firefox_profile() # Update it with passed-in options/overrides browser_kwargs.update(kwargs) if webdriver_name != 'Remote' and 'desired_capabilities' in browser_kwargs: # desired_capabilities is only for Remote driver, but can sneak in del(browser_kwargs['desired_capabilities']) if webdriver_name == 'Remote' and 'webdriver_wharf' in browser_conf and not thread_locals.wharf: # Configured to use wharf, but it isn't configured yet; check out a webdriver container wharf = Wharf(browser_conf['webdriver_wharf']) # TODO: Error handling! :D wharf.checkout() atexit.register(wharf.checkin) thread_locals.wharf = wharf if browser_kwargs['desired_capabilities']['browserName'] == 'chrome': # chrome uses containers to sandbox the browser, and we use containers to # run chrome in wharf, so disable the sandbox if running chrome in wharf co = browser_kwargs['desired_capabilities'].get('chromeOptions', {}) arg = '--no-sandbox' if 'args' not in co: co['args'] = [arg] elif arg not in co['args']: co['args'].append(arg) browser_kwargs['desired_capabilities']['chromeOptions'] = co if thread_locals.wharf: # Wharf is configured, make sure to use its command_executor wharf_config = thread_locals.wharf.config browser_kwargs['command_executor'] = wharf_config['webdriver_url'] view_msg = 'tests can be viewed via vnc on display %s' % wharf_config['vnc_display'] logger.info('webdriver command executor set to %s' % wharf_config['webdriver_url']) logger.info(view_msg) write_line(view_msg, cyan=True) try: browser = tries(3, WebDriverException, webdriver_class, **browser_kwargs) browser.maximize_window() browser.get(base_url) thread_locals.browser = browser except urllib2.URLError as ex: # connection to selenium was refused for unknown reasons if thread_locals.wharf: # If we're running wharf, try again with a new container logger.error('URLError connecting to selenium; recycling container. URLError:') # Plus, since this is a really weird thing that we need to figure out, # throw a message out to the terminal for visibility write_line('URLError caused container recycle, see log for details', red=True) logger.exception(ex) thread_locals.wharf.checkin() thread_locals.wharf = None start(webdriver_name, base_url, **kwargs) else: # If we aren't running wharf, raise it raise return thread_locals.browser def quit(): """Close the current browser Will silently fail if the current browser can't be closed for any reason. .. note:: If a browser can't be closed, it's usually because it has already been closed elsewhere. """ try: browser().quit() except: # Due to the multitude of exceptions can be thrown when attempting to kill the browser, # Diaper Pattern! pass finally: thread_locals.browser = None @contextmanager def browser_session(*args, **kwargs): """A context manager that can be used to start and stop a browser. Usage: with browser_session as browser: # do stuff with browser here # Browser will be closed here """ browser = start(*args, **kwargs) try: yield browser finally: quit() def _load_firefox_profile(): # create a firefox profile using the template in data/firefox_profile.js.template global firefox_profile_tmpdir # Make a new firefox profile dir if it's unset or doesn't exist for some reason if firefox_profile_tmpdir is None or not os.path.exists(firefox_profile_tmpdir): firefox_profile_tmpdir = mkdtemp(prefix='firefox_profile_') # Clean up tempdir at exit atexit.register(rmtree, firefox_profile_tmpdir, ignore_errors=True) template = data_path.join('firefox_profile.js.template').read() profile_json = Template(template).substitute(profile_dir=firefox_profile_tmpdir) profile_dict = json.loads(profile_json) profile = FirefoxProfile(firefox_profile_tmpdir) for pref in profile_dict.iteritems(): profile.set_preference(*pref) profile.update_preferences() return profile class Wharf(object): def __init__(self, wharf_url): self.wharf_url = wharf_url self.docker_id = None self.renew_timer = None def checkout(self): response = requests.get(os.path.join(self.wharf_url, 'checkout')) try: checkout = json.loads(response.content) except ValueError: raise ValueError("JSON could not be decoded:\n{}".format(response.content)) self.docker_id = checkout.keys()[0] self.config = checkout[self.docker_id] self._reset_renewal_timer() logger.info('Checked out webdriver container %s' % self.docker_id) return self.docker_id def checkin(self): if self.docker_id: requests.get(os.path.join(self.wharf_url, 'checkin', self.docker_id)) logger.info('Checked in webdriver container %s' % self.docker_id) self.docker_id = None def renew(self): # If we have a docker id, renew_timer shouldn't still be None if self.docker_id and not self.renew_timer.is_alive(): # You can call renew as frequently as desired, but it'll only run if # the renewal timer has stopped or failed to renew response = requests.get(os.path.join(self.wharf_url, 'renew', self.docker_id)) try: expiry_info = json.loads(response.content) except ValueError: raise ValueError("JSON could not be decoded:\n{}".format(response.content)) self.config.update(expiry_info) self._reset_renewal_timer() logger.info('Renewed webdriver container %s' % self.docker_id) def _reset_renewal_timer(self): if self.docker_id: if self.renew_timer: self.renew_timer.cancel() # Floor div by 2 and add a second to renew roughly halfway before expiration cautious_expire_interval = (self.config['expire_interval'] >> 1) + 1 self.renew_timer = Timer(cautious_expire_interval, self.renew) # mark as daemon so the timer is rudely destroyed on shutdown self.renew_timer.daemon = True self.renew_timer.start() def __nonzero__(self): return bool(self.docker_id) atexit.register(quit)
# -*- coding: utf-8 -*- import fauxfactory import pytest import cfme.configure.access_control as ac from cfme.fixtures import pytest_selenium as sel from cfme.automate import explorer as automate from cfme.exceptions import FlashMessageException from cfme.provisioning import provisioning_form from cfme.services import requests from cfme.web_ui import fill, flash from utils import testgen, version from utils.wait import wait_for from utils.providers import setup_provider pytestmark = [ pytest.mark.meta(server_roles="+automate"), pytest.mark.usefixtures('uses_infra_providers') ] def pytest_generate_tests(metafunc): argnames, argvalues, idlist = testgen.provider_by_type( metafunc, ['virtualcenter'], 'provisioning') metafunc.parametrize(argnames, argvalues, ids=idlist, scope='module') @pytest.fixture(scope="function") def vm_name(): vm_name = 'test_quota_prov_%s' % fauxfactory.gen_alphanumeric() return vm_name @pytest.fixture(scope="module") def domain(request): if version.current_version() < "5.3": return None domain = automate.Domain(name=fauxfactory.gen_alphanumeric(), enabled=True) domain.create() request.addfinalizer(lambda: domain.delete() if domain.exists() else None) return domain @pytest.fixture(scope="module") def cls(request, domain): tcls = automate.Class(name="ProvisionRequestQuotaVerification", namespace=automate.Namespace.make_path("Infrastructure", "VM", "Provisioning", "StateMachines", parent=domain, create_on_init=True)) tcls.create() request.addfinalizer(lambda: tcls.delete() if tcls.exists() else None) return tcls @pytest.fixture(scope="module") def copy_methods(domain): methods = ['rejected', 'validate_quotas'] for method in methods: ocls = automate.Class(name="ProvisionRequestQuotaVerification", namespace=automate.Namespace.make_path("Infrastructure", "VM", "Provisioning", "StateMachines", parent=automate.Domain(name="ManageIQ (Locked)"))) method = automate.Method(name=method, cls=ocls) method = method.copy_to(domain) @pytest.fixture(scope="module") def set_domain_priority(domain): automate.set_domain_order(domain.name) @pytest.yield_fixture(scope="module") def set_group_memory(): group = ac.Group(description='EvmGroup-super_administrator') group.edit_tags("Quota - Max Memory *", '2GB') yield group.remove_tag("Quota - Max Memory *", "2GB") @pytest.yield_fixture(scope="module") def set_group_cpu(): group = ac.Group(description='EvmGroup-super_administrator') group.edit_tags("Quota - Max CPUs *", '2') yield group.remove_tag("Quota - Max CPUs *", "2") @pytest.fixture(scope="function") def prov_data(provisioning, provider): return { "first_name": fauxfactory.gen_alphanumeric(), "last_name": fauxfactory.gen_alphanumeric(), "email": "{}@{}.test".format( fauxfactory.gen_alphanumeric(), fauxfactory.gen_alphanumeric()), "manager_name": "{} {}".format( fauxfactory.gen_alphanumeric(), fauxfactory.gen_alphanumeric()), "vlan": provisioning.get("vlan", None), "datastore_name": {"name": provisioning["datastore"]}, "host_name": {"name": provisioning["host"]}, "provision_type": "Native Clone" if provider.type == "rhevm" else "VMware" } @pytest.fixture(scope="function") def template_name(provisioning): return provisioning["template"] @pytest.fixture(scope="function") def provisioner(request, provider): if not provider.exists: try: setup_provider(provider.key) except FlashMessageException as e: e.skip_and_log("Provider failed to set up") def _provisioner(template, provisioning_data, delayed=None): sel.force_navigate('infrastructure_provision_vms', context={ 'provider': provider, 'template_name': template, }) fill(provisioning_form, provisioning_data, action=provisioning_form.submit_button) flash.assert_no_errors() return _provisioner def test_group_quota_max_memory_check_by_tagging( provisioner, prov_data, template_name, provider, request, vm_name, set_group_memory, bug): """ Test group Quota-Max Memory by tagging. Prerequisities: * A provider set up, supporting provisioning in CFME Steps: * Set the group quota for memory by tagging * Open the provisioning dialog. * Apart from the usual provisioning settings, set RAM greater then group quota memory. * Submit the provisioning request and wait for it to finish. * Visit the requests page. The last message should state quota validation message. Metadata: test_flag: provision """ note = ('template %s to vm %s on provider %s' % (template_name, vm_name, provider.key)) prov_data["vm_name"] = vm_name prov_data["memory"] = "4096" prov_data["notes"] = note provisioner(template_name, prov_data) # nav to requests page to check quota validation row_description = 'Provision from [%s] to [%s]' % (template_name, vm_name) cells = {'Description': row_description} row, __ = wait_for(requests.wait_for_request, [cells, True], fail_func=requests.reload, num_sec=300, delay=20) if version.current_version() >= "5.4": assert row.last_message.text == 'Request denied due to the following quota limits:'\ '(Group Allocated Memory 0.00GB + Requested 4.00GB > Quota 2.00GB)' else: assert row.last_message.text == 'Request denied due to the following quota limits:'\ '(Group Allocated Memory 0.00GB + Requested 4.00GB \> Quota 2.00GB)' def test_group_quota_max_cpu_check_by_tagging( provisioner, prov_data, template_name, provider, request, vm_name, set_group_cpu, bug): """ Test group Quota-Max CPU by tagging. Prerequisities: * A provider set up, supporting provisioning in CFME Steps: * Set the group quota for cpu by tagging * Open the provisioning dialog. * Apart from the usual provisioning settings, set CPU greater then group quota cpu. * Submit the provisioning request and wait for it to finish. * Visit the requests page. The last message should state quota validation message. Metadata: test_flag: provision """ note = ('template %s to vm %s on provider %s' % (template_name, vm_name, provider.key)) prov_data["vm_name"] = vm_name prov_data["num_sockets"] = "8" prov_data["notes"] = note provisioner(template_name, prov_data) # nav to requests page to check quota validation row_description = 'Provision from [%s] to [%s]' % (template_name, vm_name) cells = {'Description': row_description} row, __ = wait_for(requests.wait_for_request, [cells], fail_func=sel.refresh, num_sec=300, delay=20) if version.current_version() >= "5.4": assert row.last_message.text == 'Request denied due to the following quota limits:'\ '(Group Allocated vCPUs 0 + Requested 8 > Quota 2)' else: assert row.last_message.text == 'Request denied due to the following quota limits:'\ '(Group Allocated vCPUs 0 + Requested 8 \> Quota 2)'
thom-at-redhat/cfme_tests
cfme/tests/infrastructure/test_infra_quota.py
utils/browser.py
from django.contrib.postgres.fields import ArrayField from django.db import models from osf.models import Node from osf.models import OSFUser from osf.models.base import BaseModel, ObjectIDMixin from osf.models.validators import validate_subscription_type from osf.utils.fields import NonNaiveDateTimeField from website.notifications.constants import NOTIFICATION_TYPES from website.util import api_v2_url class NotificationSubscription(BaseModel): primary_identifier_name = '_id' _id = models.CharField(max_length=50, db_index=True, unique=True) # pxyz_wiki_updated, uabc_comment_replies event_name = models.CharField(max_length=50) # wiki_updated, comment_replies user = models.ForeignKey('OSFUser', related_name='notification_subscriptions', null=True, blank=True, on_delete=models.CASCADE) node = models.ForeignKey('Node', related_name='notification_subscriptions', null=True, blank=True, on_delete=models.CASCADE) provider = models.ForeignKey('AbstractProvider', related_name='notification_subscriptions', null=True, blank=True, on_delete=models.CASCADE) # Notification types none = models.ManyToManyField('OSFUser', related_name='+') # reverse relationships email_digest = models.ManyToManyField('OSFUser', related_name='+') # for these email_transactional = models.ManyToManyField('OSFUser', related_name='+') # are pointless @classmethod def load(cls, q): # modm doesn't throw exceptions when loading things that don't exist try: return cls.objects.get(_id=q) except cls.DoesNotExist: return None @property def owner(self): # ~100k have owner==user if self.user is not None: return self.user # ~8k have owner=Node elif self.node is not None: return self.node @owner.setter def owner(self, value): if isinstance(value, OSFUser): self.user = value elif isinstance(value, Node): self.node = value @property def absolute_api_v2_url(self): path = '/subscriptions/{}/'.format(self._id) return api_v2_url(path) def add_user_to_subscription(self, user, notification_type, save=True): for nt in NOTIFICATION_TYPES: if getattr(self, nt).filter(id=user.id).exists(): if nt != notification_type: getattr(self, nt).remove(user) else: if nt == notification_type: getattr(self, nt).add(user) if notification_type != 'none' and isinstance(self.owner, Node) and self.owner.parent_node: user_subs = self.owner.parent_node.child_node_subscriptions if self.owner._id not in user_subs.setdefault(user._id, []): user_subs[user._id].append(self.owner._id) self.owner.parent_node.save() if save: self.save() def remove_user_from_subscription(self, user, save=True): for notification_type in NOTIFICATION_TYPES: try: getattr(self, notification_type, []).remove(user) except ValueError: pass if isinstance(self.owner, Node) and self.owner.parent_node: try: self.owner.parent_node.child_node_subscriptions.get(user._id, []).remove(self.owner._id) self.owner.parent_node.save() except ValueError: pass if save: self.save() class NotificationDigest(ObjectIDMixin, BaseModel): user = models.ForeignKey('OSFUser', null=True, blank=True, on_delete=models.CASCADE) provider = models.ForeignKey('AbstractProvider', null=True, blank=True, on_delete=models.CASCADE) timestamp = NonNaiveDateTimeField() send_type = models.CharField(max_length=50, db_index=True, validators=[validate_subscription_type, ]) event = models.CharField(max_length=50) message = models.TextField() # TODO: Could this be a m2m with or without an order field? node_lineage = ArrayField(models.CharField(max_length=5))
from osf.models import Institution from .factories import InstitutionFactory import pytest @pytest.mark.django_db def test_factory(): inst = InstitutionFactory() assert isinstance(inst.name, basestring) assert len(inst.domains) > 0 assert len(inst.email_domains) > 0 @pytest.mark.django_db def test_querying_on_domains(): inst = InstitutionFactory(domains=['foo.test']) result = Institution.objects.filter(domains__contains=['foo.test']) assert inst in result @pytest.mark.django_db def test_institution_banner_path_none(): inst = InstitutionFactory(banner_name='kittens.png') assert inst.banner_path is not None inst.banner_name = None assert inst.banner_path is None @pytest.mark.django_db def test_institution_logo_path_none(): inst = InstitutionFactory(logo_name='kittens.png') assert inst.logo_path is not None inst.logo_name = None assert inst.logo_path is None @pytest.mark.django_db def test_institution_logo_path(): inst = InstitutionFactory(logo_name='osf-shield.png') expected_logo_path = '/static/img/institutions/shields/osf-shield.png' assert inst.logo_path == expected_logo_path @pytest.mark.django_db def test_institution_logo_path_rounded_corners(): inst = InstitutionFactory(logo_name='osf-shield.png') expected_logo_path = '/static/img/institutions/shields-rounded-corners/osf-shield-rounded-corners.png' assert inst.logo_path_rounded_corners == expected_logo_path @pytest.mark.django_db def test_institution_banner_path(): inst = InstitutionFactory(banner_name='osf-banner.png') expected_banner_path = '/static/img/institutions/banners/osf-banner.png' assert inst.banner_path == expected_banner_path
pattisdr/osf.io
osf_tests/test_institution.py
osf/models/notifications.py
"""Spectral Embedding""" # Author: Gael Varoquaux <gael.varoquaux@normalesup.org> # Wei LI <kuantkid@gmail.com> # License: BSD 3 clause from __future__ import division import warnings import numpy as np from scipy import sparse from scipy.linalg import eigh from scipy.sparse.linalg import eigsh, lobpcg from scipy.sparse.csgraph import connected_components from scipy.sparse.csgraph import laplacian as csgraph_laplacian from ..base import BaseEstimator from ..externals import six from ..utils import check_random_state, check_array, check_symmetric from ..utils.extmath import _deterministic_vector_sign_flip from ..metrics.pairwise import rbf_kernel from ..neighbors import kneighbors_graph def _graph_connected_component(graph, node_id): """Find the largest graph connected components that contains one given node Parameters ---------- graph : array-like, shape: (n_samples, n_samples) adjacency matrix of the graph, non-zero weight means an edge between the nodes node_id : int The index of the query node of the graph Returns ------- connected_components_matrix : array-like, shape: (n_samples,) An array of bool value indicating the indexes of the nodes belonging to the largest connected components of the given query node """ n_node = graph.shape[0] if sparse.issparse(graph): # speed up row-wise access to boolean connection mask graph = graph.tocsr() connected_nodes = np.zeros(n_node, dtype=np.bool) nodes_to_explore = np.zeros(n_node, dtype=np.bool) nodes_to_explore[node_id] = True for _ in range(n_node): last_num_component = connected_nodes.sum() np.logical_or(connected_nodes, nodes_to_explore, out=connected_nodes) if last_num_component >= connected_nodes.sum(): break indices = np.where(nodes_to_explore)[0] nodes_to_explore.fill(False) for i in indices: if sparse.issparse(graph): neighbors = graph[i].toarray().ravel() else: neighbors = graph[i] np.logical_or(nodes_to_explore, neighbors, out=nodes_to_explore) return connected_nodes def _graph_is_connected(graph): """ Return whether the graph is connected (True) or Not (False) Parameters ---------- graph : array-like or sparse matrix, shape: (n_samples, n_samples) adjacency matrix of the graph, non-zero weight means an edge between the nodes Returns ------- is_connected : bool True means the graph is fully connected and False means not """ if sparse.isspmatrix(graph): # sparse graph, find all the connected components n_connected_components, _ = connected_components(graph) return n_connected_components == 1 else: # dense graph, find all connected components start from node 0 return _graph_connected_component(graph, 0).sum() == graph.shape[0] def _set_diag(laplacian, value, norm_laplacian): """Set the diagonal of the laplacian matrix and convert it to a sparse format well suited for eigenvalue decomposition Parameters ---------- laplacian : array or sparse matrix The graph laplacian value : float The value of the diagonal norm_laplacian : bool Whether the value of the diagonal should be changed or not Returns ------- laplacian : array or sparse matrix An array of matrix in a form that is well suited to fast eigenvalue decomposition, depending on the band width of the matrix. """ n_nodes = laplacian.shape[0] # We need all entries in the diagonal to values if not sparse.isspmatrix(laplacian): if norm_laplacian: laplacian.flat[::n_nodes + 1] = value else: laplacian = laplacian.tocoo() if norm_laplacian: diag_idx = (laplacian.row == laplacian.col) laplacian.data[diag_idx] = value # If the matrix has a small number of diagonals (as in the # case of structured matrices coming from images), the # dia format might be best suited for matvec products: n_diags = np.unique(laplacian.row - laplacian.col).size if n_diags <= 7: # 3 or less outer diagonals on each side laplacian = laplacian.todia() else: # csr has the fastest matvec and is thus best suited to # arpack laplacian = laplacian.tocsr() return laplacian def spectral_embedding(adjacency, n_components=8, eigen_solver=None, random_state=None, eigen_tol=0.0, norm_laplacian=True, drop_first=True): """Project the sample on the first eigenvectors of the graph Laplacian. The adjacency matrix is used to compute a normalized graph Laplacian whose spectrum (especially the eigenvectors associated to the smallest eigenvalues) has an interpretation in terms of minimal number of cuts necessary to split the graph into comparably sized components. This embedding can also 'work' even if the ``adjacency`` variable is not strictly the adjacency matrix of a graph but more generally an affinity or similarity matrix between samples (for instance the heat kernel of a euclidean distance matrix or a k-NN matrix). However care must taken to always make the affinity matrix symmetric so that the eigenvector decomposition works as expected. Note : Laplacian Eigenmaps is the actual algorithm implemented here. Read more in the :ref:`User Guide <spectral_embedding>`. Parameters ---------- adjacency : array-like or sparse matrix, shape: (n_samples, n_samples) The adjacency matrix of the graph to embed. n_components : integer, optional, default 8 The dimension of the projection subspace. eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'}, default None The eigenvalue decomposition strategy to use. AMG requires pyamg to be installed. It can be faster on very large, sparse problems, but may also lead to instabilities. random_state : int, RandomState instance or None, optional, default: None A pseudo random number generator used for the initialization of the lobpcg eigenvectors decomposition. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Used when ``solver`` == 'amg'. eigen_tol : float, optional, default=0.0 Stopping criterion for eigendecomposition of the Laplacian matrix when using arpack eigen_solver. norm_laplacian : bool, optional, default=True If True, then compute normalized Laplacian. drop_first : bool, optional, default=True Whether to drop the first eigenvector. For spectral embedding, this should be True as the first eigenvector should be constant vector for connected graph, but for spectral clustering, this should be kept as False to retain the first eigenvector. Returns ------- embedding : array, shape=(n_samples, n_components) The reduced samples. Notes ----- Spectral Embedding (Laplacian Eigenmaps) is most useful when the graph has one connected component. If there graph has many components, the first few eigenvectors will simply uncover the connected components of the graph. References ---------- * https://en.wikipedia.org/wiki/LOBPCG * Toward the Optimal Preconditioned Eigensolver: Locally Optimal Block Preconditioned Conjugate Gradient Method Andrew V. Knyazev https://doi.org/10.1137%2FS1064827500366124 """ adjacency = check_symmetric(adjacency) try: from pyamg import smoothed_aggregation_solver except ImportError: if eigen_solver == "amg": raise ValueError("The eigen_solver was set to 'amg', but pyamg is " "not available.") if eigen_solver is None: eigen_solver = 'arpack' elif eigen_solver not in ('arpack', 'lobpcg', 'amg'): raise ValueError("Unknown value for eigen_solver: '%s'." "Should be 'amg', 'arpack', or 'lobpcg'" % eigen_solver) random_state = check_random_state(random_state) n_nodes = adjacency.shape[0] # Whether to drop the first eigenvector if drop_first: n_components = n_components + 1 if not _graph_is_connected(adjacency): warnings.warn("Graph is not fully connected, spectral embedding" " may not work as expected.") laplacian, dd = csgraph_laplacian(adjacency, normed=norm_laplacian, return_diag=True) if (eigen_solver == 'arpack' or eigen_solver != 'lobpcg' and (not sparse.isspmatrix(laplacian) or n_nodes < 5 * n_components)): # lobpcg used with eigen_solver='amg' has bugs for low number of nodes # for details see the source code in scipy: # https://github.com/scipy/scipy/blob/v0.11.0/scipy/sparse/linalg/eigen # /lobpcg/lobpcg.py#L237 # or matlab: # http://www.mathworks.com/matlabcentral/fileexchange/48-lobpcg-m laplacian = _set_diag(laplacian, 1, norm_laplacian) # Here we'll use shift-invert mode for fast eigenvalues # (see http://docs.scipy.org/doc/scipy/reference/tutorial/arpack.html # for a short explanation of what this means) # Because the normalized Laplacian has eigenvalues between 0 and 2, # I - L has eigenvalues between -1 and 1. ARPACK is most efficient # when finding eigenvalues of largest magnitude (keyword which='LM') # and when these eigenvalues are very large compared to the rest. # For very large, very sparse graphs, I - L can have many, many # eigenvalues very near 1.0. This leads to slow convergence. So # instead, we'll use ARPACK's shift-invert mode, asking for the # eigenvalues near 1.0. This effectively spreads-out the spectrum # near 1.0 and leads to much faster convergence: potentially an # orders-of-magnitude speedup over simply using keyword which='LA' # in standard mode. try: # We are computing the opposite of the laplacian inplace so as # to spare a memory allocation of a possibly very large array laplacian *= -1 v0 = random_state.uniform(-1, 1, laplacian.shape[0]) lambdas, diffusion_map = eigsh(laplacian, k=n_components, sigma=1.0, which='LM', tol=eigen_tol, v0=v0) embedding = diffusion_map.T[n_components::-1] if norm_laplacian: embedding = embedding / dd except RuntimeError: # When submatrices are exactly singular, an LU decomposition # in arpack fails. We fallback to lobpcg eigen_solver = "lobpcg" # Revert the laplacian to its opposite to have lobpcg work laplacian *= -1 if eigen_solver == 'amg': # Use AMG to get a preconditioner and speed up the eigenvalue # problem. if not sparse.issparse(laplacian): warnings.warn("AMG works better for sparse matrices") # lobpcg needs double precision floats laplacian = check_array(laplacian, dtype=np.float64, accept_sparse=True) laplacian = _set_diag(laplacian, 1, norm_laplacian) ml = smoothed_aggregation_solver(check_array(laplacian, 'csr')) M = ml.aspreconditioner() X = random_state.rand(laplacian.shape[0], n_components + 1) X[:, 0] = dd.ravel() lambdas, diffusion_map = lobpcg(laplacian, X, M=M, tol=1.e-12, largest=False) embedding = diffusion_map.T if norm_laplacian: embedding = embedding / dd if embedding.shape[0] == 1: raise ValueError elif eigen_solver == "lobpcg": # lobpcg needs double precision floats laplacian = check_array(laplacian, dtype=np.float64, accept_sparse=True) if n_nodes < 5 * n_components + 1: # see note above under arpack why lobpcg has problems with small # number of nodes # lobpcg will fallback to eigh, so we short circuit it if sparse.isspmatrix(laplacian): laplacian = laplacian.toarray() lambdas, diffusion_map = eigh(laplacian) embedding = diffusion_map.T[:n_components] if norm_laplacian: embedding = embedding / dd else: laplacian = _set_diag(laplacian, 1, norm_laplacian) # We increase the number of eigenvectors requested, as lobpcg # doesn't behave well in low dimension X = random_state.rand(laplacian.shape[0], n_components + 1) X[:, 0] = dd.ravel() lambdas, diffusion_map = lobpcg(laplacian, X, tol=1e-15, largest=False, maxiter=2000) embedding = diffusion_map.T[:n_components] if norm_laplacian: embedding = embedding / dd if embedding.shape[0] == 1: raise ValueError embedding = _deterministic_vector_sign_flip(embedding) if drop_first: return embedding[1:n_components].T else: return embedding[:n_components].T class SpectralEmbedding(BaseEstimator): """Spectral embedding for non-linear dimensionality reduction. Forms an affinity matrix given by the specified function and applies spectral decomposition to the corresponding graph laplacian. The resulting transformation is given by the value of the eigenvectors for each data point. Note : Laplacian Eigenmaps is the actual algorithm implemented here. Read more in the :ref:`User Guide <spectral_embedding>`. Parameters ----------- n_components : integer, default: 2 The dimension of the projected subspace. affinity : string or callable, default : "nearest_neighbors" How to construct the affinity matrix. - 'nearest_neighbors' : construct affinity matrix by knn graph - 'rbf' : construct affinity matrix by rbf kernel - 'precomputed' : interpret X as precomputed affinity matrix - callable : use passed in function as affinity the function takes in data matrix (n_samples, n_features) and return affinity matrix (n_samples, n_samples). gamma : float, optional, default : 1/n_features Kernel coefficient for rbf kernel. random_state : int, RandomState instance or None, optional, default: None A pseudo random number generator used for the initialization of the lobpcg eigenvectors. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Used when ``solver`` == 'amg'. eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'} The eigenvalue decomposition strategy to use. AMG requires pyamg to be installed. It can be faster on very large, sparse problems, but may also lead to instabilities. n_neighbors : int, default : max(n_samples/10 , 1) Number of nearest neighbors for nearest_neighbors graph building. n_jobs : int or None, optional (default=None) The number of parallel jobs to run. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Attributes ---------- embedding_ : array, shape = (n_samples, n_components) Spectral embedding of the training matrix. affinity_matrix_ : array, shape = (n_samples, n_samples) Affinity_matrix constructed from samples or precomputed. Examples -------- >>> from sklearn.datasets import load_digits >>> from sklearn.manifold import SpectralEmbedding >>> X, _ = load_digits(return_X_y=True) >>> X.shape (1797, 64) >>> embedding = SpectralEmbedding(n_components=2) >>> X_transformed = embedding.fit_transform(X[:100]) >>> X_transformed.shape (100, 2) References ---------- - A Tutorial on Spectral Clustering, 2007 Ulrike von Luxburg http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.165.9323 - On Spectral Clustering: Analysis and an algorithm, 2001 Andrew Y. Ng, Michael I. Jordan, Yair Weiss http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.8100 - Normalized cuts and image segmentation, 2000 Jianbo Shi, Jitendra Malik http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.160.2324 """ def __init__(self, n_components=2, affinity="nearest_neighbors", gamma=None, random_state=None, eigen_solver=None, n_neighbors=None, n_jobs=None): self.n_components = n_components self.affinity = affinity self.gamma = gamma self.random_state = random_state self.eigen_solver = eigen_solver self.n_neighbors = n_neighbors self.n_jobs = n_jobs @property def _pairwise(self): return self.affinity == "precomputed" def _get_affinity_matrix(self, X, Y=None): """Calculate the affinity matrix from data Parameters ---------- X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. If affinity is "precomputed" X : array-like, shape (n_samples, n_samples), Interpret X as precomputed adjacency graph computed from samples. Y: Ignored Returns ------- affinity_matrix, shape (n_samples, n_samples) """ if self.affinity == 'precomputed': self.affinity_matrix_ = X return self.affinity_matrix_ if self.affinity == 'nearest_neighbors': if sparse.issparse(X): warnings.warn("Nearest neighbors affinity currently does " "not support sparse input, falling back to " "rbf affinity") self.affinity = "rbf" else: self.n_neighbors_ = (self.n_neighbors if self.n_neighbors is not None else max(int(X.shape[0] / 10), 1)) self.affinity_matrix_ = kneighbors_graph(X, self.n_neighbors_, include_self=True, n_jobs=self.n_jobs) # currently only symmetric affinity_matrix supported self.affinity_matrix_ = 0.5 * (self.affinity_matrix_ + self.affinity_matrix_.T) return self.affinity_matrix_ if self.affinity == 'rbf': self.gamma_ = (self.gamma if self.gamma is not None else 1.0 / X.shape[1]) self.affinity_matrix_ = rbf_kernel(X, gamma=self.gamma_) return self.affinity_matrix_ self.affinity_matrix_ = self.affinity(X) return self.affinity_matrix_ def fit(self, X, y=None): """Fit the model from data in X. Parameters ---------- X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. If affinity is "precomputed" X : array-like, shape (n_samples, n_samples), Interpret X as precomputed adjacency graph computed from samples. Returns ------- self : object Returns the instance itself. """ X = check_array(X, ensure_min_samples=2, estimator=self) random_state = check_random_state(self.random_state) if isinstance(self.affinity, six.string_types): if self.affinity not in set(("nearest_neighbors", "rbf", "precomputed")): raise ValueError(("%s is not a valid affinity. Expected " "'precomputed', 'rbf', 'nearest_neighbors' " "or a callable.") % self.affinity) elif not callable(self.affinity): raise ValueError(("'affinity' is expected to be an affinity " "name or a callable. Got: %s") % self.affinity) affinity_matrix = self._get_affinity_matrix(X) self.embedding_ = spectral_embedding(affinity_matrix, n_components=self.n_components, eigen_solver=self.eigen_solver, random_state=random_state) return self def fit_transform(self, X, y=None): """Fit the model from data in X and transform X. Parameters ---------- X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. If affinity is "precomputed" X : array-like, shape (n_samples, n_samples), Interpret X as precomputed adjacency graph computed from samples. Returns ------- X_new : array-like, shape (n_samples, n_components) """ self.fit(X) return self.embedding_
import pytest import numpy as np from scipy import sparse from scipy.sparse import csgraph from scipy.linalg import eigh from sklearn.manifold.spectral_embedding_ import SpectralEmbedding from sklearn.manifold.spectral_embedding_ import _graph_is_connected from sklearn.manifold.spectral_embedding_ import _graph_connected_component from sklearn.manifold import spectral_embedding from sklearn.metrics.pairwise import rbf_kernel from sklearn.metrics import normalized_mutual_info_score from sklearn.cluster import KMeans from sklearn.datasets.samples_generator import make_blobs from sklearn.utils.extmath import _deterministic_vector_sign_flip from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_true, assert_equal, assert_raises from sklearn.utils.testing import SkipTest # non centered, sparse centers to check the centers = np.array([ [0.0, 5.0, 0.0, 0.0, 0.0], [0.0, 0.0, 4.0, 0.0, 0.0], [1.0, 0.0, 0.0, 5.0, 1.0], ]) n_samples = 1000 n_clusters, n_features = centers.shape S, true_labels = make_blobs(n_samples=n_samples, centers=centers, cluster_std=1., random_state=42) def _check_with_col_sign_flipping(A, B, tol=0.0): """ Check array A and B are equal with possible sign flipping on each columns""" sign = True for column_idx in range(A.shape[1]): sign = sign and ((((A[:, column_idx] - B[:, column_idx]) ** 2).mean() <= tol ** 2) or (((A[:, column_idx] + B[:, column_idx]) ** 2).mean() <= tol ** 2)) if not sign: return False return True def test_sparse_graph_connected_component(): rng = np.random.RandomState(42) n_samples = 300 boundaries = [0, 42, 121, 200, n_samples] p = rng.permutation(n_samples) connections = [] for start, stop in zip(boundaries[:-1], boundaries[1:]): group = p[start:stop] # Connect all elements within the group at least once via an # arbitrary path that spans the group. for i in range(len(group) - 1): connections.append((group[i], group[i + 1])) # Add some more random connections within the group min_idx, max_idx = 0, len(group) - 1 n_random_connections = 1000 source = rng.randint(min_idx, max_idx, size=n_random_connections) target = rng.randint(min_idx, max_idx, size=n_random_connections) connections.extend(zip(group[source], group[target])) # Build a symmetric affinity matrix row_idx, column_idx = tuple(np.array(connections).T) data = rng.uniform(.1, 42, size=len(connections)) affinity = sparse.coo_matrix((data, (row_idx, column_idx))) affinity = 0.5 * (affinity + affinity.T) for start, stop in zip(boundaries[:-1], boundaries[1:]): component_1 = _graph_connected_component(affinity, p[start]) component_size = stop - start assert_equal(component_1.sum(), component_size) # We should retrieve the same component mask by starting by both ends # of the group component_2 = _graph_connected_component(affinity, p[stop - 1]) assert_equal(component_2.sum(), component_size) assert_array_equal(component_1, component_2) @pytest.mark.filterwarnings("ignore:the behavior of nmi will " "change in version 0.22") def test_spectral_embedding_two_components(seed=36): # Test spectral embedding with two components random_state = np.random.RandomState(seed) n_sample = 100 affinity = np.zeros(shape=[n_sample * 2, n_sample * 2]) # first component affinity[0:n_sample, 0:n_sample] = np.abs(random_state.randn(n_sample, n_sample)) + 2 # second component affinity[n_sample::, n_sample::] = np.abs(random_state.randn(n_sample, n_sample)) + 2 # Test of internal _graph_connected_component before connection component = _graph_connected_component(affinity, 0) assert_true(component[:n_sample].all()) assert_true(not component[n_sample:].any()) component = _graph_connected_component(affinity, -1) assert_true(not component[:n_sample].any()) assert_true(component[n_sample:].all()) # connection affinity[0, n_sample + 1] = 1 affinity[n_sample + 1, 0] = 1 affinity.flat[::2 * n_sample + 1] = 0 affinity = 0.5 * (affinity + affinity.T) true_label = np.zeros(shape=2 * n_sample) true_label[0:n_sample] = 1 se_precomp = SpectralEmbedding(n_components=1, affinity="precomputed", random_state=np.random.RandomState(seed)) embedded_coordinate = se_precomp.fit_transform(affinity) # Some numpy versions are touchy with types embedded_coordinate = \ se_precomp.fit_transform(affinity.astype(np.float32)) # thresholding on the first components using 0. label_ = np.array(embedded_coordinate.ravel() < 0, dtype="float") assert_equal(normalized_mutual_info_score(true_label, label_), 1.0) def test_spectral_embedding_precomputed_affinity(seed=36): # Test spectral embedding with precomputed kernel gamma = 1.0 se_precomp = SpectralEmbedding(n_components=2, affinity="precomputed", random_state=np.random.RandomState(seed)) se_rbf = SpectralEmbedding(n_components=2, affinity="rbf", gamma=gamma, random_state=np.random.RandomState(seed)) embed_precomp = se_precomp.fit_transform(rbf_kernel(S, gamma=gamma)) embed_rbf = se_rbf.fit_transform(S) assert_array_almost_equal( se_precomp.affinity_matrix_, se_rbf.affinity_matrix_) assert_true(_check_with_col_sign_flipping(embed_precomp, embed_rbf, 0.05)) def test_spectral_embedding_callable_affinity(seed=36): # Test spectral embedding with callable affinity gamma = 0.9 kern = rbf_kernel(S, gamma=gamma) se_callable = SpectralEmbedding(n_components=2, affinity=( lambda x: rbf_kernel(x, gamma=gamma)), gamma=gamma, random_state=np.random.RandomState(seed)) se_rbf = SpectralEmbedding(n_components=2, affinity="rbf", gamma=gamma, random_state=np.random.RandomState(seed)) embed_rbf = se_rbf.fit_transform(S) embed_callable = se_callable.fit_transform(S) assert_array_almost_equal( se_callable.affinity_matrix_, se_rbf.affinity_matrix_) assert_array_almost_equal(kern, se_rbf.affinity_matrix_) assert_true( _check_with_col_sign_flipping(embed_rbf, embed_callable, 0.05)) def test_spectral_embedding_amg_solver(seed=36): # Test spectral embedding with amg solver try: from pyamg import smoothed_aggregation_solver # noqa except ImportError: raise SkipTest("pyamg not available.") se_amg = SpectralEmbedding(n_components=2, affinity="nearest_neighbors", eigen_solver="amg", n_neighbors=5, random_state=np.random.RandomState(seed)) se_arpack = SpectralEmbedding(n_components=2, affinity="nearest_neighbors", eigen_solver="arpack", n_neighbors=5, random_state=np.random.RandomState(seed)) embed_amg = se_amg.fit_transform(S) embed_arpack = se_arpack.fit_transform(S) assert_true(_check_with_col_sign_flipping(embed_amg, embed_arpack, 0.05)) @pytest.mark.filterwarnings("ignore:the behavior of nmi will " "change in version 0.22") def test_pipeline_spectral_clustering(seed=36): # Test using pipeline to do spectral clustering random_state = np.random.RandomState(seed) se_rbf = SpectralEmbedding(n_components=n_clusters, affinity="rbf", random_state=random_state) se_knn = SpectralEmbedding(n_components=n_clusters, affinity="nearest_neighbors", n_neighbors=5, random_state=random_state) for se in [se_rbf, se_knn]: km = KMeans(n_clusters=n_clusters, random_state=random_state) km.fit(se.fit_transform(S)) assert_array_almost_equal( normalized_mutual_info_score( km.labels_, true_labels), 1.0, 2) def test_spectral_embedding_unknown_eigensolver(seed=36): # Test that SpectralClustering fails with an unknown eigensolver se = SpectralEmbedding(n_components=1, affinity="precomputed", random_state=np.random.RandomState(seed), eigen_solver="<unknown>") assert_raises(ValueError, se.fit, S) def test_spectral_embedding_unknown_affinity(seed=36): # Test that SpectralClustering fails with an unknown affinity type se = SpectralEmbedding(n_components=1, affinity="<unknown>", random_state=np.random.RandomState(seed)) assert_raises(ValueError, se.fit, S) def test_connectivity(seed=36): # Test that graph connectivity test works as expected graph = np.array([[1, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 1, 1, 1], [0, 0, 0, 1, 1]]) assert_equal(_graph_is_connected(graph), False) assert_equal(_graph_is_connected(sparse.csr_matrix(graph)), False) assert_equal(_graph_is_connected(sparse.csc_matrix(graph)), False) graph = np.array([[1, 1, 0, 0, 0], [1, 1, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 1, 1, 1], [0, 0, 0, 1, 1]]) assert_equal(_graph_is_connected(graph), True) assert_equal(_graph_is_connected(sparse.csr_matrix(graph)), True) assert_equal(_graph_is_connected(sparse.csc_matrix(graph)), True) def test_spectral_embedding_deterministic(): # Test that Spectral Embedding is deterministic random_state = np.random.RandomState(36) data = random_state.randn(10, 30) sims = rbf_kernel(data) embedding_1 = spectral_embedding(sims) embedding_2 = spectral_embedding(sims) assert_array_almost_equal(embedding_1, embedding_2) def test_spectral_embedding_unnormalized(): # Test that spectral_embedding is also processing unnormalized laplacian # correctly random_state = np.random.RandomState(36) data = random_state.randn(10, 30) sims = rbf_kernel(data) n_components = 8 embedding_1 = spectral_embedding(sims, norm_laplacian=False, n_components=n_components, drop_first=False) # Verify using manual computation with dense eigh laplacian, dd = csgraph.laplacian(sims, normed=False, return_diag=True) _, diffusion_map = eigh(laplacian) embedding_2 = diffusion_map.T[:n_components] embedding_2 = _deterministic_vector_sign_flip(embedding_2).T assert_array_almost_equal(embedding_1, embedding_2) def test_spectral_embedding_first_eigen_vector(): # Test that the first eigenvector of spectral_embedding # is constant and that the second is not (for a connected graph) random_state = np.random.RandomState(36) data = random_state.randn(10, 30) sims = rbf_kernel(data) n_components = 2 for seed in range(10): embedding = spectral_embedding(sims, norm_laplacian=False, n_components=n_components, drop_first=False, random_state=seed) assert np.std(embedding[:, 0]) == pytest.approx(0) assert np.std(embedding[:, 1]) > 1e-3
vortex-ape/scikit-learn
sklearn/manifold/tests/test_spectral_embedding.py
sklearn/manifold/spectral_embedding_.py
# -*- coding: utf-8 -*- """ DBSCAN: Density-Based Spatial Clustering of Applications with Noise """ # Author: Robert Layton <robertlayton@gmail.com> # Joel Nothman <joel.nothman@gmail.com> # Lars Buitinck # # License: BSD 3 clause import numpy as np from scipy import sparse from ..base import BaseEstimator, ClusterMixin from ..utils import check_array, check_consistent_length from ..neighbors import NearestNeighbors from ._dbscan_inner import dbscan_inner def dbscan(X, eps=0.5, min_samples=5, metric='minkowski', metric_params=None, algorithm='auto', leaf_size=30, p=2, sample_weight=None, n_jobs=None): """Perform DBSCAN clustering from vector array or distance matrix. Read more in the :ref:`User Guide <dbscan>`. Parameters ---------- X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \ array of shape (n_samples, n_samples) A feature array, or array of distances between samples if ``metric='precomputed'``. eps : float, optional The maximum distance between two samples for them to be considered as in the same neighborhood. min_samples : int, optional The number of samples (or total weight) in a neighborhood for a point to be considered as a core point. This includes the point itself. metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of the options allowed by :func:`sklearn.metrics.pairwise_distances` for its metric parameter. If metric is "precomputed", X is assumed to be a distance matrix and must be square. X may be a sparse matrix, in which case only "nonzero" elements may be considered neighbors for DBSCAN. metric_params : dict, optional Additional keyword arguments for the metric function. .. versionadded:: 0.19 algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional The algorithm to be used by the NearestNeighbors module to compute pointwise distances and find nearest neighbors. See NearestNeighbors module documentation for details. leaf_size : int, optional (default = 30) Leaf size passed to BallTree or cKDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. p : float, optional The power of the Minkowski metric to be used to calculate distance between points. sample_weight : array, shape (n_samples,), optional Weight of each sample, such that a sample with a weight of at least ``min_samples`` is by itself a core sample; a sample with negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1. n_jobs : int or None, optional (default=None) The number of parallel jobs to run for neighbors search. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Returns ------- core_samples : array [n_core_samples] Indices of core samples. labels : array [n_samples] Cluster labels for each point. Noisy samples are given the label -1. See also -------- DBSCAN An estimator interface for this clustering algorithm. optics A similar clustering at multiple values of eps. Our implementation is optimized for memory usage. Notes ----- For an example, see :ref:`examples/cluster/plot_dbscan.py <sphx_glr_auto_examples_cluster_plot_dbscan.py>`. This implementation bulk-computes all neighborhood queries, which increases the memory complexity to O(n.d) where d is the average number of neighbors, while original DBSCAN had memory complexity O(n). It may attract a higher memory complexity when querying these nearest neighborhoods, depending on the ``algorithm``. One way to avoid the query complexity is to pre-compute sparse neighborhoods in chunks using :func:`NearestNeighbors.radius_neighbors_graph <sklearn.neighbors.NearestNeighbors.radius_neighbors_graph>` with ``mode='distance'``, then using ``metric='precomputed'`` here. Another way to reduce memory and computation time is to remove (near-)duplicate points and use ``sample_weight`` instead. :func:`cluster.optics` provides a similar clustering with lower memory usage. References ---------- Ester, M., H. P. Kriegel, J. Sander, and X. Xu, "A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise". In: Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 """ if not eps > 0.0: raise ValueError("eps must be positive.") X = check_array(X, accept_sparse='csr') if sample_weight is not None: sample_weight = np.asarray(sample_weight) check_consistent_length(X, sample_weight) # Calculate neighborhood for all samples. This leaves the original point # in, which needs to be considered later (i.e. point i is in the # neighborhood of point i. While True, its useless information) if metric == 'precomputed' and sparse.issparse(X): neighborhoods = np.empty(X.shape[0], dtype=object) X.sum_duplicates() # XXX: modifies X's internals in-place X_mask = X.data <= eps masked_indices = X.indices.astype(np.intp, copy=False)[X_mask] masked_indptr = np.concatenate(([0], np.cumsum(X_mask)))[X.indptr[1:]] # insert the diagonal: a point is its own neighbor, but 0 distance # means absence from sparse matrix data masked_indices = np.insert(masked_indices, masked_indptr, np.arange(X.shape[0])) masked_indptr = masked_indptr[:-1] + np.arange(1, X.shape[0]) # split into rows neighborhoods[:] = np.split(masked_indices, masked_indptr) else: neighbors_model = NearestNeighbors(radius=eps, algorithm=algorithm, leaf_size=leaf_size, metric=metric, metric_params=metric_params, p=p, n_jobs=n_jobs) neighbors_model.fit(X) # This has worst case O(n^2) memory complexity neighborhoods = neighbors_model.radius_neighbors(X, eps, return_distance=False) if sample_weight is None: n_neighbors = np.array([len(neighbors) for neighbors in neighborhoods]) else: n_neighbors = np.array([np.sum(sample_weight[neighbors]) for neighbors in neighborhoods]) # Initially, all samples are noise. labels = np.full(X.shape[0], -1, dtype=np.intp) # A list of all core samples found. core_samples = np.asarray(n_neighbors >= min_samples, dtype=np.uint8) dbscan_inner(core_samples, neighborhoods, labels) return np.where(core_samples)[0], labels class DBSCAN(BaseEstimator, ClusterMixin): """Perform DBSCAN clustering from vector array or distance matrix. DBSCAN - Density-Based Spatial Clustering of Applications with Noise. Finds core samples of high density and expands clusters from them. Good for data which contains clusters of similar density. Read more in the :ref:`User Guide <dbscan>`. Parameters ---------- eps : float, optional The maximum distance between two samples for them to be considered as in the same neighborhood. min_samples : int, optional The number of samples (or total weight) in a neighborhood for a point to be considered as a core point. This includes the point itself. metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of the options allowed by :func:`sklearn.metrics.pairwise_distances` for its metric parameter. If metric is "precomputed", X is assumed to be a distance matrix and must be square. X may be a sparse matrix, in which case only "nonzero" elements may be considered neighbors for DBSCAN. .. versionadded:: 0.17 metric *precomputed* to accept precomputed sparse matrix. metric_params : dict, optional Additional keyword arguments for the metric function. .. versionadded:: 0.19 algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional The algorithm to be used by the NearestNeighbors module to compute pointwise distances and find nearest neighbors. See NearestNeighbors module documentation for details. leaf_size : int, optional (default = 30) Leaf size passed to BallTree or cKDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. p : float, optional The power of the Minkowski metric to be used to calculate distance between points. n_jobs : int or None, optional (default=None) The number of parallel jobs to run. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Attributes ---------- core_sample_indices_ : array, shape = [n_core_samples] Indices of core samples. components_ : array, shape = [n_core_samples, n_features] Copy of each core sample found by training. labels_ : array, shape = [n_samples] Cluster labels for each point in the dataset given to fit(). Noisy samples are given the label -1. Examples -------- >>> from sklearn.cluster import DBSCAN >>> import numpy as np >>> X = np.array([[1, 2], [2, 2], [2, 3], ... [8, 7], [8, 8], [25, 80]]) >>> clustering = DBSCAN(eps=3, min_samples=2).fit(X) >>> clustering.labels_ array([ 0, 0, 0, 1, 1, -1]) >>> clustering # doctest: +NORMALIZE_WHITESPACE DBSCAN(algorithm='auto', eps=3, leaf_size=30, metric='euclidean', metric_params=None, min_samples=2, n_jobs=None, p=None) See also -------- OPTICS A similar clustering at multiple values of eps. Our implementation is optimized for memory usage. Notes ----- For an example, see :ref:`examples/cluster/plot_dbscan.py <sphx_glr_auto_examples_cluster_plot_dbscan.py>`. This implementation bulk-computes all neighborhood queries, which increases the memory complexity to O(n.d) where d is the average number of neighbors, while original DBSCAN had memory complexity O(n). It may attract a higher memory complexity when querying these nearest neighborhoods, depending on the ``algorithm``. One way to avoid the query complexity is to pre-compute sparse neighborhoods in chunks using :func:`NearestNeighbors.radius_neighbors_graph <sklearn.neighbors.NearestNeighbors.radius_neighbors_graph>` with ``mode='distance'``, then using ``metric='precomputed'`` here. Another way to reduce memory and computation time is to remove (near-)duplicate points and use ``sample_weight`` instead. :class:`cluster.OPTICS` provides a similar clustering with lower memory usage. References ---------- Ester, M., H. P. Kriegel, J. Sander, and X. Xu, "A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise". In: Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 """ def __init__(self, eps=0.5, min_samples=5, metric='euclidean', metric_params=None, algorithm='auto', leaf_size=30, p=None, n_jobs=None): self.eps = eps self.min_samples = min_samples self.metric = metric self.metric_params = metric_params self.algorithm = algorithm self.leaf_size = leaf_size self.p = p self.n_jobs = n_jobs def fit(self, X, y=None, sample_weight=None): """Perform DBSCAN clustering from features or distance matrix. Parameters ---------- X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \ array of shape (n_samples, n_samples) A feature array, or array of distances between samples if ``metric='precomputed'``. sample_weight : array, shape (n_samples,), optional Weight of each sample, such that a sample with a weight of at least ``min_samples`` is by itself a core sample; a sample with negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1. y : Ignored """ X = check_array(X, accept_sparse='csr') clust = dbscan(X, sample_weight=sample_weight, **self.get_params()) self.core_sample_indices_, self.labels_ = clust if len(self.core_sample_indices_): # fix for scipy sparse indexing issue self.components_ = X[self.core_sample_indices_].copy() else: # no core samples self.components_ = np.empty((0, X.shape[1])) return self def fit_predict(self, X, y=None, sample_weight=None): """Performs clustering on X and returns cluster labels. Parameters ---------- X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \ array of shape (n_samples, n_samples) A feature array, or array of distances between samples if ``metric='precomputed'``. sample_weight : array, shape (n_samples,), optional Weight of each sample, such that a sample with a weight of at least ``min_samples`` is by itself a core sample; a sample with negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1. y : Ignored Returns ------- y : ndarray, shape (n_samples,) cluster labels """ self.fit(X, sample_weight=sample_weight) return self.labels_
import pytest import numpy as np from scipy import sparse from scipy.sparse import csgraph from scipy.linalg import eigh from sklearn.manifold.spectral_embedding_ import SpectralEmbedding from sklearn.manifold.spectral_embedding_ import _graph_is_connected from sklearn.manifold.spectral_embedding_ import _graph_connected_component from sklearn.manifold import spectral_embedding from sklearn.metrics.pairwise import rbf_kernel from sklearn.metrics import normalized_mutual_info_score from sklearn.cluster import KMeans from sklearn.datasets.samples_generator import make_blobs from sklearn.utils.extmath import _deterministic_vector_sign_flip from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_true, assert_equal, assert_raises from sklearn.utils.testing import SkipTest # non centered, sparse centers to check the centers = np.array([ [0.0, 5.0, 0.0, 0.0, 0.0], [0.0, 0.0, 4.0, 0.0, 0.0], [1.0, 0.0, 0.0, 5.0, 1.0], ]) n_samples = 1000 n_clusters, n_features = centers.shape S, true_labels = make_blobs(n_samples=n_samples, centers=centers, cluster_std=1., random_state=42) def _check_with_col_sign_flipping(A, B, tol=0.0): """ Check array A and B are equal with possible sign flipping on each columns""" sign = True for column_idx in range(A.shape[1]): sign = sign and ((((A[:, column_idx] - B[:, column_idx]) ** 2).mean() <= tol ** 2) or (((A[:, column_idx] + B[:, column_idx]) ** 2).mean() <= tol ** 2)) if not sign: return False return True def test_sparse_graph_connected_component(): rng = np.random.RandomState(42) n_samples = 300 boundaries = [0, 42, 121, 200, n_samples] p = rng.permutation(n_samples) connections = [] for start, stop in zip(boundaries[:-1], boundaries[1:]): group = p[start:stop] # Connect all elements within the group at least once via an # arbitrary path that spans the group. for i in range(len(group) - 1): connections.append((group[i], group[i + 1])) # Add some more random connections within the group min_idx, max_idx = 0, len(group) - 1 n_random_connections = 1000 source = rng.randint(min_idx, max_idx, size=n_random_connections) target = rng.randint(min_idx, max_idx, size=n_random_connections) connections.extend(zip(group[source], group[target])) # Build a symmetric affinity matrix row_idx, column_idx = tuple(np.array(connections).T) data = rng.uniform(.1, 42, size=len(connections)) affinity = sparse.coo_matrix((data, (row_idx, column_idx))) affinity = 0.5 * (affinity + affinity.T) for start, stop in zip(boundaries[:-1], boundaries[1:]): component_1 = _graph_connected_component(affinity, p[start]) component_size = stop - start assert_equal(component_1.sum(), component_size) # We should retrieve the same component mask by starting by both ends # of the group component_2 = _graph_connected_component(affinity, p[stop - 1]) assert_equal(component_2.sum(), component_size) assert_array_equal(component_1, component_2) @pytest.mark.filterwarnings("ignore:the behavior of nmi will " "change in version 0.22") def test_spectral_embedding_two_components(seed=36): # Test spectral embedding with two components random_state = np.random.RandomState(seed) n_sample = 100 affinity = np.zeros(shape=[n_sample * 2, n_sample * 2]) # first component affinity[0:n_sample, 0:n_sample] = np.abs(random_state.randn(n_sample, n_sample)) + 2 # second component affinity[n_sample::, n_sample::] = np.abs(random_state.randn(n_sample, n_sample)) + 2 # Test of internal _graph_connected_component before connection component = _graph_connected_component(affinity, 0) assert_true(component[:n_sample].all()) assert_true(not component[n_sample:].any()) component = _graph_connected_component(affinity, -1) assert_true(not component[:n_sample].any()) assert_true(component[n_sample:].all()) # connection affinity[0, n_sample + 1] = 1 affinity[n_sample + 1, 0] = 1 affinity.flat[::2 * n_sample + 1] = 0 affinity = 0.5 * (affinity + affinity.T) true_label = np.zeros(shape=2 * n_sample) true_label[0:n_sample] = 1 se_precomp = SpectralEmbedding(n_components=1, affinity="precomputed", random_state=np.random.RandomState(seed)) embedded_coordinate = se_precomp.fit_transform(affinity) # Some numpy versions are touchy with types embedded_coordinate = \ se_precomp.fit_transform(affinity.astype(np.float32)) # thresholding on the first components using 0. label_ = np.array(embedded_coordinate.ravel() < 0, dtype="float") assert_equal(normalized_mutual_info_score(true_label, label_), 1.0) def test_spectral_embedding_precomputed_affinity(seed=36): # Test spectral embedding with precomputed kernel gamma = 1.0 se_precomp = SpectralEmbedding(n_components=2, affinity="precomputed", random_state=np.random.RandomState(seed)) se_rbf = SpectralEmbedding(n_components=2, affinity="rbf", gamma=gamma, random_state=np.random.RandomState(seed)) embed_precomp = se_precomp.fit_transform(rbf_kernel(S, gamma=gamma)) embed_rbf = se_rbf.fit_transform(S) assert_array_almost_equal( se_precomp.affinity_matrix_, se_rbf.affinity_matrix_) assert_true(_check_with_col_sign_flipping(embed_precomp, embed_rbf, 0.05)) def test_spectral_embedding_callable_affinity(seed=36): # Test spectral embedding with callable affinity gamma = 0.9 kern = rbf_kernel(S, gamma=gamma) se_callable = SpectralEmbedding(n_components=2, affinity=( lambda x: rbf_kernel(x, gamma=gamma)), gamma=gamma, random_state=np.random.RandomState(seed)) se_rbf = SpectralEmbedding(n_components=2, affinity="rbf", gamma=gamma, random_state=np.random.RandomState(seed)) embed_rbf = se_rbf.fit_transform(S) embed_callable = se_callable.fit_transform(S) assert_array_almost_equal( se_callable.affinity_matrix_, se_rbf.affinity_matrix_) assert_array_almost_equal(kern, se_rbf.affinity_matrix_) assert_true( _check_with_col_sign_flipping(embed_rbf, embed_callable, 0.05)) def test_spectral_embedding_amg_solver(seed=36): # Test spectral embedding with amg solver try: from pyamg import smoothed_aggregation_solver # noqa except ImportError: raise SkipTest("pyamg not available.") se_amg = SpectralEmbedding(n_components=2, affinity="nearest_neighbors", eigen_solver="amg", n_neighbors=5, random_state=np.random.RandomState(seed)) se_arpack = SpectralEmbedding(n_components=2, affinity="nearest_neighbors", eigen_solver="arpack", n_neighbors=5, random_state=np.random.RandomState(seed)) embed_amg = se_amg.fit_transform(S) embed_arpack = se_arpack.fit_transform(S) assert_true(_check_with_col_sign_flipping(embed_amg, embed_arpack, 0.05)) @pytest.mark.filterwarnings("ignore:the behavior of nmi will " "change in version 0.22") def test_pipeline_spectral_clustering(seed=36): # Test using pipeline to do spectral clustering random_state = np.random.RandomState(seed) se_rbf = SpectralEmbedding(n_components=n_clusters, affinity="rbf", random_state=random_state) se_knn = SpectralEmbedding(n_components=n_clusters, affinity="nearest_neighbors", n_neighbors=5, random_state=random_state) for se in [se_rbf, se_knn]: km = KMeans(n_clusters=n_clusters, random_state=random_state) km.fit(se.fit_transform(S)) assert_array_almost_equal( normalized_mutual_info_score( km.labels_, true_labels), 1.0, 2) def test_spectral_embedding_unknown_eigensolver(seed=36): # Test that SpectralClustering fails with an unknown eigensolver se = SpectralEmbedding(n_components=1, affinity="precomputed", random_state=np.random.RandomState(seed), eigen_solver="<unknown>") assert_raises(ValueError, se.fit, S) def test_spectral_embedding_unknown_affinity(seed=36): # Test that SpectralClustering fails with an unknown affinity type se = SpectralEmbedding(n_components=1, affinity="<unknown>", random_state=np.random.RandomState(seed)) assert_raises(ValueError, se.fit, S) def test_connectivity(seed=36): # Test that graph connectivity test works as expected graph = np.array([[1, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 1, 1, 1], [0, 0, 0, 1, 1]]) assert_equal(_graph_is_connected(graph), False) assert_equal(_graph_is_connected(sparse.csr_matrix(graph)), False) assert_equal(_graph_is_connected(sparse.csc_matrix(graph)), False) graph = np.array([[1, 1, 0, 0, 0], [1, 1, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 1, 1, 1], [0, 0, 0, 1, 1]]) assert_equal(_graph_is_connected(graph), True) assert_equal(_graph_is_connected(sparse.csr_matrix(graph)), True) assert_equal(_graph_is_connected(sparse.csc_matrix(graph)), True) def test_spectral_embedding_deterministic(): # Test that Spectral Embedding is deterministic random_state = np.random.RandomState(36) data = random_state.randn(10, 30) sims = rbf_kernel(data) embedding_1 = spectral_embedding(sims) embedding_2 = spectral_embedding(sims) assert_array_almost_equal(embedding_1, embedding_2) def test_spectral_embedding_unnormalized(): # Test that spectral_embedding is also processing unnormalized laplacian # correctly random_state = np.random.RandomState(36) data = random_state.randn(10, 30) sims = rbf_kernel(data) n_components = 8 embedding_1 = spectral_embedding(sims, norm_laplacian=False, n_components=n_components, drop_first=False) # Verify using manual computation with dense eigh laplacian, dd = csgraph.laplacian(sims, normed=False, return_diag=True) _, diffusion_map = eigh(laplacian) embedding_2 = diffusion_map.T[:n_components] embedding_2 = _deterministic_vector_sign_flip(embedding_2).T assert_array_almost_equal(embedding_1, embedding_2) def test_spectral_embedding_first_eigen_vector(): # Test that the first eigenvector of spectral_embedding # is constant and that the second is not (for a connected graph) random_state = np.random.RandomState(36) data = random_state.randn(10, 30) sims = rbf_kernel(data) n_components = 2 for seed in range(10): embedding = spectral_embedding(sims, norm_laplacian=False, n_components=n_components, drop_first=False, random_state=seed) assert np.std(embedding[:, 0]) == pytest.approx(0) assert np.std(embedding[:, 1]) > 1e-3
vortex-ape/scikit-learn
sklearn/manifold/tests/test_spectral_embedding.py
sklearn/cluster/dbscan_.py
from __future__ import division, absolute_import, print_function import functools import itertools import operator import sys import warnings import numbers import contextlib import numpy as np from numpy.compat import pickle, basestring from . import multiarray from .multiarray import ( _fastCopyAndTranspose as fastCopyAndTranspose, ALLOW_THREADS, BUFSIZE, CLIP, MAXDIMS, MAY_SHARE_BOUNDS, MAY_SHARE_EXACT, RAISE, WRAP, arange, array, broadcast, can_cast, compare_chararrays, concatenate, copyto, dot, dtype, empty, empty_like, flatiter, frombuffer, fromfile, fromiter, fromstring, inner, int_asbuffer, lexsort, matmul, may_share_memory, min_scalar_type, ndarray, nditer, nested_iters, promote_types, putmask, result_type, set_numeric_ops, shares_memory, vdot, where, zeros, normalize_axis_index) if sys.version_info[0] < 3: from .multiarray import newbuffer, getbuffer from . import overrides from . import umath from . import shape_base from .overrides import set_module from .umath import (multiply, invert, sin, PINF, NAN) from . import numerictypes from .numerictypes import longlong, intc, int_, float_, complex_, bool_ from ._exceptions import TooHardError, AxisError from ._asarray import asarray, asanyarray from ._ufunc_config import errstate bitwise_not = invert ufunc = type(sin) newaxis = None if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins array_function_dispatch = functools.partial( overrides.array_function_dispatch, module='numpy') __all__ = [ 'newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc', 'arange', 'array', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype', 'fromstring', 'fromfile', 'frombuffer', 'int_asbuffer', 'where', 'argwhere', 'copyto', 'concatenate', 'fastCopyAndTranspose', 'lexsort', 'set_numeric_ops', 'can_cast', 'promote_types', 'min_scalar_type', 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like', 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll', 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian', 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction', 'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones', 'identity', 'allclose', 'compare_chararrays', 'putmask', 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', 'nan', 'NaN', 'False_', 'True_', 'bitwise_not', 'CLIP', 'RAISE', 'WRAP', 'MAXDIMS', 'BUFSIZE', 'ALLOW_THREADS', 'ComplexWarning', 'full', 'full_like', 'matmul', 'shares_memory', 'may_share_memory', 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'TooHardError', 'AxisError'] if sys.version_info[0] < 3: __all__.extend(['getbuffer', 'newbuffer']) @set_module('numpy') class ComplexWarning(RuntimeWarning): """ The warning raised when casting a complex dtype to a real dtype. As implemented, casting a complex number to a real discards its imaginary part, but this behavior may not be what the user actually wants. """ pass def _zeros_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None): return (a,) @array_function_dispatch(_zeros_like_dispatcher) def zeros_like(a, dtype=None, order='K', subok=True, shape=None): """ Return an array of zeros with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. dtype : data-type, optional Overrides the data type of the result. .. versionadded:: 1.6.0 order : {'C', 'F', 'A', or 'K'}, optional Overrides the memory layout of the result. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. .. versionadded:: 1.6.0 subok : bool, optional. If True, then the newly created array will use the sub-class type of 'a', otherwise it will be a base-class array. Defaults to True. shape : int or sequence of ints, optional. Overrides the shape of the result. If order='K' and the number of dimensions is unchanged, will try to keep order, otherwise, order='C' is implied. .. versionadded:: 1.17.0 Returns ------- out : ndarray Array of zeros with the same shape and type as `a`. See Also -------- empty_like : Return an empty array with shape and type of input. ones_like : Return an array of ones with shape and type of input. full_like : Return a new array with shape of input filled with value. zeros : Return a new array setting values to zero. Examples -------- >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.zeros_like(x) array([[0, 0, 0], [0, 0, 0]]) >>> y = np.arange(3, dtype=float) >>> y array([0., 1., 2.]) >>> np.zeros_like(y) array([0., 0., 0.]) """ res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape) # needed instead of a 0 to get same result as zeros for for string dtypes z = zeros(1, dtype=res.dtype) multiarray.copyto(res, z, casting='unsafe') return res @set_module('numpy') def ones(shape, dtype=None, order='C'): """ Return a new array of given shape and type, filled with ones. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired data-type for the array, e.g., `numpy.int8`. Default is `numpy.float64`. order : {'C', 'F'}, optional, default: C Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory. Returns ------- out : ndarray Array of ones with the given shape, dtype, and order. See Also -------- ones_like : Return an array of ones with shape and type of input. empty : Return a new uninitialized array. zeros : Return a new array setting values to zero. full : Return a new array of given shape filled with value. Examples -------- >>> np.ones(5) array([1., 1., 1., 1., 1.]) >>> np.ones((5,), dtype=int) array([1, 1, 1, 1, 1]) >>> np.ones((2, 1)) array([[1.], [1.]]) >>> s = (2,2) >>> np.ones(s) array([[1., 1.], [1., 1.]]) """ a = empty(shape, dtype, order) multiarray.copyto(a, 1, casting='unsafe') return a def _ones_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None): return (a,) @array_function_dispatch(_ones_like_dispatcher) def ones_like(a, dtype=None, order='K', subok=True, shape=None): """ Return an array of ones with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. dtype : data-type, optional Overrides the data type of the result. .. versionadded:: 1.6.0 order : {'C', 'F', 'A', or 'K'}, optional Overrides the memory layout of the result. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. .. versionadded:: 1.6.0 subok : bool, optional. If True, then the newly created array will use the sub-class type of 'a', otherwise it will be a base-class array. Defaults to True. shape : int or sequence of ints, optional. Overrides the shape of the result. If order='K' and the number of dimensions is unchanged, will try to keep order, otherwise, order='C' is implied. .. versionadded:: 1.17.0 Returns ------- out : ndarray Array of ones with the same shape and type as `a`. See Also -------- empty_like : Return an empty array with shape and type of input. zeros_like : Return an array of zeros with shape and type of input. full_like : Return a new array with shape of input filled with value. ones : Return a new array setting values to one. Examples -------- >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.ones_like(x) array([[1, 1, 1], [1, 1, 1]]) >>> y = np.arange(3, dtype=float) >>> y array([0., 1., 2.]) >>> np.ones_like(y) array([1., 1., 1.]) """ res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape) multiarray.copyto(res, 1, casting='unsafe') return res @set_module('numpy') def full(shape, fill_value, dtype=None, order='C'): """ Return a new array of given shape and type, filled with `fill_value`. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. fill_value : scalar Fill value. dtype : data-type, optional The desired data-type for the array The default, `None`, means `np.array(fill_value).dtype`. order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. Returns ------- out : ndarray Array of `fill_value` with the given shape, dtype, and order. See Also -------- full_like : Return a new array with shape of input filled with value. empty : Return a new uninitialized array. ones : Return a new array setting values to one. zeros : Return a new array setting values to zero. Examples -------- >>> np.full((2, 2), np.inf) array([[inf, inf], [inf, inf]]) >>> np.full((2, 2), 10) array([[10, 10], [10, 10]]) """ if dtype is None: dtype = array(fill_value).dtype a = empty(shape, dtype, order) multiarray.copyto(a, fill_value, casting='unsafe') return a def _full_like_dispatcher(a, fill_value, dtype=None, order=None, subok=None, shape=None): return (a,) @array_function_dispatch(_full_like_dispatcher) def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None): """ Return a full array with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. fill_value : scalar Fill value. dtype : data-type, optional Overrides the data type of the result. order : {'C', 'F', 'A', or 'K'}, optional Overrides the memory layout of the result. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. subok : bool, optional. If True, then the newly created array will use the sub-class type of 'a', otherwise it will be a base-class array. Defaults to True. shape : int or sequence of ints, optional. Overrides the shape of the result. If order='K' and the number of dimensions is unchanged, will try to keep order, otherwise, order='C' is implied. .. versionadded:: 1.17.0 Returns ------- out : ndarray Array of `fill_value` with the same shape and type as `a`. See Also -------- empty_like : Return an empty array with shape and type of input. ones_like : Return an array of ones with shape and type of input. zeros_like : Return an array of zeros with shape and type of input. full : Return a new array of given shape filled with value. Examples -------- >>> x = np.arange(6, dtype=int) >>> np.full_like(x, 1) array([1, 1, 1, 1, 1, 1]) >>> np.full_like(x, 0.1) array([0, 0, 0, 0, 0, 0]) >>> np.full_like(x, 0.1, dtype=np.double) array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) >>> np.full_like(x, np.nan, dtype=np.double) array([nan, nan, nan, nan, nan, nan]) >>> y = np.arange(6, dtype=np.double) >>> np.full_like(y, 0.1) array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) """ res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape) multiarray.copyto(res, fill_value, casting='unsafe') return res def _count_nonzero_dispatcher(a, axis=None): return (a,) @array_function_dispatch(_count_nonzero_dispatcher) def count_nonzero(a, axis=None): """ Counts the number of non-zero values in the array ``a``. The word "non-zero" is in reference to the Python 2.x built-in method ``__nonzero__()`` (renamed ``__bool__()`` in Python 3.x) of Python objects that tests an object's "truthfulness". For example, any number is considered truthful if it is nonzero, whereas any string is considered truthful if it is not the empty string. Thus, this function (recursively) counts how many elements in ``a`` (and in sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()`` method evaluated to ``True``. Parameters ---------- a : array_like The array for which to count non-zeros. axis : int or tuple, optional Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of ``a``. .. versionadded:: 1.12.0 Returns ------- count : int or array of int Number of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned. See Also -------- nonzero : Return the coordinates of all the non-zero values. Examples -------- >>> np.count_nonzero(np.eye(4)) 4 >>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]]) 5 >>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]], axis=0) array([1, 1, 1, 1, 1]) >>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]], axis=1) array([2, 3]) """ if axis is None: return multiarray.count_nonzero(a) a = asanyarray(a) # TODO: this works around .astype(bool) not working properly (gh-9847) if np.issubdtype(a.dtype, np.character): a_bool = a != a.dtype.type() else: a_bool = a.astype(np.bool_, copy=False) return a_bool.sum(axis=axis, dtype=np.intp) @set_module('numpy') def isfortran(a): """ Check if the array is Fortran contiguous but *not* C contiguous. This function is obsolete and, because of changes due to relaxed stride checking, its return value for the same array may differ for versions of NumPy >= 1.10.0 and previous versions. If you only want to check if an array is Fortran contiguous use ``a.flags.f_contiguous`` instead. Parameters ---------- a : ndarray Input array. Returns ------- isfortran : bool Returns True if the array is Fortran contiguous but *not* C contiguous. Examples -------- np.array allows to specify whether the array is written in C-contiguous order (last index varies the fastest), or FORTRAN-contiguous order in memory (first index varies the fastest). >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C') >>> a array([[1, 2, 3], [4, 5, 6]]) >>> np.isfortran(a) False >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F') >>> b array([[1, 2, 3], [4, 5, 6]]) >>> np.isfortran(b) True The transpose of a C-ordered array is a FORTRAN-ordered array. >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C') >>> a array([[1, 2, 3], [4, 5, 6]]) >>> np.isfortran(a) False >>> b = a.T >>> b array([[1, 4], [2, 5], [3, 6]]) >>> np.isfortran(b) True C-ordered arrays evaluate as False even if they are also FORTRAN-ordered. >>> np.isfortran(np.array([1, 2], order='FORTRAN')) False """ return a.flags.fnc def _argwhere_dispatcher(a): return (a,) @array_function_dispatch(_argwhere_dispatcher) def argwhere(a): """ Find the indices of array elements that are non-zero, grouped by element. Parameters ---------- a : array_like Input data. Returns ------- index_array : (N, a.ndim) ndarray Indices of elements that are non-zero. Indices are grouped by element. This array will have shape ``(N, a.ndim)`` where ``N`` is the number of non-zero items. See Also -------- where, nonzero Notes ----- ``np.argwhere(a)`` is almost the same as ``np.transpose(np.nonzero(a))``, but produces a result of the correct shape for a 0D array. The output of ``argwhere`` is not suitable for indexing arrays. For this purpose use ``nonzero(a)`` instead. Examples -------- >>> x = np.arange(6).reshape(2,3) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.argwhere(x>1) array([[0, 2], [1, 0], [1, 1], [1, 2]]) """ # nonzero does not behave well on 0d, so promote to 1d if np.ndim(a) == 0: a = shape_base.atleast_1d(a) # then remove the added dimension return argwhere(a)[:,:0] return transpose(nonzero(a)) def _flatnonzero_dispatcher(a): return (a,) @array_function_dispatch(_flatnonzero_dispatcher) def flatnonzero(a): """ Return indices that are non-zero in the flattened version of a. This is equivalent to np.nonzero(np.ravel(a))[0]. Parameters ---------- a : array_like Input data. Returns ------- res : ndarray Output array, containing the indices of the elements of `a.ravel()` that are non-zero. See Also -------- nonzero : Return the indices of the non-zero elements of the input array. ravel : Return a 1-D array containing the elements of the input array. Examples -------- >>> x = np.arange(-2, 3) >>> x array([-2, -1, 0, 1, 2]) >>> np.flatnonzero(x) array([0, 1, 3, 4]) Use the indices of the non-zero elements as an index array to extract these elements: >>> x.ravel()[np.flatnonzero(x)] array([-2, -1, 1, 2]) """ return np.nonzero(np.ravel(a))[0] _mode_from_name_dict = {'v': 0, 's': 1, 'f': 2} def _mode_from_name(mode): if isinstance(mode, basestring): return _mode_from_name_dict[mode.lower()[0]] return mode def _correlate_dispatcher(a, v, mode=None): return (a, v) @array_function_dispatch(_correlate_dispatcher) def correlate(a, v, mode='valid'): """ Cross-correlation of two 1-dimensional sequences. This function computes the correlation as generally defined in signal processing texts:: c_{av}[k] = sum_n a[n+k] * conj(v[n]) with a and v sequences being zero-padded where necessary and conj being the conjugate. Parameters ---------- a, v : array_like Input sequences. mode : {'valid', 'same', 'full'}, optional Refer to the `convolve` docstring. Note that the default is 'valid', unlike `convolve`, which uses 'full'. old_behavior : bool `old_behavior` was removed in NumPy 1.10. If you need the old behavior, use `multiarray.correlate`. Returns ------- out : ndarray Discrete cross-correlation of `a` and `v`. See Also -------- convolve : Discrete, linear convolution of two one-dimensional sequences. multiarray.correlate : Old, no conjugate, version of correlate. Notes ----- The definition of correlation above is not unique and sometimes correlation may be defined differently. Another common definition is:: c'_{av}[k] = sum_n a[n] conj(v[n+k]) which is related to ``c_{av}[k]`` by ``c'_{av}[k] = c_{av}[-k]``. Examples -------- >>> np.correlate([1, 2, 3], [0, 1, 0.5]) array([3.5]) >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same") array([2. , 3.5, 3. ]) >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full") array([0.5, 2. , 3.5, 3. , 0. ]) Using complex sequences: >>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full') array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ]) Note that you get the time reversed, complex conjugated result when the two input sequences change places, i.e., ``c_{va}[k] = c^{*}_{av}[-k]``: >>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full') array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j]) """ mode = _mode_from_name(mode) return multiarray.correlate2(a, v, mode) def _convolve_dispatcher(a, v, mode=None): return (a, v) @array_function_dispatch(_convolve_dispatcher) def convolve(a, v, mode='full'): """ Returns the discrete, linear convolution of two one-dimensional sequences. The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal [1]_. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions. If `v` is longer than `a`, the arrays are swapped before computation. Parameters ---------- a : (N,) array_like First one-dimensional input array. v : (M,) array_like Second one-dimensional input array. mode : {'full', 'valid', 'same'}, optional 'full': By default, mode is 'full'. This returns the convolution at each point of overlap, with an output shape of (N+M-1,). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen. 'same': Mode 'same' returns output of length ``max(M, N)``. Boundary effects are still visible. 'valid': Mode 'valid' returns output of length ``max(M, N) - min(M, N) + 1``. The convolution product is only given for points where the signals overlap completely. Values outside the signal boundary have no effect. Returns ------- out : ndarray Discrete, linear convolution of `a` and `v`. See Also -------- scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier Transform. scipy.linalg.toeplitz : Used to construct the convolution operator. polymul : Polynomial multiplication. Same output as convolve, but also accepts poly1d objects as input. Notes ----- The discrete convolution operation is defined as .. math:: (a * v)[n] = \\sum_{m = -\\infty}^{\\infty} a[m] v[n - m] It can be shown that a convolution :math:`x(t) * y(t)` in time/space is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier domain, after appropriate padding (padding is necessary to prevent circular convolution). Since multiplication is more efficient (faster) than convolution, the function `scipy.signal.fftconvolve` exploits the FFT to calculate the convolution of large data-sets. References ---------- .. [1] Wikipedia, "Convolution", https://en.wikipedia.org/wiki/Convolution Examples -------- Note how the convolution operator flips the second array before "sliding" the two across one another: >>> np.convolve([1, 2, 3], [0, 1, 0.5]) array([0. , 1. , 2.5, 4. , 1.5]) Only return the middle values of the convolution. Contains boundary effects, where zeros are taken into account: >>> np.convolve([1,2,3],[0,1,0.5], 'same') array([1. , 2.5, 4. ]) The two arrays are of the same length, so there is only one position where they completely overlap: >>> np.convolve([1,2,3],[0,1,0.5], 'valid') array([2.5]) """ a, v = array(a, copy=False, ndmin=1), array(v, copy=False, ndmin=1) if (len(v) > len(a)): a, v = v, a if len(a) == 0: raise ValueError('a cannot be empty') if len(v) == 0: raise ValueError('v cannot be empty') mode = _mode_from_name(mode) return multiarray.correlate(a, v[::-1], mode) def _outer_dispatcher(a, b, out=None): return (a, b, out) @array_function_dispatch(_outer_dispatcher) def outer(a, b, out=None): """ Compute the outer product of two vectors. Given two vectors, ``a = [a0, a1, ..., aM]`` and ``b = [b0, b1, ..., bN]``, the outer product [1]_ is:: [[a0*b0 a0*b1 ... a0*bN ] [a1*b0 . [ ... . [aM*b0 aM*bN ]] Parameters ---------- a : (M,) array_like First input vector. Input is flattened if not already 1-dimensional. b : (N,) array_like Second input vector. Input is flattened if not already 1-dimensional. out : (M, N) ndarray, optional A location where the result is stored .. versionadded:: 1.9.0 Returns ------- out : (M, N) ndarray ``out[i, j] = a[i] * b[j]`` See also -------- inner einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent. ufunc.outer : A generalization to N dimensions and other operations. ``np.multiply.outer(a.ravel(), b.ravel())`` is the equivalent. References ---------- .. [1] : G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd ed., Baltimore, MD, Johns Hopkins University Press, 1996, pg. 8. Examples -------- Make a (*very* coarse) grid for computing a Mandelbrot set: >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5)) >>> rl array([[-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.]]) >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,))) >>> im array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j], [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j], [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]]) >>> grid = rl + im >>> grid array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j], [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j], [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j], [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j], [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]]) An example using a "vector" of letters: >>> x = np.array(['a', 'b', 'c'], dtype=object) >>> np.outer(x, [1, 2, 3]) array([['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']], dtype=object) """ a = asarray(a) b = asarray(b) return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out) def _tensordot_dispatcher(a, b, axes=None): return (a, b) @array_function_dispatch(_tensordot_dispatcher) def tensordot(a, b, axes=2): """ Compute tensor dot product along specified axes. Given two tensors, `a` and `b`, and an array_like object containing two array_like objects, ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s elements (components) over the axes specified by ``a_axes`` and ``b_axes``. The third argument can be a single non-negative integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions of `a` and the first ``N`` dimensions of `b` are summed over. Parameters ---------- a, b : array_like Tensors to "dot". axes : int or (2,) array_like * integer_like If an int N, sum over the last N axes of `a` and the first N axes of `b` in order. The sizes of the corresponding axes must match. * (2,) array_like Or, a list of axes to be summed over, first sequence applying to `a`, second to `b`. Both elements array_like must be of the same length. Returns ------- output : ndarray The tensor dot product of the input. See Also -------- dot, einsum Notes ----- Three common use cases are: * ``axes = 0`` : tensor product :math:`a\\otimes b` * ``axes = 1`` : tensor dot product :math:`a\\cdot b` * ``axes = 2`` : (default) tensor double contraction :math:`a:b` When `axes` is integer_like, the sequence for evaluation will be: first the -Nth axis in `a` and 0th axis in `b`, and the -1th axis in `a` and Nth axis in `b` last. When there is more than one axis to sum over - and they are not the last (first) axes of `a` (`b`) - the argument `axes` should consist of two sequences of the same length, with the first axis to sum over given first in both sequences, the second axis second, and so forth. Examples -------- A "traditional" example: >>> a = np.arange(60.).reshape(3,4,5) >>> b = np.arange(24.).reshape(4,3,2) >>> c = np.tensordot(a,b, axes=([1,0],[0,1])) >>> c.shape (5, 2) >>> c array([[4400., 4730.], [4532., 4874.], [4664., 5018.], [4796., 5162.], [4928., 5306.]]) >>> # A slower but equivalent way of computing the same... >>> d = np.zeros((5,2)) >>> for i in range(5): ... for j in range(2): ... for k in range(3): ... for n in range(4): ... d[i,j] += a[k,n,i] * b[n,k,j] >>> c == d array([[ True, True], [ True, True], [ True, True], [ True, True], [ True, True]]) An extended example taking advantage of the overloading of + and \\*: >>> a = np.array(range(1, 9)) >>> a.shape = (2, 2, 2) >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object) >>> A.shape = (2, 2) >>> a; A array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) array([['a', 'b'], ['c', 'd']], dtype=object) >>> np.tensordot(a, A) # third argument default is 2 for double-contraction array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object) >>> np.tensordot(a, A, 1) array([[['acc', 'bdd'], ['aaacccc', 'bbbdddd']], [['aaaaacccccc', 'bbbbbdddddd'], ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object) >>> np.tensordot(a, A, 0) # tensor product (result too long to incl.) array([[[[['a', 'b'], ['c', 'd']], ... >>> np.tensordot(a, A, (0, 1)) array([[['abbbbb', 'cddddd'], ['aabbbbbb', 'ccdddddd']], [['aaabbbbbbb', 'cccddddddd'], ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object) >>> np.tensordot(a, A, (2, 1)) array([[['abb', 'cdd'], ['aaabbbb', 'cccdddd']], [['aaaaabbbbbb', 'cccccdddddd'], ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object) >>> np.tensordot(a, A, ((0, 1), (0, 1))) array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object) >>> np.tensordot(a, A, ((2, 1), (1, 0))) array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object) """ try: iter(axes) except Exception: axes_a = list(range(-axes, 0)) axes_b = list(range(0, axes)) else: axes_a, axes_b = axes try: na = len(axes_a) axes_a = list(axes_a) except TypeError: axes_a = [axes_a] na = 1 try: nb = len(axes_b) axes_b = list(axes_b) except TypeError: axes_b = [axes_b] nb = 1 a, b = asarray(a), asarray(b) as_ = a.shape nda = a.ndim bs = b.shape ndb = b.ndim equal = True if na != nb: equal = False else: for k in range(na): if as_[axes_a[k]] != bs[axes_b[k]]: equal = False break if axes_a[k] < 0: axes_a[k] += nda if axes_b[k] < 0: axes_b[k] += ndb if not equal: raise ValueError("shape-mismatch for sum") # Move the axes to sum over to the end of "a" # and to the front of "b" notin = [k for k in range(nda) if k not in axes_a] newaxes_a = notin + axes_a N2 = 1 for axis in axes_a: N2 *= as_[axis] newshape_a = (int(multiply.reduce([as_[ax] for ax in notin])), N2) olda = [as_[axis] for axis in notin] notin = [k for k in range(ndb) if k not in axes_b] newaxes_b = axes_b + notin N2 = 1 for axis in axes_b: N2 *= bs[axis] newshape_b = (N2, int(multiply.reduce([bs[ax] for ax in notin]))) oldb = [bs[axis] for axis in notin] at = a.transpose(newaxes_a).reshape(newshape_a) bt = b.transpose(newaxes_b).reshape(newshape_b) res = dot(at, bt) return res.reshape(olda + oldb) def _roll_dispatcher(a, shift, axis=None): return (a,) @array_function_dispatch(_roll_dispatcher) def roll(a, shift, axis=None): """ Roll array elements along a given axis. Elements that roll beyond the last position are re-introduced at the first. Parameters ---------- a : array_like Input array. shift : int or tuple of ints The number of places by which elements are shifted. If a tuple, then `axis` must be a tuple of the same size, and each of the given axes is shifted by the corresponding number. If an int while `axis` is a tuple of ints, then the same value is used for all given axes. axis : int or tuple of ints, optional Axis or axes along which elements are shifted. By default, the array is flattened before shifting, after which the original shape is restored. Returns ------- res : ndarray Output array, with the same shape as `a`. See Also -------- rollaxis : Roll the specified axis backwards, until it lies in a given position. Notes ----- .. versionadded:: 1.12.0 Supports rolling over multiple dimensions simultaneously. Examples -------- >>> x = np.arange(10) >>> np.roll(x, 2) array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]) >>> np.roll(x, -2) array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1]) >>> x2 = np.reshape(x, (2,5)) >>> x2 array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> np.roll(x2, 1) array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]]) >>> np.roll(x2, -1) array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 0]]) >>> np.roll(x2, 1, axis=0) array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]) >>> np.roll(x2, -1, axis=0) array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]) >>> np.roll(x2, 1, axis=1) array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]) >>> np.roll(x2, -1, axis=1) array([[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]]) """ a = asanyarray(a) if axis is None: return roll(a.ravel(), shift, 0).reshape(a.shape) else: axis = normalize_axis_tuple(axis, a.ndim, allow_duplicate=True) broadcasted = broadcast(shift, axis) if broadcasted.ndim > 1: raise ValueError( "'shift' and 'axis' should be scalars or 1D sequences") shifts = {ax: 0 for ax in range(a.ndim)} for sh, ax in broadcasted: shifts[ax] += sh rolls = [((slice(None), slice(None)),)] * a.ndim for ax, offset in shifts.items(): offset %= a.shape[ax] or 1 # If `a` is empty, nothing matters. if offset: # (original, result), (original, result) rolls[ax] = ((slice(None, -offset), slice(offset, None)), (slice(-offset, None), slice(None, offset))) result = empty_like(a) for indices in itertools.product(*rolls): arr_index, res_index = zip(*indices) result[res_index] = a[arr_index] return result def _rollaxis_dispatcher(a, axis, start=None): return (a,) @array_function_dispatch(_rollaxis_dispatcher) def rollaxis(a, axis, start=0): """ Roll the specified axis backwards, until it lies in a given position. This function continues to be supported for backward compatibility, but you should prefer `moveaxis`. The `moveaxis` function was added in NumPy 1.11. Parameters ---------- a : ndarray Input array. axis : int The axis to roll backwards. The positions of the other axes do not change relative to one another. start : int, optional The axis is rolled until it lies before this position. The default, 0, results in a "complete" roll. Returns ------- res : ndarray For NumPy >= 1.10.0 a view of `a` is always returned. For earlier NumPy versions a view of `a` is returned only if the order of the axes is changed, otherwise the input array is returned. See Also -------- moveaxis : Move array axes to new positions. roll : Roll the elements of an array by a number of positions along a given axis. Examples -------- >>> a = np.ones((3,4,5,6)) >>> np.rollaxis(a, 3, 1).shape (3, 6, 4, 5) >>> np.rollaxis(a, 2).shape (5, 3, 4, 6) >>> np.rollaxis(a, 1, 4).shape (3, 5, 6, 4) """ n = a.ndim axis = normalize_axis_index(axis, n) if start < 0: start += n msg = "'%s' arg requires %d <= %s < %d, but %d was passed in" if not (0 <= start < n + 1): raise AxisError(msg % ('start', -n, 'start', n + 1, start)) if axis < start: # it's been removed start -= 1 if axis == start: return a[...] axes = list(range(0, n)) axes.remove(axis) axes.insert(start, axis) return a.transpose(axes) def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False): """ Normalizes an axis argument into a tuple of non-negative integer axes. This handles shorthands such as ``1`` and converts them to ``(1,)``, as well as performing the handling of negative indices covered by `normalize_axis_index`. By default, this forbids axes from being specified multiple times. Used internally by multi-axis-checking logic. .. versionadded:: 1.13.0 Parameters ---------- axis : int, iterable of int The un-normalized index or indices of the axis. ndim : int The number of dimensions of the array that `axis` should be normalized against. argname : str, optional A prefix to put before the error message, typically the name of the argument. allow_duplicate : bool, optional If False, the default, disallow an axis from being specified twice. Returns ------- normalized_axes : tuple of int The normalized axis index, such that `0 <= normalized_axis < ndim` Raises ------ AxisError If any axis provided is out of range ValueError If an axis is repeated See also -------- normalize_axis_index : normalizing a single scalar axis """ # Optimization to speed-up the most common cases. if type(axis) not in (tuple, list): try: axis = [operator.index(axis)] except TypeError: pass # Going via an iterator directly is slower than via list comprehension. axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis]) if not allow_duplicate and len(set(axis)) != len(axis): if argname: raise ValueError('repeated axis in `{}` argument'.format(argname)) else: raise ValueError('repeated axis') return axis def _moveaxis_dispatcher(a, source, destination): return (a,) @array_function_dispatch(_moveaxis_dispatcher) def moveaxis(a, source, destination): """ Move axes of an array to new positions. Other axes remain in their original order. .. versionadded:: 1.11.0 Parameters ---------- a : np.ndarray The array whose axes should be reordered. source : int or sequence of int Original positions of the axes to move. These must be unique. destination : int or sequence of int Destination positions for each of the original axes. These must also be unique. Returns ------- result : np.ndarray Array with moved axes. This array is a view of the input array. See Also -------- transpose: Permute the dimensions of an array. swapaxes: Interchange two axes of an array. Examples -------- >>> x = np.zeros((3, 4, 5)) >>> np.moveaxis(x, 0, -1).shape (4, 5, 3) >>> np.moveaxis(x, -1, 0).shape (5, 3, 4) These all achieve the same result: >>> np.transpose(x).shape (5, 4, 3) >>> np.swapaxes(x, 0, -1).shape (5, 4, 3) >>> np.moveaxis(x, [0, 1], [-1, -2]).shape (5, 4, 3) >>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape (5, 4, 3) """ try: # allow duck-array types if they define transpose transpose = a.transpose except AttributeError: a = asarray(a) transpose = a.transpose source = normalize_axis_tuple(source, a.ndim, 'source') destination = normalize_axis_tuple(destination, a.ndim, 'destination') if len(source) != len(destination): raise ValueError('`source` and `destination` arguments must have ' 'the same number of elements') order = [n for n in range(a.ndim) if n not in source] for dest, src in sorted(zip(destination, source)): order.insert(dest, src) result = transpose(order) return result # fix hack in scipy which imports this function def _move_axis_to_0(a, axis): return moveaxis(a, axis, 0) def _cross_dispatcher(a, b, axisa=None, axisb=None, axisc=None, axis=None): return (a, b) @array_function_dispatch(_cross_dispatcher) def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): """ Return the cross product of two (arrays of) vectors. The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors are defined by the last axis of `a` and `b` by default, and these axes can have dimensions 2 or 3. Where the dimension of either `a` or `b` is 2, the third component of the input vector is assumed to be zero and the cross product calculated accordingly. In cases where both input vectors have dimension 2, the z-component of the cross product is returned. Parameters ---------- a : array_like Components of the first vector(s). b : array_like Components of the second vector(s). axisa : int, optional Axis of `a` that defines the vector(s). By default, the last axis. axisb : int, optional Axis of `b` that defines the vector(s). By default, the last axis. axisc : int, optional Axis of `c` containing the cross product vector(s). Ignored if both input vectors have dimension 2, as the return is scalar. By default, the last axis. axis : int, optional If defined, the axis of `a`, `b` and `c` that defines the vector(s) and cross product(s). Overrides `axisa`, `axisb` and `axisc`. Returns ------- c : ndarray Vector cross product(s). Raises ------ ValueError When the dimension of the vector(s) in `a` and/or `b` does not equal 2 or 3. See Also -------- inner : Inner product outer : Outer product. ix_ : Construct index arrays. Notes ----- .. versionadded:: 1.9.0 Supports full broadcasting of the inputs. Examples -------- Vector cross-product. >>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> np.cross(x, y) array([-3, 6, -3]) One vector with dimension 2. >>> x = [1, 2] >>> y = [4, 5, 6] >>> np.cross(x, y) array([12, -6, -3]) Equivalently: >>> x = [1, 2, 0] >>> y = [4, 5, 6] >>> np.cross(x, y) array([12, -6, -3]) Both vectors with dimension 2. >>> x = [1,2] >>> y = [4,5] >>> np.cross(x, y) array(-3) Multiple vector cross-products. Note that the direction of the cross product vector is defined by the `right-hand rule`. >>> x = np.array([[1,2,3], [4,5,6]]) >>> y = np.array([[4,5,6], [1,2,3]]) >>> np.cross(x, y) array([[-3, 6, -3], [ 3, -6, 3]]) The orientation of `c` can be changed using the `axisc` keyword. >>> np.cross(x, y, axisc=0) array([[-3, 3], [ 6, -6], [-3, 3]]) Change the vector definition of `x` and `y` using `axisa` and `axisb`. >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]]) >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]]) >>> np.cross(x, y) array([[ -6, 12, -6], [ 0, 0, 0], [ 6, -12, 6]]) >>> np.cross(x, y, axisa=0, axisb=0) array([[-24, 48, -24], [-30, 60, -30], [-36, 72, -36]]) """ if axis is not None: axisa, axisb, axisc = (axis,) * 3 a = asarray(a) b = asarray(b) # Check axisa and axisb are within bounds axisa = normalize_axis_index(axisa, a.ndim, msg_prefix='axisa') axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb') # Move working axis to the end of the shape a = moveaxis(a, axisa, -1) b = moveaxis(b, axisb, -1) msg = ("incompatible dimensions for cross product\n" "(dimension must be 2 or 3)") if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3): raise ValueError(msg) # Create the output array shape = broadcast(a[..., 0], b[..., 0]).shape if a.shape[-1] == 3 or b.shape[-1] == 3: shape += (3,) # Check axisc is within bounds axisc = normalize_axis_index(axisc, len(shape), msg_prefix='axisc') dtype = promote_types(a.dtype, b.dtype) cp = empty(shape, dtype) # create local aliases for readability a0 = a[..., 0] a1 = a[..., 1] if a.shape[-1] == 3: a2 = a[..., 2] b0 = b[..., 0] b1 = b[..., 1] if b.shape[-1] == 3: b2 = b[..., 2] if cp.ndim != 0 and cp.shape[-1] == 3: cp0 = cp[..., 0] cp1 = cp[..., 1] cp2 = cp[..., 2] if a.shape[-1] == 2: if b.shape[-1] == 2: # a0 * b1 - a1 * b0 multiply(a0, b1, out=cp) cp -= a1 * b0 return cp else: assert b.shape[-1] == 3 # cp0 = a1 * b2 - 0 (a2 = 0) # cp1 = 0 - a0 * b2 (a2 = 0) # cp2 = a0 * b1 - a1 * b0 multiply(a1, b2, out=cp0) multiply(a0, b2, out=cp1) negative(cp1, out=cp1) multiply(a0, b1, out=cp2) cp2 -= a1 * b0 else: assert a.shape[-1] == 3 if b.shape[-1] == 3: # cp0 = a1 * b2 - a2 * b1 # cp1 = a2 * b0 - a0 * b2 # cp2 = a0 * b1 - a1 * b0 multiply(a1, b2, out=cp0) tmp = array(a2 * b1) cp0 -= tmp multiply(a2, b0, out=cp1) multiply(a0, b2, out=tmp) cp1 -= tmp multiply(a0, b1, out=cp2) multiply(a1, b0, out=tmp) cp2 -= tmp else: assert b.shape[-1] == 2 # cp0 = 0 - a2 * b1 (b2 = 0) # cp1 = a2 * b0 - 0 (b2 = 0) # cp2 = a0 * b1 - a1 * b0 multiply(a2, b1, out=cp0) negative(cp0, out=cp0) multiply(a2, b0, out=cp1) multiply(a0, b1, out=cp2) cp2 -= a1 * b0 return moveaxis(cp, -1, axisc) little_endian = (sys.byteorder == 'little') @set_module('numpy') def indices(dimensions, dtype=int, sparse=False): """ Return an array representing the indices of a grid. Compute an array where the subarrays contain index values 0, 1, ... varying only along the corresponding axis. Parameters ---------- dimensions : sequence of ints The shape of the grid. dtype : dtype, optional Data type of the result. sparse : boolean, optional Return a sparse representation of the grid instead of a dense representation. Default is False. .. versionadded:: 1.17 Returns ------- grid : one ndarray or tuple of ndarrays If sparse is False: Returns one array of grid indices, ``grid.shape = (len(dimensions),) + tuple(dimensions)``. If sparse is True: Returns a tuple of arrays, with ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with dimensions[i] in the ith place See Also -------- mgrid, ogrid, meshgrid Notes ----- The output shape in the dense case is obtained by prepending the number of dimensions in front of the tuple of dimensions, i.e. if `dimensions` is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is ``(N, r0, ..., rN-1)``. The subarrays ``grid[k]`` contains the N-D array of indices along the ``k-th`` axis. Explicitly:: grid[k, i0, i1, ..., iN-1] = ik Examples -------- >>> grid = np.indices((2, 3)) >>> grid.shape (2, 2, 3) >>> grid[0] # row indices array([[0, 0, 0], [1, 1, 1]]) >>> grid[1] # column indices array([[0, 1, 2], [0, 1, 2]]) The indices can be used as an index into an array. >>> x = np.arange(20).reshape(5, 4) >>> row, col = np.indices((2, 3)) >>> x[row, col] array([[0, 1, 2], [4, 5, 6]]) Note that it would be more straightforward in the above example to extract the required elements directly with ``x[:2, :3]``. If sparse is set to true, the grid will be returned in a sparse representation. >>> i, j = np.indices((2, 3), sparse=True) >>> i.shape (2, 1) >>> j.shape (1, 3) >>> i # row indices array([[0], [1]]) >>> j # column indices array([[0, 1, 2]]) """ dimensions = tuple(dimensions) N = len(dimensions) shape = (1,)*N if sparse: res = tuple() else: res = empty((N,)+dimensions, dtype=dtype) for i, dim in enumerate(dimensions): idx = arange(dim, dtype=dtype).reshape( shape[:i] + (dim,) + shape[i+1:] ) if sparse: res = res + (idx,) else: res[i] = idx return res @set_module('numpy') def fromfunction(function, shape, **kwargs): """ Construct an array by executing a function over each coordinate. The resulting array therefore has a value ``fn(x, y, z)`` at coordinate ``(x, y, z)``. Parameters ---------- function : callable The function is called with N parameters, where N is the rank of `shape`. Each parameter represents the coordinates of the array varying along a specific axis. For example, if `shape` were ``(2, 2)``, then the parameters would be ``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])`` shape : (N,) tuple of ints Shape of the output array, which also determines the shape of the coordinate arrays passed to `function`. dtype : data-type, optional Data-type of the coordinate arrays passed to `function`. By default, `dtype` is float. Returns ------- fromfunction : any The result of the call to `function` is passed back directly. Therefore the shape of `fromfunction` is completely determined by `function`. If `function` returns a scalar value, the shape of `fromfunction` would not match the `shape` parameter. See Also -------- indices, meshgrid Notes ----- Keywords other than `dtype` are passed to `function`. Examples -------- >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int) array([[ True, False, False], [False, True, False], [False, False, True]]) >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int) array([[0, 1, 2], [1, 2, 3], [2, 3, 4]]) """ dtype = kwargs.pop('dtype', float) args = indices(shape, dtype=dtype) return function(*args, **kwargs) def _frombuffer(buf, dtype, shape, order): return frombuffer(buf, dtype=dtype).reshape(shape, order=order) @set_module('numpy') def isscalar(num): """ Returns True if the type of `num` is a scalar type. Parameters ---------- num : any Input argument, can be of any type and shape. Returns ------- val : bool True if `num` is a scalar type, False if it is not. See Also -------- ndim : Get the number of dimensions of an array Notes ----- In almost all cases ``np.ndim(x) == 0`` should be used instead of this function, as that will also return true for 0d arrays. This is how numpy overloads functions in the style of the ``dx`` arguments to `gradient` and the ``bins`` argument to `histogram`. Some key differences: +--------------------------------------+---------------+-------------------+ | x |``isscalar(x)``|``np.ndim(x) == 0``| +======================================+===============+===================+ | PEP 3141 numeric objects (including | ``True`` | ``True`` | | builtins) | | | +--------------------------------------+---------------+-------------------+ | builtin string and buffer objects | ``True`` | ``True`` | +--------------------------------------+---------------+-------------------+ | other builtin objects, like | ``False`` | ``True`` | | `pathlib.Path`, `Exception`, | | | | the result of `re.compile` | | | +--------------------------------------+---------------+-------------------+ | third-party objects like | ``False`` | ``True`` | | `matplotlib.figure.Figure` | | | +--------------------------------------+---------------+-------------------+ | zero-dimensional numpy arrays | ``False`` | ``True`` | +--------------------------------------+---------------+-------------------+ | other numpy arrays | ``False`` | ``False`` | +--------------------------------------+---------------+-------------------+ | `list`, `tuple`, and other sequence | ``False`` | ``False`` | | objects | | | +--------------------------------------+---------------+-------------------+ Examples -------- >>> np.isscalar(3.1) True >>> np.isscalar(np.array(3.1)) False >>> np.isscalar([3.1]) False >>> np.isscalar(False) True >>> np.isscalar('numpy') True NumPy supports PEP 3141 numbers: >>> from fractions import Fraction >>> np.isscalar(Fraction(5, 17)) True >>> from numbers import Number >>> np.isscalar(Number()) True """ return (isinstance(num, generic) or type(num) in ScalarType or isinstance(num, numbers.Number)) @set_module('numpy') def binary_repr(num, width=None): """ Return the binary representation of the input number as a string. For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the two's complement of the number is returned, with respect to that width. In a two's-complement system negative numbers are represented by the two's complement of the absolute value. This is the most common method of representing signed integers on computers [1]_. A N-bit two's-complement system can represent every integer in the range :math:`-2^{N-1}` to :math:`+2^{N-1}-1`. Parameters ---------- num : int Only an integer decimal number can be used. width : int, optional The length of the returned string if `num` is positive, or the length of the two's complement if `num` is negative, provided that `width` is at least a sufficient number of bits for `num` to be represented in the designated form. If the `width` value is insufficient, it will be ignored, and `num` will be returned in binary (`num` > 0) or two's complement (`num` < 0) form with its width equal to the minimum number of bits needed to represent the number in the designated form. This behavior is deprecated and will later raise an error. .. deprecated:: 1.12.0 Returns ------- bin : str Binary representation of `num` or two's complement of `num`. See Also -------- base_repr: Return a string representation of a number in the given base system. bin: Python's built-in binary representation generator of an integer. Notes ----- `binary_repr` is equivalent to using `base_repr` with base 2, but about 25x faster. References ---------- .. [1] Wikipedia, "Two's complement", https://en.wikipedia.org/wiki/Two's_complement Examples -------- >>> np.binary_repr(3) '11' >>> np.binary_repr(-3) '-11' >>> np.binary_repr(3, width=4) '0011' The two's complement is returned when the input number is negative and width is specified: >>> np.binary_repr(-3, width=3) '101' >>> np.binary_repr(-3, width=5) '11101' """ def warn_if_insufficient(width, binwidth): if width is not None and width < binwidth: warnings.warn( "Insufficient bit width provided. This behavior " "will raise an error in the future.", DeprecationWarning, stacklevel=3) # Ensure that num is a Python integer to avoid overflow or unwanted # casts to floating point. num = operator.index(num) if num == 0: return '0' * (width or 1) elif num > 0: binary = bin(num)[2:] binwidth = len(binary) outwidth = (binwidth if width is None else max(binwidth, width)) warn_if_insufficient(width, binwidth) return binary.zfill(outwidth) else: if width is None: return '-' + bin(-num)[2:] else: poswidth = len(bin(-num)[2:]) # See gh-8679: remove extra digit # for numbers at boundaries. if 2**(poswidth - 1) == -num: poswidth -= 1 twocomp = 2**(poswidth + 1) + num binary = bin(twocomp)[2:] binwidth = len(binary) outwidth = max(binwidth, width) warn_if_insufficient(width, binwidth) return '1' * (outwidth - binwidth) + binary @set_module('numpy') def base_repr(number, base=2, padding=0): """ Return a string representation of a number in the given base system. Parameters ---------- number : int The value to convert. Positive and negative values are handled. base : int, optional Convert `number` to the `base` number system. The valid range is 2-36, the default value is 2. padding : int, optional Number of zeros padded on the left. Default is 0 (no padding). Returns ------- out : str String representation of `number` in `base` system. See Also -------- binary_repr : Faster version of `base_repr` for base 2. Examples -------- >>> np.base_repr(5) '101' >>> np.base_repr(6, 5) '11' >>> np.base_repr(7, base=5, padding=3) '00012' >>> np.base_repr(10, base=16) 'A' >>> np.base_repr(32, base=16) '20' """ digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' if base > len(digits): raise ValueError("Bases greater than 36 not handled in base_repr.") elif base < 2: raise ValueError("Bases less than 2 not handled in base_repr.") num = abs(number) res = [] while num: res.append(digits[num % base]) num //= base if padding: res.append('0' * padding) if number < 0: res.append('-') return ''.join(reversed(res or '0')) # These are all essentially abbreviations # These might wind up in a special abbreviations module def _maketup(descr, val): dt = dtype(descr) # Place val in all scalar tuples: fields = dt.fields if fields is None: return val else: res = [_maketup(fields[name][0], val) for name in dt.names] return tuple(res) @set_module('numpy') def identity(n, dtype=None): """ Return the identity array. The identity array is a square array with ones on the main diagonal. Parameters ---------- n : int Number of rows (and columns) in `n` x `n` output. dtype : data-type, optional Data-type of the output. Defaults to ``float``. Returns ------- out : ndarray `n` x `n` array with its main diagonal set to one, and all other elements 0. Examples -------- >>> np.identity(3) array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) """ from numpy import eye return eye(n, dtype=dtype) def _allclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None): return (a, b) @array_function_dispatch(_allclose_dispatcher) def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): """ Returns True if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (`rtol` * abs(`b`)) and the absolute difference `atol` are added together to compare against the absolute difference between `a` and `b`. If either array contains one or more NaNs, False is returned. Infs are treated as equal if they are in the same place and of the same sign in both arrays. Parameters ---------- a, b : array_like Input arrays to compare. rtol : float The relative tolerance parameter (see Notes). atol : float The absolute tolerance parameter (see Notes). equal_nan : bool Whether to compare NaN's as equal. If True, NaN's in `a` will be considered equal to NaN's in `b`. .. versionadded:: 1.10.0 Returns ------- allclose : bool Returns True if the two arrays are equal within the given tolerance; False otherwise. See Also -------- isclose, all, any, equal Notes ----- If the following equation is element-wise True, then allclose returns True. absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) The above equation is not symmetric in `a` and `b`, so that ``allclose(a, b)`` might be different from ``allclose(b, a)`` in some rare cases. The comparison of `a` and `b` uses standard broadcasting, which means that `a` and `b` need not have the same shape in order for ``allclose(a, b)`` to evaluate to True. The same is true for `equal` but not `array_equal`. Examples -------- >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8]) False >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9]) True >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9]) False >>> np.allclose([1.0, np.nan], [1.0, np.nan]) False >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) True """ res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)) return bool(res) def _isclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None): return (a, b) @array_function_dispatch(_isclose_dispatcher) def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): """ Returns a boolean array where two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (`rtol` * abs(`b`)) and the absolute difference `atol` are added together to compare against the absolute difference between `a` and `b`. .. warning:: The default `atol` is not appropriate for comparing numbers that are much smaller than one (see Notes). Parameters ---------- a, b : array_like Input arrays to compare. rtol : float The relative tolerance parameter (see Notes). atol : float The absolute tolerance parameter (see Notes). equal_nan : bool Whether to compare NaN's as equal. If True, NaN's in `a` will be considered equal to NaN's in `b` in the output array. Returns ------- y : array_like Returns a boolean array of where `a` and `b` are equal within the given tolerance. If both `a` and `b` are scalars, returns a single boolean value. See Also -------- allclose Notes ----- .. versionadded:: 1.7.0 For finite values, isclose uses the following equation to test whether two floating point values are equivalent. absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) Unlike the built-in `math.isclose`, the above equation is not symmetric in `a` and `b` -- it assumes `b` is the reference value -- so that `isclose(a, b)` might be different from `isclose(b, a)`. Furthermore, the default value of atol is not zero, and is used to determine what small values should be considered close to zero. The default value is appropriate for expected values of order unity: if the expected values are significantly smaller than one, it can result in false positives. `atol` should be carefully selected for the use case at hand. A zero value for `atol` will result in `False` if either `a` or `b` is zero. Examples -------- >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8]) array([ True, False]) >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9]) array([ True, True]) >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9]) array([False, True]) >>> np.isclose([1.0, np.nan], [1.0, np.nan]) array([ True, False]) >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) array([ True, True]) >>> np.isclose([1e-8, 1e-7], [0.0, 0.0]) array([ True, False]) >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0) array([False, False]) >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0]) array([ True, True]) >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0) array([False, True]) """ def within_tol(x, y, atol, rtol): with errstate(invalid='ignore'): return less_equal(abs(x-y), atol + rtol * abs(y)) x = asanyarray(a) y = asanyarray(b) # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT). # This will cause casting of x later. Also, make sure to allow subclasses # (e.g., for numpy.ma). dt = multiarray.result_type(y, 1.) y = array(y, dtype=dt, copy=False, subok=True) xfin = isfinite(x) yfin = isfinite(y) if all(xfin) and all(yfin): return within_tol(x, y, atol, rtol) else: finite = xfin & yfin cond = zeros_like(finite, subok=True) # Because we're using boolean indexing, x & y must be the same shape. # Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in # lib.stride_tricks, though, so we can't import it here. x = x * ones_like(cond) y = y * ones_like(cond) # Avoid subtraction with infinite/nan values... cond[finite] = within_tol(x[finite], y[finite], atol, rtol) # Check for equality of infinite values... cond[~finite] = (x[~finite] == y[~finite]) if equal_nan: # Make NaN == NaN both_nan = isnan(x) & isnan(y) # Needed to treat masked arrays correctly. = True would not work. cond[both_nan] = both_nan[both_nan] return cond[()] # Flatten 0d arrays to scalars def _array_equal_dispatcher(a1, a2): return (a1, a2) @array_function_dispatch(_array_equal_dispatcher) def array_equal(a1, a2): """ True if two arrays have the same shape and elements, False otherwise. Parameters ---------- a1, a2 : array_like Input arrays. Returns ------- b : bool Returns True if the arrays are equal. See Also -------- allclose: Returns True if two arrays are element-wise equal within a tolerance. array_equiv: Returns True if input arrays are shape consistent and all elements equal. Examples -------- >>> np.array_equal([1, 2], [1, 2]) True >>> np.array_equal(np.array([1, 2]), np.array([1, 2])) True >>> np.array_equal([1, 2], [1, 2, 3]) False >>> np.array_equal([1, 2], [1, 4]) False """ try: a1, a2 = asarray(a1), asarray(a2) except Exception: return False if a1.shape != a2.shape: return False return bool(asarray(a1 == a2).all()) def _array_equiv_dispatcher(a1, a2): return (a1, a2) @array_function_dispatch(_array_equiv_dispatcher) def array_equiv(a1, a2): """ Returns True if input arrays are shape consistent and all elements equal. Shape consistent means they are either the same shape, or one input array can be broadcasted to create the same shape as the other one. Parameters ---------- a1, a2 : array_like Input arrays. Returns ------- out : bool True if equivalent, False otherwise. Examples -------- >>> np.array_equiv([1, 2], [1, 2]) True >>> np.array_equiv([1, 2], [1, 3]) False Showing the shape equivalence: >>> np.array_equiv([1, 2], [[1, 2], [1, 2]]) True >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]]) False >>> np.array_equiv([1, 2], [[1, 2], [1, 3]]) False """ try: a1, a2 = asarray(a1), asarray(a2) except Exception: return False try: multiarray.broadcast(a1, a2) except Exception: return False return bool(asarray(a1 == a2).all()) Inf = inf = infty = Infinity = PINF nan = NaN = NAN False_ = bool_(False) True_ = bool_(True) def extend_all(module): existing = set(__all__) mall = getattr(module, '__all__') for a in mall: if a not in existing: __all__.append(a) from .umath import * from .numerictypes import * from . import fromnumeric from .fromnumeric import * from . import arrayprint from .arrayprint import * from . import _asarray from ._asarray import * from . import _ufunc_config from ._ufunc_config import * extend_all(fromnumeric) extend_all(umath) extend_all(numerictypes) extend_all(arrayprint) extend_all(_asarray) extend_all(_ufunc_config)
from __future__ import division, absolute_import, print_function import sys import warnings import itertools import operator import platform import pytest import numpy as np from numpy.testing import ( assert_, assert_equal, assert_raises, assert_almost_equal, assert_array_equal, IS_PYPY, suppress_warnings, _gen_alignment_data, assert_warns ) types = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc, np.int_, np.uint, np.longlong, np.ulonglong, np.single, np.double, np.longdouble, np.csingle, np.cdouble, np.clongdouble] floating_types = np.floating.__subclasses__() complex_floating_types = np.complexfloating.__subclasses__() # This compares scalarmath against ufuncs. class TestTypes(object): def test_types(self): for atype in types: a = atype(1) assert_(a == 1, "error with %r: got %r" % (atype, a)) def test_type_add(self): # list of types for k, atype in enumerate(types): a_scalar = atype(3) a_array = np.array([3], dtype=atype) for l, btype in enumerate(types): b_scalar = btype(1) b_array = np.array([1], dtype=btype) c_scalar = a_scalar + b_scalar c_array = a_array + b_array # It was comparing the type numbers, but the new ufunc # function-finding mechanism finds the lowest function # to which both inputs can be cast - which produces 'l' # when you do 'q' + 'b'. The old function finding mechanism # skipped ahead based on the first argument, but that # does not produce properly symmetric results... assert_equal(c_scalar.dtype, c_array.dtype, "error with types (%d/'%c' + %d/'%c')" % (k, np.dtype(atype).char, l, np.dtype(btype).char)) def test_type_create(self): for k, atype in enumerate(types): a = np.array([1, 2, 3], atype) b = atype([1, 2, 3]) assert_equal(a, b) def test_leak(self): # test leak of scalar objects # a leak would show up in valgrind as still-reachable of ~2.6MB for i in range(200000): np.add(1, 1) class TestBaseMath(object): def test_blocked(self): # test alignments offsets for simd instructions # alignments for vz + 2 * (vs - 1) + 1 for dt, sz in [(np.float32, 11), (np.float64, 7), (np.int32, 11)]: for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt, type='binary', max_size=sz): exp1 = np.ones_like(inp1) inp1[...] = np.ones_like(inp1) inp2[...] = np.zeros_like(inp2) assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg) assert_almost_equal(np.add(inp1, 2), exp1 + 2, err_msg=msg) assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg) np.add(inp1, inp2, out=out) assert_almost_equal(out, exp1, err_msg=msg) inp2[...] += np.arange(inp2.size, dtype=dt) + 1 assert_almost_equal(np.square(inp2), np.multiply(inp2, inp2), err_msg=msg) # skip true divide for ints if dt != np.int32 or (sys.version_info.major < 3 and not sys.py3kwarning): assert_almost_equal(np.reciprocal(inp2), np.divide(1, inp2), err_msg=msg) inp1[...] = np.ones_like(inp1) np.add(inp1, 2, out=out) assert_almost_equal(out, exp1 + 2, err_msg=msg) inp2[...] = np.ones_like(inp2) np.add(2, inp2, out=out) assert_almost_equal(out, exp1 + 2, err_msg=msg) def test_lower_align(self): # check data that is not aligned to element size # i.e doubles are aligned to 4 bytes on i386 d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) o = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) assert_almost_equal(d + d, d * 2) np.add(d, d, out=o) np.add(np.ones_like(d), d, out=o) np.add(d, np.ones_like(d), out=o) np.add(np.ones_like(d), d) np.add(d, np.ones_like(d)) class TestPower(object): def test_small_types(self): for t in [np.int8, np.int16, np.float16]: a = t(3) b = a ** 4 assert_(b == 81, "error with %r: got %r" % (t, b)) def test_large_types(self): for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]: a = t(51) b = a ** 4 msg = "error with %r: got %r" % (t, b) if np.issubdtype(t, np.integer): assert_(b == 6765201, msg) else: assert_almost_equal(b, 6765201, err_msg=msg) def test_integers_to_negative_integer_power(self): # Note that the combination of uint64 with a signed integer # has common type np.float64. The other combinations should all # raise a ValueError for integer ** negative integer. exp = [np.array(-1, dt)[()] for dt in 'bhilq'] # 1 ** -1 possible special case base = [np.array(1, dt)[()] for dt in 'bhilqBHILQ'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, 1.) # -1 ** -1 possible special case base = [np.array(-1, dt)[()] for dt in 'bhilq'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, -1.) # 2 ** -1 perhaps generic base = [np.array(2, dt)[()] for dt in 'bhilqBHILQ'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, .5) def test_mixed_types(self): typelist = [np.int8, np.int16, np.float16, np.float32, np.float64, np.int8, np.int16, np.int32, np.int64] for t1 in typelist: for t2 in typelist: a = t1(3) b = t2(2) result = a**b msg = ("error with %r and %r:" "got %r, expected %r") % (t1, t2, result, 9) if np.issubdtype(np.dtype(result), np.integer): assert_(result == 9, msg) else: assert_almost_equal(result, 9, err_msg=msg) def test_modular_power(self): # modular power is not implemented, so ensure it errors a = 5 b = 4 c = 10 expected = pow(a, b, c) # noqa: F841 for t in (np.int32, np.float32, np.complex64): # note that 3-operand power only dispatches on the first argument assert_raises(TypeError, operator.pow, t(a), b, c) assert_raises(TypeError, operator.pow, np.array(t(a)), b, c) def floordiv_and_mod(x, y): return (x // y, x % y) def _signs(dt): if dt in np.typecodes['UnsignedInteger']: return (+1,) else: return (+1, -1) class TestModulus(object): def test_modulus_basic(self): dt = np.typecodes['AllInteger'] + np.typecodes['Float'] for op in [floordiv_and_mod, divmod]: for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product(_signs(dt1), _signs(dt2)): fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (op.__name__, dt1, dt2, sg1, sg2) a = np.array(sg1*71, dtype=dt1)[()] b = np.array(sg2*19, dtype=dt2)[()] div, rem = op(a, b) assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg) def test_float_modulus_exact(self): # test that float results are exact for small integers. This also # holds for the same integers scaled by powers of two. nlst = list(range(-127, 0)) plst = list(range(1, 128)) dividend = nlst + [0] + plst divisor = nlst + plst arg = list(itertools.product(dividend, divisor)) tgt = list(divmod(*t) for t in arg) a, b = np.array(arg, dtype=int).T # convert exact integer results from Python to float so that # signed zero can be used, it is checked. tgtdiv, tgtrem = np.array(tgt, dtype=float).T tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv) tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem) for op in [floordiv_and_mod, divmod]: for dt in np.typecodes['Float']: msg = 'op: %s, dtype: %s' % (op.__name__, dt) fa = a.astype(dt) fb = b.astype(dt) # use list comprehension so a_ and b_ are scalars div, rem = zip(*[op(a_, b_) for a_, b_ in zip(fa, fb)]) assert_equal(div, tgtdiv, err_msg=msg) assert_equal(rem, tgtrem, err_msg=msg) def test_float_modulus_roundoff(self): # gh-6127 dt = np.typecodes['Float'] for op in [floordiv_and_mod, divmod]: for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product((+1, -1), (+1, -1)): fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (op.__name__, dt1, dt2, sg1, sg2) a = np.array(sg1*78*6e-8, dtype=dt1)[()] b = np.array(sg2*6e-8, dtype=dt2)[()] div, rem = op(a, b) # Equal assertion should hold when fmod is used assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg) def test_float_modulus_corner_cases(self): # Check remainder magnitude. for dt in np.typecodes['Float']: b = np.array(1.0, dtype=dt) a = np.nextafter(np.array(0.0, dtype=dt), -b) rem = operator.mod(a, b) assert_(rem <= b, 'dt: %s' % dt) rem = operator.mod(-a, -b) assert_(rem >= -b, 'dt: %s' % dt) # Check nans, inf with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in remainder") for dt in np.typecodes['Float']: fone = np.array(1.0, dtype=dt) fzer = np.array(0.0, dtype=dt) finf = np.array(np.inf, dtype=dt) fnan = np.array(np.nan, dtype=dt) rem = operator.mod(fone, fzer) assert_(np.isnan(rem), 'dt: %s' % dt) # MSVC 2008 returns NaN here, so disable the check. #rem = operator.mod(fone, finf) #assert_(rem == fone, 'dt: %s' % dt) rem = operator.mod(fone, fnan) assert_(np.isnan(rem), 'dt: %s' % dt) rem = operator.mod(finf, fone) assert_(np.isnan(rem), 'dt: %s' % dt) class TestComplexDivision(object): def test_zero_division(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: a = t(0.0) b = t(1.0) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.nan)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.nan)) assert_(np.isnan(b/a)) b = t(0.) assert_(np.isnan(b/a)) def test_signed_zeros(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = ( (( 0.0,-1.0), ( 0.0, 1.0), (-1.0,-0.0)), (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), (( 0.0,-1.0), (-0.0,-1.0), ( 1.0, 0.0)), (( 0.0,-1.0), (-0.0, 1.0), (-1.0, 0.0)), (( 0.0, 1.0), ( 0.0,-1.0), (-1.0, 0.0)), (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), ((-0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), ((-0.0, 1.0), ( 0.0,-1.0), (-1.0,-0.0)) ) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1]) def test_branches(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = list() # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by else condition as neither are == 0 data.append((( 2.0, 1.0), ( 2.0, 1.0), (1.0, 0.0))) # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by if condition as both are == 0 # is performed in test_zero_division(), so this is skipped # trigger else if branch: real(fabs(denom)) < imag(fabs(denom)) data.append((( 1.0, 2.0), ( 1.0, 2.0), (1.0, 0.0))) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1]) class TestConversion(object): def test_int_from_long(self): l = [1e6, 1e12, 1e18, -1e6, -1e12, -1e18] li = [10**6, 10**12, 10**18, -10**6, -10**12, -10**18] for T in [None, np.float64, np.int64]: a = np.array(l, dtype=T) assert_equal([int(_m) for _m in a], li) a = np.array(l[:3], dtype=np.uint64) assert_equal([int(_m) for _m in a], li[:3]) def test_iinfo_long_values(self): for code in 'bBhH': res = np.array(np.iinfo(code).max + 1, dtype=code) tgt = np.iinfo(code).min assert_(res == tgt) for code in np.typecodes['AllInteger']: res = np.array(np.iinfo(code).max, dtype=code) tgt = np.iinfo(code).max assert_(res == tgt) for code in np.typecodes['AllInteger']: res = np.typeDict[code](np.iinfo(code).max) tgt = np.iinfo(code).max assert_(res == tgt) def test_int_raise_behaviour(self): def overflow_error_func(dtype): np.typeDict[dtype](np.iinfo(dtype).max + 1) for code in 'lLqQ': assert_raises(OverflowError, overflow_error_func, code) def test_int_from_infinite_longdouble(self): # gh-627 x = np.longdouble(np.inf) assert_raises(OverflowError, int, x) with suppress_warnings() as sup: sup.record(np.ComplexWarning) x = np.clongdouble(np.inf) assert_raises(OverflowError, int, x) assert_equal(len(sup.log), 1) @pytest.mark.skipif(not IS_PYPY, reason="Test is PyPy only (gh-9972)") def test_int_from_infinite_longdouble___int__(self): x = np.longdouble(np.inf) assert_raises(OverflowError, x.__int__) with suppress_warnings() as sup: sup.record(np.ComplexWarning) x = np.clongdouble(np.inf) assert_raises(OverflowError, x.__int__) assert_equal(len(sup.log), 1) @pytest.mark.skipif(np.finfo(np.double) == np.finfo(np.longdouble), reason="long double is same as double") @pytest.mark.skipif(platform.machine().startswith("ppc"), reason="IBM double double") def test_int_from_huge_longdouble(self): # Produce a longdouble that would overflow a double, # use exponent that avoids bug in Darwin pow function. exp = np.finfo(np.double).maxexp - 1 huge_ld = 2 * 1234 * np.longdouble(2) ** exp huge_i = 2 * 1234 * 2 ** exp assert_(huge_ld != np.inf) assert_equal(int(huge_ld), huge_i) def test_int_from_longdouble(self): x = np.longdouble(1.5) assert_equal(int(x), 1) x = np.longdouble(-10.5) assert_equal(int(x), -10) def test_numpy_scalar_relational_operators(self): # All integer for dt1 in np.typecodes['AllInteger']: assert_(1 > np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not 1 < np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,)) for dt2 in np.typecodes['AllInteger']: assert_(np.array(1, dtype=dt1)[()] > np.array(0, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(0, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) #Unsigned integers for dt1 in 'BHILQP': assert_(-1 < np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not -1 > np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(-1 != np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) #unsigned vs signed for dt2 in 'bhilqp': assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(np.array(1, dtype=dt1)[()] != np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) #Signed integers and floats for dt1 in 'bhlqp' + np.typecodes['Float']: assert_(1 > np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not 1 < np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(-1 == np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) for dt2 in 'bhlqp' + np.typecodes['Float']: assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(np.array(-1, dtype=dt1)[()] == np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) def test_scalar_comparison_to_none(self): # Scalars should just return False and not give a warnings. # The comparisons are flagged by pep8, ignore that. with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', FutureWarning) assert_(not np.float32(1) == None) assert_(not np.str_('test') == None) # This is dubious (see below): assert_(not np.datetime64('NaT') == None) assert_(np.float32(1) != None) assert_(np.str_('test') != None) # This is dubious (see below): assert_(np.datetime64('NaT') != None) assert_(len(w) == 0) # For documentation purposes, this is why the datetime is dubious. # At the time of deprecation this was no behaviour change, but # it has to be considered when the deprecations are done. assert_(np.equal(np.datetime64('NaT'), None)) #class TestRepr(object): # def test_repr(self): # for t in types: # val = t(1197346475.0137341) # val_repr = repr(val) # val2 = eval(val_repr) # assert_equal( val, val2 ) class TestRepr(object): def _test_type_repr(self, t): finfo = np.finfo(t) last_fraction_bit_idx = finfo.nexp + finfo.nmant last_exponent_bit_idx = finfo.nexp storage_bytes = np.dtype(t).itemsize*8 # could add some more types to the list below for which in ['small denorm', 'small norm']: # Values from https://en.wikipedia.org/wiki/IEEE_754 constr = np.array([0x00]*storage_bytes, dtype=np.uint8) if which == 'small denorm': byte = last_fraction_bit_idx // 8 bytebit = 7-(last_fraction_bit_idx % 8) constr[byte] = 1 << bytebit elif which == 'small norm': byte = last_exponent_bit_idx // 8 bytebit = 7-(last_exponent_bit_idx % 8) constr[byte] = 1 << bytebit else: raise ValueError('hmm') val = constr.view(t)[0] val_repr = repr(val) val2 = t(eval(val_repr)) if not (val2 == 0 and val < 1e-100): assert_equal(val, val2) def test_float_repr(self): # long double test cannot work, because eval goes through a python # float for t in [np.float32, np.float64]: self._test_type_repr(t) if not IS_PYPY: # sys.getsizeof() is not valid on PyPy class TestSizeOf(object): def test_equal_nbytes(self): for type in types: x = type(0) assert_(sys.getsizeof(x) > x.nbytes) def test_error(self): d = np.float32() assert_raises(TypeError, d.__sizeof__, "a") class TestMultiply(object): def test_seq_repeat(self): # Test that basic sequences get repeated when multiplied with # numpy integers. And errors are raised when multiplied with others. # Some of this behaviour may be controversial and could be open for # change. accepted_types = set(np.typecodes["AllInteger"]) deprecated_types = {'?'} forbidden_types = ( set(np.typecodes["All"]) - accepted_types - deprecated_types) forbidden_types -= {'V'} # can't default-construct void scalars for seq_type in (list, tuple): seq = seq_type([1, 2, 3]) for numpy_type in accepted_types: i = np.dtype(numpy_type).type(2) assert_equal(seq * i, seq * int(i)) assert_equal(i * seq, int(i) * seq) for numpy_type in deprecated_types: i = np.dtype(numpy_type).type() assert_equal( assert_warns(DeprecationWarning, operator.mul, seq, i), seq * int(i)) assert_equal( assert_warns(DeprecationWarning, operator.mul, i, seq), int(i) * seq) for numpy_type in forbidden_types: i = np.dtype(numpy_type).type() assert_raises(TypeError, operator.mul, seq, i) assert_raises(TypeError, operator.mul, i, seq) def test_no_seq_repeat_basic_array_like(self): # Test that an array-like which does not know how to be multiplied # does not attempt sequence repeat (raise TypeError). # See also gh-7428. class ArrayLike(object): def __init__(self, arr): self.arr = arr def __array__(self): return self.arr # Test for simple ArrayLike above and memoryviews (original report) for arr_like in (ArrayLike(np.ones(3)), memoryview(np.ones(3))): assert_array_equal(arr_like * np.float32(3.), np.full(3, 3.)) assert_array_equal(np.float32(3.) * arr_like, np.full(3, 3.)) assert_array_equal(arr_like * np.int_(3), np.full(3, 3)) assert_array_equal(np.int_(3) * arr_like, np.full(3, 3)) class TestNegative(object): def test_exceptions(self): a = np.ones((), dtype=np.bool_)[()] assert_raises(TypeError, operator.neg, a) def test_result(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] with suppress_warnings() as sup: sup.filter(RuntimeWarning) for dt in types: a = np.ones((), dtype=dt)[()] assert_equal(operator.neg(a) + a, 0) class TestSubtract(object): def test_exceptions(self): a = np.ones((), dtype=np.bool_)[()] assert_raises(TypeError, operator.sub, a, a) def test_result(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] with suppress_warnings() as sup: sup.filter(RuntimeWarning) for dt in types: a = np.ones((), dtype=dt)[()] assert_equal(operator.sub(a, a), 0) class TestAbs(object): def _test_abs_func(self, absfunc): for tp in floating_types + complex_floating_types: x = tp(-1.5) assert_equal(absfunc(x), 1.5) x = tp(0.0) res = absfunc(x) # assert_equal() checks zero signedness assert_equal(res, 0.0) x = tp(-0.0) res = absfunc(x) assert_equal(res, 0.0) x = tp(np.finfo(tp).max) assert_equal(absfunc(x), x.real) x = tp(np.finfo(tp).tiny) assert_equal(absfunc(x), x.real) x = tp(np.finfo(tp).min) assert_equal(absfunc(x), -x.real) def test_builtin_abs(self): self._test_abs_func(abs) def test_numpy_abs(self): self._test_abs_func(np.abs) class TestBitShifts(object): @pytest.mark.parametrize('type_code', np.typecodes['AllInteger']) @pytest.mark.parametrize('op', [operator.rshift, operator.lshift], ids=['>>', '<<']) def test_shift_all_bits(self, type_code, op): """ Shifts where the shift amount is the width of the type or wider """ # gh-2449 dt = np.dtype(type_code) nbits = dt.itemsize * 8 for val in [5, -5]: for shift in [nbits, nbits + 4]: val_scl = dt.type(val) shift_scl = dt.type(shift) res_scl = op(val_scl, shift_scl) if val_scl < 0 and op is operator.rshift: # sign bit is preserved assert_equal(res_scl, -1) else: assert_equal(res_scl, 0) # Result on scalars should be the same as on arrays val_arr = np.array([val]*32, dtype=dt) shift_arr = np.array([shift]*32, dtype=dt) res_arr = op(val_arr, shift_arr) assert_equal(res_arr, res_scl)
MSeifert04/numpy
numpy/core/tests/test_scalarmath.py
numpy/core/numeric.py
from __future__ import division, absolute_import, print_function import numpy as np from numpy.core._rational_tests import rational from numpy.testing import ( assert_equal, assert_array_equal, assert_raises, assert_, assert_raises_regex, assert_warns, ) from numpy.lib.stride_tricks import ( as_strided, broadcast_arrays, _broadcast_shape, broadcast_to ) def assert_shapes_correct(input_shapes, expected_shape): # Broadcast a list of arrays with the given input shapes and check the # common output shape. inarrays = [np.zeros(s) for s in input_shapes] outarrays = broadcast_arrays(*inarrays) outshapes = [a.shape for a in outarrays] expected = [expected_shape] * len(inarrays) assert_equal(outshapes, expected) def assert_incompatible_shapes_raise(input_shapes): # Broadcast a list of arrays with the given (incompatible) input shapes # and check that they raise a ValueError. inarrays = [np.zeros(s) for s in input_shapes] assert_raises(ValueError, broadcast_arrays, *inarrays) def assert_same_as_ufunc(shape0, shape1, transposed=False, flipped=False): # Broadcast two shapes against each other and check that the data layout # is the same as if a ufunc did the broadcasting. x0 = np.zeros(shape0, dtype=int) # Note that multiply.reduce's identity element is 1.0, so when shape1==(), # this gives the desired n==1. n = int(np.multiply.reduce(shape1)) x1 = np.arange(n).reshape(shape1) if transposed: x0 = x0.T x1 = x1.T if flipped: x0 = x0[::-1] x1 = x1[::-1] # Use the add ufunc to do the broadcasting. Since we're adding 0s to x1, the # result should be exactly the same as the broadcasted view of x1. y = x0 + x1 b0, b1 = broadcast_arrays(x0, x1) assert_array_equal(y, b1) def test_same(): x = np.arange(10) y = np.arange(10) bx, by = broadcast_arrays(x, y) assert_array_equal(x, bx) assert_array_equal(y, by) def test_broadcast_kwargs(): # ensure that a TypeError is appropriately raised when # np.broadcast_arrays() is called with any keyword # argument other than 'subok' x = np.arange(10) y = np.arange(10) with assert_raises_regex(TypeError, r'broadcast_arrays\(\) got an unexpected keyword*'): broadcast_arrays(x, y, dtype='float64') def test_one_off(): x = np.array([[1, 2, 3]]) y = np.array([[1], [2], [3]]) bx, by = broadcast_arrays(x, y) bx0 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) by0 = bx0.T assert_array_equal(bx0, bx) assert_array_equal(by0, by) def test_same_input_shapes(): # Check that the final shape is just the input shape. data = [ (), (1,), (3,), (0, 1), (0, 3), (1, 0), (3, 0), (1, 3), (3, 1), (3, 3), ] for shape in data: input_shapes = [shape] # Single input. assert_shapes_correct(input_shapes, shape) # Double input. input_shapes2 = [shape, shape] assert_shapes_correct(input_shapes2, shape) # Triple input. input_shapes3 = [shape, shape, shape] assert_shapes_correct(input_shapes3, shape) def test_two_compatible_by_ones_input_shapes(): # Check that two different input shapes of the same length, but some have # ones, broadcast to the correct shape. data = [ [[(1,), (3,)], (3,)], [[(1, 3), (3, 3)], (3, 3)], [[(3, 1), (3, 3)], (3, 3)], [[(1, 3), (3, 1)], (3, 3)], [[(1, 1), (3, 3)], (3, 3)], [[(1, 1), (1, 3)], (1, 3)], [[(1, 1), (3, 1)], (3, 1)], [[(1, 0), (0, 0)], (0, 0)], [[(0, 1), (0, 0)], (0, 0)], [[(1, 0), (0, 1)], (0, 0)], [[(1, 1), (0, 0)], (0, 0)], [[(1, 1), (1, 0)], (1, 0)], [[(1, 1), (0, 1)], (0, 1)], ] for input_shapes, expected_shape in data: assert_shapes_correct(input_shapes, expected_shape) # Reverse the input shapes since broadcasting should be symmetric. assert_shapes_correct(input_shapes[::-1], expected_shape) def test_two_compatible_by_prepending_ones_input_shapes(): # Check that two different input shapes (of different lengths) broadcast # to the correct shape. data = [ [[(), (3,)], (3,)], [[(3,), (3, 3)], (3, 3)], [[(3,), (3, 1)], (3, 3)], [[(1,), (3, 3)], (3, 3)], [[(), (3, 3)], (3, 3)], [[(1, 1), (3,)], (1, 3)], [[(1,), (3, 1)], (3, 1)], [[(1,), (1, 3)], (1, 3)], [[(), (1, 3)], (1, 3)], [[(), (3, 1)], (3, 1)], [[(), (0,)], (0,)], [[(0,), (0, 0)], (0, 0)], [[(0,), (0, 1)], (0, 0)], [[(1,), (0, 0)], (0, 0)], [[(), (0, 0)], (0, 0)], [[(1, 1), (0,)], (1, 0)], [[(1,), (0, 1)], (0, 1)], [[(1,), (1, 0)], (1, 0)], [[(), (1, 0)], (1, 0)], [[(), (0, 1)], (0, 1)], ] for input_shapes, expected_shape in data: assert_shapes_correct(input_shapes, expected_shape) # Reverse the input shapes since broadcasting should be symmetric. assert_shapes_correct(input_shapes[::-1], expected_shape) def test_incompatible_shapes_raise_valueerror(): # Check that a ValueError is raised for incompatible shapes. data = [ [(3,), (4,)], [(2, 3), (2,)], [(3,), (3,), (4,)], [(1, 3, 4), (2, 3, 3)], ] for input_shapes in data: assert_incompatible_shapes_raise(input_shapes) # Reverse the input shapes since broadcasting should be symmetric. assert_incompatible_shapes_raise(input_shapes[::-1]) def test_same_as_ufunc(): # Check that the data layout is the same as if a ufunc did the operation. data = [ [[(1,), (3,)], (3,)], [[(1, 3), (3, 3)], (3, 3)], [[(3, 1), (3, 3)], (3, 3)], [[(1, 3), (3, 1)], (3, 3)], [[(1, 1), (3, 3)], (3, 3)], [[(1, 1), (1, 3)], (1, 3)], [[(1, 1), (3, 1)], (3, 1)], [[(1, 0), (0, 0)], (0, 0)], [[(0, 1), (0, 0)], (0, 0)], [[(1, 0), (0, 1)], (0, 0)], [[(1, 1), (0, 0)], (0, 0)], [[(1, 1), (1, 0)], (1, 0)], [[(1, 1), (0, 1)], (0, 1)], [[(), (3,)], (3,)], [[(3,), (3, 3)], (3, 3)], [[(3,), (3, 1)], (3, 3)], [[(1,), (3, 3)], (3, 3)], [[(), (3, 3)], (3, 3)], [[(1, 1), (3,)], (1, 3)], [[(1,), (3, 1)], (3, 1)], [[(1,), (1, 3)], (1, 3)], [[(), (1, 3)], (1, 3)], [[(), (3, 1)], (3, 1)], [[(), (0,)], (0,)], [[(0,), (0, 0)], (0, 0)], [[(0,), (0, 1)], (0, 0)], [[(1,), (0, 0)], (0, 0)], [[(), (0, 0)], (0, 0)], [[(1, 1), (0,)], (1, 0)], [[(1,), (0, 1)], (0, 1)], [[(1,), (1, 0)], (1, 0)], [[(), (1, 0)], (1, 0)], [[(), (0, 1)], (0, 1)], ] for input_shapes, expected_shape in data: assert_same_as_ufunc(input_shapes[0], input_shapes[1], "Shapes: %s %s" % (input_shapes[0], input_shapes[1])) # Reverse the input shapes since broadcasting should be symmetric. assert_same_as_ufunc(input_shapes[1], input_shapes[0]) # Try them transposed, too. assert_same_as_ufunc(input_shapes[0], input_shapes[1], True) # ... and flipped for non-rank-0 inputs in order to test negative # strides. if () not in input_shapes: assert_same_as_ufunc(input_shapes[0], input_shapes[1], False, True) assert_same_as_ufunc(input_shapes[0], input_shapes[1], True, True) def test_broadcast_to_succeeds(): data = [ [np.array(0), (0,), np.array(0)], [np.array(0), (1,), np.zeros(1)], [np.array(0), (3,), np.zeros(3)], [np.ones(1), (1,), np.ones(1)], [np.ones(1), (2,), np.ones(2)], [np.ones(1), (1, 2, 3), np.ones((1, 2, 3))], [np.arange(3), (3,), np.arange(3)], [np.arange(3), (1, 3), np.arange(3).reshape(1, -1)], [np.arange(3), (2, 3), np.array([[0, 1, 2], [0, 1, 2]])], # test if shape is not a tuple [np.ones(0), 0, np.ones(0)], [np.ones(1), 1, np.ones(1)], [np.ones(1), 2, np.ones(2)], # these cases with size 0 are strange, but they reproduce the behavior # of broadcasting with ufuncs (see test_same_as_ufunc above) [np.ones(1), (0,), np.ones(0)], [np.ones((1, 2)), (0, 2), np.ones((0, 2))], [np.ones((2, 1)), (2, 0), np.ones((2, 0))], ] for input_array, shape, expected in data: actual = broadcast_to(input_array, shape) assert_array_equal(expected, actual) def test_broadcast_to_raises(): data = [ [(0,), ()], [(1,), ()], [(3,), ()], [(3,), (1,)], [(3,), (2,)], [(3,), (4,)], [(1, 2), (2, 1)], [(1, 1), (1,)], [(1,), -1], [(1,), (-1,)], [(1, 2), (-1, 2)], ] for orig_shape, target_shape in data: arr = np.zeros(orig_shape) assert_raises(ValueError, lambda: broadcast_to(arr, target_shape)) def test_broadcast_shape(): # broadcast_shape is already exercized indirectly by broadcast_arrays assert_equal(_broadcast_shape(), ()) assert_equal(_broadcast_shape([1, 2]), (2,)) assert_equal(_broadcast_shape(np.ones((1, 1))), (1, 1)) assert_equal(_broadcast_shape(np.ones((1, 1)), np.ones((3, 4))), (3, 4)) assert_equal(_broadcast_shape(*([np.ones((1, 2))] * 32)), (1, 2)) assert_equal(_broadcast_shape(*([np.ones((1, 2))] * 100)), (1, 2)) # regression tests for gh-5862 assert_equal(_broadcast_shape(*([np.ones(2)] * 32 + [1])), (2,)) bad_args = [np.ones(2)] * 32 + [np.ones(3)] * 32 assert_raises(ValueError, lambda: _broadcast_shape(*bad_args)) def test_as_strided(): a = np.array([None]) a_view = as_strided(a) expected = np.array([None]) assert_array_equal(a_view, np.array([None])) a = np.array([1, 2, 3, 4]) a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,)) expected = np.array([1, 3]) assert_array_equal(a_view, expected) a = np.array([1, 2, 3, 4]) a_view = as_strided(a, shape=(3, 4), strides=(0, 1 * a.itemsize)) expected = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) assert_array_equal(a_view, expected) # Regression test for gh-5081 dt = np.dtype([('num', 'i4'), ('obj', 'O')]) a = np.empty((4,), dtype=dt) a['num'] = np.arange(1, 5) a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize)) expected_num = [[1, 2, 3, 4]] * 3 expected_obj = [[None]*4]*3 assert_equal(a_view.dtype, dt) assert_array_equal(expected_num, a_view['num']) assert_array_equal(expected_obj, a_view['obj']) # Make sure that void types without fields are kept unchanged a = np.empty((4,), dtype='V4') a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize)) assert_equal(a.dtype, a_view.dtype) # Make sure that the only type that could fail is properly handled dt = np.dtype({'names': [''], 'formats': ['V4']}) a = np.empty((4,), dtype=dt) a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize)) assert_equal(a.dtype, a_view.dtype) # Custom dtypes should not be lost (gh-9161) r = [rational(i) for i in range(4)] a = np.array(r, dtype=rational) a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize)) assert_equal(a.dtype, a_view.dtype) assert_array_equal([r] * 3, a_view) def as_strided_writeable(): arr = np.ones(10) view = as_strided(arr, writeable=False) assert_(not view.flags.writeable) # Check that writeable also is fine: view = as_strided(arr, writeable=True) assert_(view.flags.writeable) view[...] = 3 assert_array_equal(arr, np.full_like(arr, 3)) # Test that things do not break down for readonly: arr.flags.writeable = False view = as_strided(arr, writeable=False) view = as_strided(arr, writeable=True) assert_(not view.flags.writeable) class VerySimpleSubClass(np.ndarray): def __new__(cls, *args, **kwargs): kwargs['subok'] = True return np.array(*args, **kwargs).view(cls) class SimpleSubClass(VerySimpleSubClass): def __new__(cls, *args, **kwargs): kwargs['subok'] = True self = np.array(*args, **kwargs).view(cls) self.info = 'simple' return self def __array_finalize__(self, obj): self.info = getattr(obj, 'info', '') + ' finalized' def test_subclasses(): # test that subclass is preserved only if subok=True a = VerySimpleSubClass([1, 2, 3, 4]) assert_(type(a) is VerySimpleSubClass) a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,)) assert_(type(a_view) is np.ndarray) a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,), subok=True) assert_(type(a_view) is VerySimpleSubClass) # test that if a subclass has __array_finalize__, it is used a = SimpleSubClass([1, 2, 3, 4]) a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,), subok=True) assert_(type(a_view) is SimpleSubClass) assert_(a_view.info == 'simple finalized') # similar tests for broadcast_arrays b = np.arange(len(a)).reshape(-1, 1) a_view, b_view = broadcast_arrays(a, b) assert_(type(a_view) is np.ndarray) assert_(type(b_view) is np.ndarray) assert_(a_view.shape == b_view.shape) a_view, b_view = broadcast_arrays(a, b, subok=True) assert_(type(a_view) is SimpleSubClass) assert_(a_view.info == 'simple finalized') assert_(type(b_view) is np.ndarray) assert_(a_view.shape == b_view.shape) # and for broadcast_to shape = (2, 4) a_view = broadcast_to(a, shape) assert_(type(a_view) is np.ndarray) assert_(a_view.shape == shape) a_view = broadcast_to(a, shape, subok=True) assert_(type(a_view) is SimpleSubClass) assert_(a_view.info == 'simple finalized') assert_(a_view.shape == shape) def test_writeable(): # broadcast_to should return a readonly array original = np.array([1, 2, 3]) result = broadcast_to(original, (2, 3)) assert_equal(result.flags.writeable, False) assert_raises(ValueError, result.__setitem__, slice(None), 0) # but the result of broadcast_arrays needs to be writeable, to # preserve backwards compatibility for is_broadcast, results in [(False, broadcast_arrays(original,)), (True, broadcast_arrays(0, original))]: for result in results: # This will change to False in a future version if is_broadcast: with assert_warns(FutureWarning): assert_equal(result.flags.writeable, True) with assert_warns(DeprecationWarning): result[:] = 0 # Warning not emitted, writing to the array resets it assert_equal(result.flags.writeable, True) else: # No warning: assert_equal(result.flags.writeable, True) for results in [broadcast_arrays(original), broadcast_arrays(0, original)]: for result in results: # resets the warn_on_write DeprecationWarning result.flags.writeable = True # check: no warning emitted assert_equal(result.flags.writeable, True) result[:] = 0 # keep readonly input readonly original.flags.writeable = False _, result = broadcast_arrays(0, original) assert_equal(result.flags.writeable, False) # regression test for GH6491 shape = (2,) strides = [0] tricky_array = as_strided(np.array(0), shape, strides) other = np.zeros((1,)) first, second = broadcast_arrays(tricky_array, other) assert_(first.shape == second.shape) def test_writeable_memoryview(): # The result of broadcast_arrays exports as a non-writeable memoryview # because otherwise there is no good way to opt in to the new behaviour # (i.e. you would need to set writeable to False explicitly). # See gh-13929. original = np.array([1, 2, 3]) for is_broadcast, results in [(False, broadcast_arrays(original,)), (True, broadcast_arrays(0, original))]: for result in results: # This will change to False in a future version if is_broadcast: # memoryview(result, writable=True) will give warning but cannot # be tested using the python API. assert memoryview(result).readonly else: assert not memoryview(result).readonly def test_reference_types(): input_array = np.array('a', dtype=object) expected = np.array(['a'] * 3, dtype=object) actual = broadcast_to(input_array, (3,)) assert_array_equal(expected, actual) actual, _ = broadcast_arrays(input_array, np.ones(3)) assert_array_equal(expected, actual)
from __future__ import division, absolute_import, print_function import sys import warnings import itertools import operator import platform import pytest import numpy as np from numpy.testing import ( assert_, assert_equal, assert_raises, assert_almost_equal, assert_array_equal, IS_PYPY, suppress_warnings, _gen_alignment_data, assert_warns ) types = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc, np.int_, np.uint, np.longlong, np.ulonglong, np.single, np.double, np.longdouble, np.csingle, np.cdouble, np.clongdouble] floating_types = np.floating.__subclasses__() complex_floating_types = np.complexfloating.__subclasses__() # This compares scalarmath against ufuncs. class TestTypes(object): def test_types(self): for atype in types: a = atype(1) assert_(a == 1, "error with %r: got %r" % (atype, a)) def test_type_add(self): # list of types for k, atype in enumerate(types): a_scalar = atype(3) a_array = np.array([3], dtype=atype) for l, btype in enumerate(types): b_scalar = btype(1) b_array = np.array([1], dtype=btype) c_scalar = a_scalar + b_scalar c_array = a_array + b_array # It was comparing the type numbers, but the new ufunc # function-finding mechanism finds the lowest function # to which both inputs can be cast - which produces 'l' # when you do 'q' + 'b'. The old function finding mechanism # skipped ahead based on the first argument, but that # does not produce properly symmetric results... assert_equal(c_scalar.dtype, c_array.dtype, "error with types (%d/'%c' + %d/'%c')" % (k, np.dtype(atype).char, l, np.dtype(btype).char)) def test_type_create(self): for k, atype in enumerate(types): a = np.array([1, 2, 3], atype) b = atype([1, 2, 3]) assert_equal(a, b) def test_leak(self): # test leak of scalar objects # a leak would show up in valgrind as still-reachable of ~2.6MB for i in range(200000): np.add(1, 1) class TestBaseMath(object): def test_blocked(self): # test alignments offsets for simd instructions # alignments for vz + 2 * (vs - 1) + 1 for dt, sz in [(np.float32, 11), (np.float64, 7), (np.int32, 11)]: for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt, type='binary', max_size=sz): exp1 = np.ones_like(inp1) inp1[...] = np.ones_like(inp1) inp2[...] = np.zeros_like(inp2) assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg) assert_almost_equal(np.add(inp1, 2), exp1 + 2, err_msg=msg) assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg) np.add(inp1, inp2, out=out) assert_almost_equal(out, exp1, err_msg=msg) inp2[...] += np.arange(inp2.size, dtype=dt) + 1 assert_almost_equal(np.square(inp2), np.multiply(inp2, inp2), err_msg=msg) # skip true divide for ints if dt != np.int32 or (sys.version_info.major < 3 and not sys.py3kwarning): assert_almost_equal(np.reciprocal(inp2), np.divide(1, inp2), err_msg=msg) inp1[...] = np.ones_like(inp1) np.add(inp1, 2, out=out) assert_almost_equal(out, exp1 + 2, err_msg=msg) inp2[...] = np.ones_like(inp2) np.add(2, inp2, out=out) assert_almost_equal(out, exp1 + 2, err_msg=msg) def test_lower_align(self): # check data that is not aligned to element size # i.e doubles are aligned to 4 bytes on i386 d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) o = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) assert_almost_equal(d + d, d * 2) np.add(d, d, out=o) np.add(np.ones_like(d), d, out=o) np.add(d, np.ones_like(d), out=o) np.add(np.ones_like(d), d) np.add(d, np.ones_like(d)) class TestPower(object): def test_small_types(self): for t in [np.int8, np.int16, np.float16]: a = t(3) b = a ** 4 assert_(b == 81, "error with %r: got %r" % (t, b)) def test_large_types(self): for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]: a = t(51) b = a ** 4 msg = "error with %r: got %r" % (t, b) if np.issubdtype(t, np.integer): assert_(b == 6765201, msg) else: assert_almost_equal(b, 6765201, err_msg=msg) def test_integers_to_negative_integer_power(self): # Note that the combination of uint64 with a signed integer # has common type np.float64. The other combinations should all # raise a ValueError for integer ** negative integer. exp = [np.array(-1, dt)[()] for dt in 'bhilq'] # 1 ** -1 possible special case base = [np.array(1, dt)[()] for dt in 'bhilqBHILQ'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, 1.) # -1 ** -1 possible special case base = [np.array(-1, dt)[()] for dt in 'bhilq'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, -1.) # 2 ** -1 perhaps generic base = [np.array(2, dt)[()] for dt in 'bhilqBHILQ'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, .5) def test_mixed_types(self): typelist = [np.int8, np.int16, np.float16, np.float32, np.float64, np.int8, np.int16, np.int32, np.int64] for t1 in typelist: for t2 in typelist: a = t1(3) b = t2(2) result = a**b msg = ("error with %r and %r:" "got %r, expected %r") % (t1, t2, result, 9) if np.issubdtype(np.dtype(result), np.integer): assert_(result == 9, msg) else: assert_almost_equal(result, 9, err_msg=msg) def test_modular_power(self): # modular power is not implemented, so ensure it errors a = 5 b = 4 c = 10 expected = pow(a, b, c) # noqa: F841 for t in (np.int32, np.float32, np.complex64): # note that 3-operand power only dispatches on the first argument assert_raises(TypeError, operator.pow, t(a), b, c) assert_raises(TypeError, operator.pow, np.array(t(a)), b, c) def floordiv_and_mod(x, y): return (x // y, x % y) def _signs(dt): if dt in np.typecodes['UnsignedInteger']: return (+1,) else: return (+1, -1) class TestModulus(object): def test_modulus_basic(self): dt = np.typecodes['AllInteger'] + np.typecodes['Float'] for op in [floordiv_and_mod, divmod]: for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product(_signs(dt1), _signs(dt2)): fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (op.__name__, dt1, dt2, sg1, sg2) a = np.array(sg1*71, dtype=dt1)[()] b = np.array(sg2*19, dtype=dt2)[()] div, rem = op(a, b) assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg) def test_float_modulus_exact(self): # test that float results are exact for small integers. This also # holds for the same integers scaled by powers of two. nlst = list(range(-127, 0)) plst = list(range(1, 128)) dividend = nlst + [0] + plst divisor = nlst + plst arg = list(itertools.product(dividend, divisor)) tgt = list(divmod(*t) for t in arg) a, b = np.array(arg, dtype=int).T # convert exact integer results from Python to float so that # signed zero can be used, it is checked. tgtdiv, tgtrem = np.array(tgt, dtype=float).T tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv) tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem) for op in [floordiv_and_mod, divmod]: for dt in np.typecodes['Float']: msg = 'op: %s, dtype: %s' % (op.__name__, dt) fa = a.astype(dt) fb = b.astype(dt) # use list comprehension so a_ and b_ are scalars div, rem = zip(*[op(a_, b_) for a_, b_ in zip(fa, fb)]) assert_equal(div, tgtdiv, err_msg=msg) assert_equal(rem, tgtrem, err_msg=msg) def test_float_modulus_roundoff(self): # gh-6127 dt = np.typecodes['Float'] for op in [floordiv_and_mod, divmod]: for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product((+1, -1), (+1, -1)): fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (op.__name__, dt1, dt2, sg1, sg2) a = np.array(sg1*78*6e-8, dtype=dt1)[()] b = np.array(sg2*6e-8, dtype=dt2)[()] div, rem = op(a, b) # Equal assertion should hold when fmod is used assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg) def test_float_modulus_corner_cases(self): # Check remainder magnitude. for dt in np.typecodes['Float']: b = np.array(1.0, dtype=dt) a = np.nextafter(np.array(0.0, dtype=dt), -b) rem = operator.mod(a, b) assert_(rem <= b, 'dt: %s' % dt) rem = operator.mod(-a, -b) assert_(rem >= -b, 'dt: %s' % dt) # Check nans, inf with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in remainder") for dt in np.typecodes['Float']: fone = np.array(1.0, dtype=dt) fzer = np.array(0.0, dtype=dt) finf = np.array(np.inf, dtype=dt) fnan = np.array(np.nan, dtype=dt) rem = operator.mod(fone, fzer) assert_(np.isnan(rem), 'dt: %s' % dt) # MSVC 2008 returns NaN here, so disable the check. #rem = operator.mod(fone, finf) #assert_(rem == fone, 'dt: %s' % dt) rem = operator.mod(fone, fnan) assert_(np.isnan(rem), 'dt: %s' % dt) rem = operator.mod(finf, fone) assert_(np.isnan(rem), 'dt: %s' % dt) class TestComplexDivision(object): def test_zero_division(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: a = t(0.0) b = t(1.0) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.nan)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.nan)) assert_(np.isnan(b/a)) b = t(0.) assert_(np.isnan(b/a)) def test_signed_zeros(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = ( (( 0.0,-1.0), ( 0.0, 1.0), (-1.0,-0.0)), (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), (( 0.0,-1.0), (-0.0,-1.0), ( 1.0, 0.0)), (( 0.0,-1.0), (-0.0, 1.0), (-1.0, 0.0)), (( 0.0, 1.0), ( 0.0,-1.0), (-1.0, 0.0)), (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), ((-0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), ((-0.0, 1.0), ( 0.0,-1.0), (-1.0,-0.0)) ) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1]) def test_branches(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = list() # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by else condition as neither are == 0 data.append((( 2.0, 1.0), ( 2.0, 1.0), (1.0, 0.0))) # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by if condition as both are == 0 # is performed in test_zero_division(), so this is skipped # trigger else if branch: real(fabs(denom)) < imag(fabs(denom)) data.append((( 1.0, 2.0), ( 1.0, 2.0), (1.0, 0.0))) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1]) class TestConversion(object): def test_int_from_long(self): l = [1e6, 1e12, 1e18, -1e6, -1e12, -1e18] li = [10**6, 10**12, 10**18, -10**6, -10**12, -10**18] for T in [None, np.float64, np.int64]: a = np.array(l, dtype=T) assert_equal([int(_m) for _m in a], li) a = np.array(l[:3], dtype=np.uint64) assert_equal([int(_m) for _m in a], li[:3]) def test_iinfo_long_values(self): for code in 'bBhH': res = np.array(np.iinfo(code).max + 1, dtype=code) tgt = np.iinfo(code).min assert_(res == tgt) for code in np.typecodes['AllInteger']: res = np.array(np.iinfo(code).max, dtype=code) tgt = np.iinfo(code).max assert_(res == tgt) for code in np.typecodes['AllInteger']: res = np.typeDict[code](np.iinfo(code).max) tgt = np.iinfo(code).max assert_(res == tgt) def test_int_raise_behaviour(self): def overflow_error_func(dtype): np.typeDict[dtype](np.iinfo(dtype).max + 1) for code in 'lLqQ': assert_raises(OverflowError, overflow_error_func, code) def test_int_from_infinite_longdouble(self): # gh-627 x = np.longdouble(np.inf) assert_raises(OverflowError, int, x) with suppress_warnings() as sup: sup.record(np.ComplexWarning) x = np.clongdouble(np.inf) assert_raises(OverflowError, int, x) assert_equal(len(sup.log), 1) @pytest.mark.skipif(not IS_PYPY, reason="Test is PyPy only (gh-9972)") def test_int_from_infinite_longdouble___int__(self): x = np.longdouble(np.inf) assert_raises(OverflowError, x.__int__) with suppress_warnings() as sup: sup.record(np.ComplexWarning) x = np.clongdouble(np.inf) assert_raises(OverflowError, x.__int__) assert_equal(len(sup.log), 1) @pytest.mark.skipif(np.finfo(np.double) == np.finfo(np.longdouble), reason="long double is same as double") @pytest.mark.skipif(platform.machine().startswith("ppc"), reason="IBM double double") def test_int_from_huge_longdouble(self): # Produce a longdouble that would overflow a double, # use exponent that avoids bug in Darwin pow function. exp = np.finfo(np.double).maxexp - 1 huge_ld = 2 * 1234 * np.longdouble(2) ** exp huge_i = 2 * 1234 * 2 ** exp assert_(huge_ld != np.inf) assert_equal(int(huge_ld), huge_i) def test_int_from_longdouble(self): x = np.longdouble(1.5) assert_equal(int(x), 1) x = np.longdouble(-10.5) assert_equal(int(x), -10) def test_numpy_scalar_relational_operators(self): # All integer for dt1 in np.typecodes['AllInteger']: assert_(1 > np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not 1 < np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,)) for dt2 in np.typecodes['AllInteger']: assert_(np.array(1, dtype=dt1)[()] > np.array(0, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(0, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) #Unsigned integers for dt1 in 'BHILQP': assert_(-1 < np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not -1 > np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(-1 != np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) #unsigned vs signed for dt2 in 'bhilqp': assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(np.array(1, dtype=dt1)[()] != np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) #Signed integers and floats for dt1 in 'bhlqp' + np.typecodes['Float']: assert_(1 > np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not 1 < np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(-1 == np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) for dt2 in 'bhlqp' + np.typecodes['Float']: assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(np.array(-1, dtype=dt1)[()] == np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) def test_scalar_comparison_to_none(self): # Scalars should just return False and not give a warnings. # The comparisons are flagged by pep8, ignore that. with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', FutureWarning) assert_(not np.float32(1) == None) assert_(not np.str_('test') == None) # This is dubious (see below): assert_(not np.datetime64('NaT') == None) assert_(np.float32(1) != None) assert_(np.str_('test') != None) # This is dubious (see below): assert_(np.datetime64('NaT') != None) assert_(len(w) == 0) # For documentation purposes, this is why the datetime is dubious. # At the time of deprecation this was no behaviour change, but # it has to be considered when the deprecations are done. assert_(np.equal(np.datetime64('NaT'), None)) #class TestRepr(object): # def test_repr(self): # for t in types: # val = t(1197346475.0137341) # val_repr = repr(val) # val2 = eval(val_repr) # assert_equal( val, val2 ) class TestRepr(object): def _test_type_repr(self, t): finfo = np.finfo(t) last_fraction_bit_idx = finfo.nexp + finfo.nmant last_exponent_bit_idx = finfo.nexp storage_bytes = np.dtype(t).itemsize*8 # could add some more types to the list below for which in ['small denorm', 'small norm']: # Values from https://en.wikipedia.org/wiki/IEEE_754 constr = np.array([0x00]*storage_bytes, dtype=np.uint8) if which == 'small denorm': byte = last_fraction_bit_idx // 8 bytebit = 7-(last_fraction_bit_idx % 8) constr[byte] = 1 << bytebit elif which == 'small norm': byte = last_exponent_bit_idx // 8 bytebit = 7-(last_exponent_bit_idx % 8) constr[byte] = 1 << bytebit else: raise ValueError('hmm') val = constr.view(t)[0] val_repr = repr(val) val2 = t(eval(val_repr)) if not (val2 == 0 and val < 1e-100): assert_equal(val, val2) def test_float_repr(self): # long double test cannot work, because eval goes through a python # float for t in [np.float32, np.float64]: self._test_type_repr(t) if not IS_PYPY: # sys.getsizeof() is not valid on PyPy class TestSizeOf(object): def test_equal_nbytes(self): for type in types: x = type(0) assert_(sys.getsizeof(x) > x.nbytes) def test_error(self): d = np.float32() assert_raises(TypeError, d.__sizeof__, "a") class TestMultiply(object): def test_seq_repeat(self): # Test that basic sequences get repeated when multiplied with # numpy integers. And errors are raised when multiplied with others. # Some of this behaviour may be controversial and could be open for # change. accepted_types = set(np.typecodes["AllInteger"]) deprecated_types = {'?'} forbidden_types = ( set(np.typecodes["All"]) - accepted_types - deprecated_types) forbidden_types -= {'V'} # can't default-construct void scalars for seq_type in (list, tuple): seq = seq_type([1, 2, 3]) for numpy_type in accepted_types: i = np.dtype(numpy_type).type(2) assert_equal(seq * i, seq * int(i)) assert_equal(i * seq, int(i) * seq) for numpy_type in deprecated_types: i = np.dtype(numpy_type).type() assert_equal( assert_warns(DeprecationWarning, operator.mul, seq, i), seq * int(i)) assert_equal( assert_warns(DeprecationWarning, operator.mul, i, seq), int(i) * seq) for numpy_type in forbidden_types: i = np.dtype(numpy_type).type() assert_raises(TypeError, operator.mul, seq, i) assert_raises(TypeError, operator.mul, i, seq) def test_no_seq_repeat_basic_array_like(self): # Test that an array-like which does not know how to be multiplied # does not attempt sequence repeat (raise TypeError). # See also gh-7428. class ArrayLike(object): def __init__(self, arr): self.arr = arr def __array__(self): return self.arr # Test for simple ArrayLike above and memoryviews (original report) for arr_like in (ArrayLike(np.ones(3)), memoryview(np.ones(3))): assert_array_equal(arr_like * np.float32(3.), np.full(3, 3.)) assert_array_equal(np.float32(3.) * arr_like, np.full(3, 3.)) assert_array_equal(arr_like * np.int_(3), np.full(3, 3)) assert_array_equal(np.int_(3) * arr_like, np.full(3, 3)) class TestNegative(object): def test_exceptions(self): a = np.ones((), dtype=np.bool_)[()] assert_raises(TypeError, operator.neg, a) def test_result(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] with suppress_warnings() as sup: sup.filter(RuntimeWarning) for dt in types: a = np.ones((), dtype=dt)[()] assert_equal(operator.neg(a) + a, 0) class TestSubtract(object): def test_exceptions(self): a = np.ones((), dtype=np.bool_)[()] assert_raises(TypeError, operator.sub, a, a) def test_result(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] with suppress_warnings() as sup: sup.filter(RuntimeWarning) for dt in types: a = np.ones((), dtype=dt)[()] assert_equal(operator.sub(a, a), 0) class TestAbs(object): def _test_abs_func(self, absfunc): for tp in floating_types + complex_floating_types: x = tp(-1.5) assert_equal(absfunc(x), 1.5) x = tp(0.0) res = absfunc(x) # assert_equal() checks zero signedness assert_equal(res, 0.0) x = tp(-0.0) res = absfunc(x) assert_equal(res, 0.0) x = tp(np.finfo(tp).max) assert_equal(absfunc(x), x.real) x = tp(np.finfo(tp).tiny) assert_equal(absfunc(x), x.real) x = tp(np.finfo(tp).min) assert_equal(absfunc(x), -x.real) def test_builtin_abs(self): self._test_abs_func(abs) def test_numpy_abs(self): self._test_abs_func(np.abs) class TestBitShifts(object): @pytest.mark.parametrize('type_code', np.typecodes['AllInteger']) @pytest.mark.parametrize('op', [operator.rshift, operator.lshift], ids=['>>', '<<']) def test_shift_all_bits(self, type_code, op): """ Shifts where the shift amount is the width of the type or wider """ # gh-2449 dt = np.dtype(type_code) nbits = dt.itemsize * 8 for val in [5, -5]: for shift in [nbits, nbits + 4]: val_scl = dt.type(val) shift_scl = dt.type(shift) res_scl = op(val_scl, shift_scl) if val_scl < 0 and op is operator.rshift: # sign bit is preserved assert_equal(res_scl, -1) else: assert_equal(res_scl, 0) # Result on scalars should be the same as on arrays val_arr = np.array([val]*32, dtype=dt) shift_arr = np.array([shift]*32, dtype=dt) res_arr = op(val_arr, shift_arr) assert_equal(res_arr, res_scl)
MSeifert04/numpy
numpy/core/tests/test_scalarmath.py
numpy/lib/tests/test_stride_tricks.py
"""Defines a multi-dimensional array and useful procedures for Numerical computation. Functions - array - NumPy Array construction - zeros - Return an array of all zeros - empty - Return an uninitialized array - shape - Return shape of sequence or array - rank - Return number of dimensions - size - Return number of elements in entire array or a certain dimension - fromstring - Construct array from (byte) string - take - Select sub-arrays using sequence of indices - put - Set sub-arrays using sequence of 1-D indices - putmask - Set portion of arrays using a mask - reshape - Return array with new shape - repeat - Repeat elements of array - choose - Construct new array from indexed array tuple - correlate - Correlate two 1-d arrays - searchsorted - Search for element in 1-d array - sum - Total sum over a specified dimension - average - Average, possibly weighted, over axis or array. - cumsum - Cumulative sum over a specified dimension - product - Total product over a specified dimension - cumproduct - Cumulative product over a specified dimension - alltrue - Logical and over an entire axis - sometrue - Logical or over an entire axis - allclose - Tests if sequences are essentially equal More Functions: - arange - Return regularly spaced array - asarray - Guarantee NumPy array - convolve - Convolve two 1-d arrays - swapaxes - Exchange axes - concatenate - Join arrays together - transpose - Permute axes - sort - Sort elements of array - argsort - Indices of sorted array - argmax - Index of largest value - argmin - Index of smallest value - inner - Innerproduct of two arrays - dot - Dot product (matrix multiplication) - outer - Outerproduct of two arrays - resize - Return array with arbitrary new shape - indices - Tuple of indices - fromfunction - Construct array from universal function - diagonal - Return diagonal array - trace - Trace of array - dump - Dump array to file object (pickle) - dumps - Return pickled string representing data - load - Return array stored in file object - loads - Return array from pickled string - ravel - Return array as 1-D - nonzero - Indices of nonzero elements for 1-D array - shape - Shape of array - where - Construct array from binary result - compress - Elements of array where condition is true - clip - Clip array between two values - ones - Array of all ones - identity - 2-D identity array (matrix) (Universal) Math Functions add logical_or exp subtract logical_xor log multiply logical_not log10 divide maximum sin divide_safe minimum sinh conjugate bitwise_and sqrt power bitwise_or tan absolute bitwise_xor tanh negative invert ceil greater left_shift fabs greater_equal right_shift floor less arccos arctan2 less_equal arcsin fmod equal arctan hypot not_equal cos around logical_and cosh sign arccosh arcsinh arctanh """ from __future__ import division, absolute_import, print_function depends = ['testing'] global_symbols = ['*']
from __future__ import division, absolute_import, print_function import sys import warnings import itertools import operator import platform import pytest import numpy as np from numpy.testing import ( assert_, assert_equal, assert_raises, assert_almost_equal, assert_array_equal, IS_PYPY, suppress_warnings, _gen_alignment_data, assert_warns ) types = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc, np.int_, np.uint, np.longlong, np.ulonglong, np.single, np.double, np.longdouble, np.csingle, np.cdouble, np.clongdouble] floating_types = np.floating.__subclasses__() complex_floating_types = np.complexfloating.__subclasses__() # This compares scalarmath against ufuncs. class TestTypes(object): def test_types(self): for atype in types: a = atype(1) assert_(a == 1, "error with %r: got %r" % (atype, a)) def test_type_add(self): # list of types for k, atype in enumerate(types): a_scalar = atype(3) a_array = np.array([3], dtype=atype) for l, btype in enumerate(types): b_scalar = btype(1) b_array = np.array([1], dtype=btype) c_scalar = a_scalar + b_scalar c_array = a_array + b_array # It was comparing the type numbers, but the new ufunc # function-finding mechanism finds the lowest function # to which both inputs can be cast - which produces 'l' # when you do 'q' + 'b'. The old function finding mechanism # skipped ahead based on the first argument, but that # does not produce properly symmetric results... assert_equal(c_scalar.dtype, c_array.dtype, "error with types (%d/'%c' + %d/'%c')" % (k, np.dtype(atype).char, l, np.dtype(btype).char)) def test_type_create(self): for k, atype in enumerate(types): a = np.array([1, 2, 3], atype) b = atype([1, 2, 3]) assert_equal(a, b) def test_leak(self): # test leak of scalar objects # a leak would show up in valgrind as still-reachable of ~2.6MB for i in range(200000): np.add(1, 1) class TestBaseMath(object): def test_blocked(self): # test alignments offsets for simd instructions # alignments for vz + 2 * (vs - 1) + 1 for dt, sz in [(np.float32, 11), (np.float64, 7), (np.int32, 11)]: for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt, type='binary', max_size=sz): exp1 = np.ones_like(inp1) inp1[...] = np.ones_like(inp1) inp2[...] = np.zeros_like(inp2) assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg) assert_almost_equal(np.add(inp1, 2), exp1 + 2, err_msg=msg) assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg) np.add(inp1, inp2, out=out) assert_almost_equal(out, exp1, err_msg=msg) inp2[...] += np.arange(inp2.size, dtype=dt) + 1 assert_almost_equal(np.square(inp2), np.multiply(inp2, inp2), err_msg=msg) # skip true divide for ints if dt != np.int32 or (sys.version_info.major < 3 and not sys.py3kwarning): assert_almost_equal(np.reciprocal(inp2), np.divide(1, inp2), err_msg=msg) inp1[...] = np.ones_like(inp1) np.add(inp1, 2, out=out) assert_almost_equal(out, exp1 + 2, err_msg=msg) inp2[...] = np.ones_like(inp2) np.add(2, inp2, out=out) assert_almost_equal(out, exp1 + 2, err_msg=msg) def test_lower_align(self): # check data that is not aligned to element size # i.e doubles are aligned to 4 bytes on i386 d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) o = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) assert_almost_equal(d + d, d * 2) np.add(d, d, out=o) np.add(np.ones_like(d), d, out=o) np.add(d, np.ones_like(d), out=o) np.add(np.ones_like(d), d) np.add(d, np.ones_like(d)) class TestPower(object): def test_small_types(self): for t in [np.int8, np.int16, np.float16]: a = t(3) b = a ** 4 assert_(b == 81, "error with %r: got %r" % (t, b)) def test_large_types(self): for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]: a = t(51) b = a ** 4 msg = "error with %r: got %r" % (t, b) if np.issubdtype(t, np.integer): assert_(b == 6765201, msg) else: assert_almost_equal(b, 6765201, err_msg=msg) def test_integers_to_negative_integer_power(self): # Note that the combination of uint64 with a signed integer # has common type np.float64. The other combinations should all # raise a ValueError for integer ** negative integer. exp = [np.array(-1, dt)[()] for dt in 'bhilq'] # 1 ** -1 possible special case base = [np.array(1, dt)[()] for dt in 'bhilqBHILQ'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, 1.) # -1 ** -1 possible special case base = [np.array(-1, dt)[()] for dt in 'bhilq'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, -1.) # 2 ** -1 perhaps generic base = [np.array(2, dt)[()] for dt in 'bhilqBHILQ'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, .5) def test_mixed_types(self): typelist = [np.int8, np.int16, np.float16, np.float32, np.float64, np.int8, np.int16, np.int32, np.int64] for t1 in typelist: for t2 in typelist: a = t1(3) b = t2(2) result = a**b msg = ("error with %r and %r:" "got %r, expected %r") % (t1, t2, result, 9) if np.issubdtype(np.dtype(result), np.integer): assert_(result == 9, msg) else: assert_almost_equal(result, 9, err_msg=msg) def test_modular_power(self): # modular power is not implemented, so ensure it errors a = 5 b = 4 c = 10 expected = pow(a, b, c) # noqa: F841 for t in (np.int32, np.float32, np.complex64): # note that 3-operand power only dispatches on the first argument assert_raises(TypeError, operator.pow, t(a), b, c) assert_raises(TypeError, operator.pow, np.array(t(a)), b, c) def floordiv_and_mod(x, y): return (x // y, x % y) def _signs(dt): if dt in np.typecodes['UnsignedInteger']: return (+1,) else: return (+1, -1) class TestModulus(object): def test_modulus_basic(self): dt = np.typecodes['AllInteger'] + np.typecodes['Float'] for op in [floordiv_and_mod, divmod]: for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product(_signs(dt1), _signs(dt2)): fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (op.__name__, dt1, dt2, sg1, sg2) a = np.array(sg1*71, dtype=dt1)[()] b = np.array(sg2*19, dtype=dt2)[()] div, rem = op(a, b) assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg) def test_float_modulus_exact(self): # test that float results are exact for small integers. This also # holds for the same integers scaled by powers of two. nlst = list(range(-127, 0)) plst = list(range(1, 128)) dividend = nlst + [0] + plst divisor = nlst + plst arg = list(itertools.product(dividend, divisor)) tgt = list(divmod(*t) for t in arg) a, b = np.array(arg, dtype=int).T # convert exact integer results from Python to float so that # signed zero can be used, it is checked. tgtdiv, tgtrem = np.array(tgt, dtype=float).T tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv) tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem) for op in [floordiv_and_mod, divmod]: for dt in np.typecodes['Float']: msg = 'op: %s, dtype: %s' % (op.__name__, dt) fa = a.astype(dt) fb = b.astype(dt) # use list comprehension so a_ and b_ are scalars div, rem = zip(*[op(a_, b_) for a_, b_ in zip(fa, fb)]) assert_equal(div, tgtdiv, err_msg=msg) assert_equal(rem, tgtrem, err_msg=msg) def test_float_modulus_roundoff(self): # gh-6127 dt = np.typecodes['Float'] for op in [floordiv_and_mod, divmod]: for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product((+1, -1), (+1, -1)): fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (op.__name__, dt1, dt2, sg1, sg2) a = np.array(sg1*78*6e-8, dtype=dt1)[()] b = np.array(sg2*6e-8, dtype=dt2)[()] div, rem = op(a, b) # Equal assertion should hold when fmod is used assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg) def test_float_modulus_corner_cases(self): # Check remainder magnitude. for dt in np.typecodes['Float']: b = np.array(1.0, dtype=dt) a = np.nextafter(np.array(0.0, dtype=dt), -b) rem = operator.mod(a, b) assert_(rem <= b, 'dt: %s' % dt) rem = operator.mod(-a, -b) assert_(rem >= -b, 'dt: %s' % dt) # Check nans, inf with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in remainder") for dt in np.typecodes['Float']: fone = np.array(1.0, dtype=dt) fzer = np.array(0.0, dtype=dt) finf = np.array(np.inf, dtype=dt) fnan = np.array(np.nan, dtype=dt) rem = operator.mod(fone, fzer) assert_(np.isnan(rem), 'dt: %s' % dt) # MSVC 2008 returns NaN here, so disable the check. #rem = operator.mod(fone, finf) #assert_(rem == fone, 'dt: %s' % dt) rem = operator.mod(fone, fnan) assert_(np.isnan(rem), 'dt: %s' % dt) rem = operator.mod(finf, fone) assert_(np.isnan(rem), 'dt: %s' % dt) class TestComplexDivision(object): def test_zero_division(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: a = t(0.0) b = t(1.0) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.nan)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.nan)) assert_(np.isnan(b/a)) b = t(0.) assert_(np.isnan(b/a)) def test_signed_zeros(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = ( (( 0.0,-1.0), ( 0.0, 1.0), (-1.0,-0.0)), (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), (( 0.0,-1.0), (-0.0,-1.0), ( 1.0, 0.0)), (( 0.0,-1.0), (-0.0, 1.0), (-1.0, 0.0)), (( 0.0, 1.0), ( 0.0,-1.0), (-1.0, 0.0)), (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), ((-0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), ((-0.0, 1.0), ( 0.0,-1.0), (-1.0,-0.0)) ) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1]) def test_branches(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = list() # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by else condition as neither are == 0 data.append((( 2.0, 1.0), ( 2.0, 1.0), (1.0, 0.0))) # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by if condition as both are == 0 # is performed in test_zero_division(), so this is skipped # trigger else if branch: real(fabs(denom)) < imag(fabs(denom)) data.append((( 1.0, 2.0), ( 1.0, 2.0), (1.0, 0.0))) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1]) class TestConversion(object): def test_int_from_long(self): l = [1e6, 1e12, 1e18, -1e6, -1e12, -1e18] li = [10**6, 10**12, 10**18, -10**6, -10**12, -10**18] for T in [None, np.float64, np.int64]: a = np.array(l, dtype=T) assert_equal([int(_m) for _m in a], li) a = np.array(l[:3], dtype=np.uint64) assert_equal([int(_m) for _m in a], li[:3]) def test_iinfo_long_values(self): for code in 'bBhH': res = np.array(np.iinfo(code).max + 1, dtype=code) tgt = np.iinfo(code).min assert_(res == tgt) for code in np.typecodes['AllInteger']: res = np.array(np.iinfo(code).max, dtype=code) tgt = np.iinfo(code).max assert_(res == tgt) for code in np.typecodes['AllInteger']: res = np.typeDict[code](np.iinfo(code).max) tgt = np.iinfo(code).max assert_(res == tgt) def test_int_raise_behaviour(self): def overflow_error_func(dtype): np.typeDict[dtype](np.iinfo(dtype).max + 1) for code in 'lLqQ': assert_raises(OverflowError, overflow_error_func, code) def test_int_from_infinite_longdouble(self): # gh-627 x = np.longdouble(np.inf) assert_raises(OverflowError, int, x) with suppress_warnings() as sup: sup.record(np.ComplexWarning) x = np.clongdouble(np.inf) assert_raises(OverflowError, int, x) assert_equal(len(sup.log), 1) @pytest.mark.skipif(not IS_PYPY, reason="Test is PyPy only (gh-9972)") def test_int_from_infinite_longdouble___int__(self): x = np.longdouble(np.inf) assert_raises(OverflowError, x.__int__) with suppress_warnings() as sup: sup.record(np.ComplexWarning) x = np.clongdouble(np.inf) assert_raises(OverflowError, x.__int__) assert_equal(len(sup.log), 1) @pytest.mark.skipif(np.finfo(np.double) == np.finfo(np.longdouble), reason="long double is same as double") @pytest.mark.skipif(platform.machine().startswith("ppc"), reason="IBM double double") def test_int_from_huge_longdouble(self): # Produce a longdouble that would overflow a double, # use exponent that avoids bug in Darwin pow function. exp = np.finfo(np.double).maxexp - 1 huge_ld = 2 * 1234 * np.longdouble(2) ** exp huge_i = 2 * 1234 * 2 ** exp assert_(huge_ld != np.inf) assert_equal(int(huge_ld), huge_i) def test_int_from_longdouble(self): x = np.longdouble(1.5) assert_equal(int(x), 1) x = np.longdouble(-10.5) assert_equal(int(x), -10) def test_numpy_scalar_relational_operators(self): # All integer for dt1 in np.typecodes['AllInteger']: assert_(1 > np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not 1 < np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,)) for dt2 in np.typecodes['AllInteger']: assert_(np.array(1, dtype=dt1)[()] > np.array(0, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(0, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) #Unsigned integers for dt1 in 'BHILQP': assert_(-1 < np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not -1 > np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(-1 != np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) #unsigned vs signed for dt2 in 'bhilqp': assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(np.array(1, dtype=dt1)[()] != np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) #Signed integers and floats for dt1 in 'bhlqp' + np.typecodes['Float']: assert_(1 > np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not 1 < np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(-1 == np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) for dt2 in 'bhlqp' + np.typecodes['Float']: assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(np.array(-1, dtype=dt1)[()] == np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) def test_scalar_comparison_to_none(self): # Scalars should just return False and not give a warnings. # The comparisons are flagged by pep8, ignore that. with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', FutureWarning) assert_(not np.float32(1) == None) assert_(not np.str_('test') == None) # This is dubious (see below): assert_(not np.datetime64('NaT') == None) assert_(np.float32(1) != None) assert_(np.str_('test') != None) # This is dubious (see below): assert_(np.datetime64('NaT') != None) assert_(len(w) == 0) # For documentation purposes, this is why the datetime is dubious. # At the time of deprecation this was no behaviour change, but # it has to be considered when the deprecations are done. assert_(np.equal(np.datetime64('NaT'), None)) #class TestRepr(object): # def test_repr(self): # for t in types: # val = t(1197346475.0137341) # val_repr = repr(val) # val2 = eval(val_repr) # assert_equal( val, val2 ) class TestRepr(object): def _test_type_repr(self, t): finfo = np.finfo(t) last_fraction_bit_idx = finfo.nexp + finfo.nmant last_exponent_bit_idx = finfo.nexp storage_bytes = np.dtype(t).itemsize*8 # could add some more types to the list below for which in ['small denorm', 'small norm']: # Values from https://en.wikipedia.org/wiki/IEEE_754 constr = np.array([0x00]*storage_bytes, dtype=np.uint8) if which == 'small denorm': byte = last_fraction_bit_idx // 8 bytebit = 7-(last_fraction_bit_idx % 8) constr[byte] = 1 << bytebit elif which == 'small norm': byte = last_exponent_bit_idx // 8 bytebit = 7-(last_exponent_bit_idx % 8) constr[byte] = 1 << bytebit else: raise ValueError('hmm') val = constr.view(t)[0] val_repr = repr(val) val2 = t(eval(val_repr)) if not (val2 == 0 and val < 1e-100): assert_equal(val, val2) def test_float_repr(self): # long double test cannot work, because eval goes through a python # float for t in [np.float32, np.float64]: self._test_type_repr(t) if not IS_PYPY: # sys.getsizeof() is not valid on PyPy class TestSizeOf(object): def test_equal_nbytes(self): for type in types: x = type(0) assert_(sys.getsizeof(x) > x.nbytes) def test_error(self): d = np.float32() assert_raises(TypeError, d.__sizeof__, "a") class TestMultiply(object): def test_seq_repeat(self): # Test that basic sequences get repeated when multiplied with # numpy integers. And errors are raised when multiplied with others. # Some of this behaviour may be controversial and could be open for # change. accepted_types = set(np.typecodes["AllInteger"]) deprecated_types = {'?'} forbidden_types = ( set(np.typecodes["All"]) - accepted_types - deprecated_types) forbidden_types -= {'V'} # can't default-construct void scalars for seq_type in (list, tuple): seq = seq_type([1, 2, 3]) for numpy_type in accepted_types: i = np.dtype(numpy_type).type(2) assert_equal(seq * i, seq * int(i)) assert_equal(i * seq, int(i) * seq) for numpy_type in deprecated_types: i = np.dtype(numpy_type).type() assert_equal( assert_warns(DeprecationWarning, operator.mul, seq, i), seq * int(i)) assert_equal( assert_warns(DeprecationWarning, operator.mul, i, seq), int(i) * seq) for numpy_type in forbidden_types: i = np.dtype(numpy_type).type() assert_raises(TypeError, operator.mul, seq, i) assert_raises(TypeError, operator.mul, i, seq) def test_no_seq_repeat_basic_array_like(self): # Test that an array-like which does not know how to be multiplied # does not attempt sequence repeat (raise TypeError). # See also gh-7428. class ArrayLike(object): def __init__(self, arr): self.arr = arr def __array__(self): return self.arr # Test for simple ArrayLike above and memoryviews (original report) for arr_like in (ArrayLike(np.ones(3)), memoryview(np.ones(3))): assert_array_equal(arr_like * np.float32(3.), np.full(3, 3.)) assert_array_equal(np.float32(3.) * arr_like, np.full(3, 3.)) assert_array_equal(arr_like * np.int_(3), np.full(3, 3)) assert_array_equal(np.int_(3) * arr_like, np.full(3, 3)) class TestNegative(object): def test_exceptions(self): a = np.ones((), dtype=np.bool_)[()] assert_raises(TypeError, operator.neg, a) def test_result(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] with suppress_warnings() as sup: sup.filter(RuntimeWarning) for dt in types: a = np.ones((), dtype=dt)[()] assert_equal(operator.neg(a) + a, 0) class TestSubtract(object): def test_exceptions(self): a = np.ones((), dtype=np.bool_)[()] assert_raises(TypeError, operator.sub, a, a) def test_result(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] with suppress_warnings() as sup: sup.filter(RuntimeWarning) for dt in types: a = np.ones((), dtype=dt)[()] assert_equal(operator.sub(a, a), 0) class TestAbs(object): def _test_abs_func(self, absfunc): for tp in floating_types + complex_floating_types: x = tp(-1.5) assert_equal(absfunc(x), 1.5) x = tp(0.0) res = absfunc(x) # assert_equal() checks zero signedness assert_equal(res, 0.0) x = tp(-0.0) res = absfunc(x) assert_equal(res, 0.0) x = tp(np.finfo(tp).max) assert_equal(absfunc(x), x.real) x = tp(np.finfo(tp).tiny) assert_equal(absfunc(x), x.real) x = tp(np.finfo(tp).min) assert_equal(absfunc(x), -x.real) def test_builtin_abs(self): self._test_abs_func(abs) def test_numpy_abs(self): self._test_abs_func(np.abs) class TestBitShifts(object): @pytest.mark.parametrize('type_code', np.typecodes['AllInteger']) @pytest.mark.parametrize('op', [operator.rshift, operator.lshift], ids=['>>', '<<']) def test_shift_all_bits(self, type_code, op): """ Shifts where the shift amount is the width of the type or wider """ # gh-2449 dt = np.dtype(type_code) nbits = dt.itemsize * 8 for val in [5, -5]: for shift in [nbits, nbits + 4]: val_scl = dt.type(val) shift_scl = dt.type(shift) res_scl = op(val_scl, shift_scl) if val_scl < 0 and op is operator.rshift: # sign bit is preserved assert_equal(res_scl, -1) else: assert_equal(res_scl, 0) # Result on scalars should be the same as on arrays val_arr = np.array([val]*32, dtype=dt) shift_arr = np.array([shift]*32, dtype=dt) res_arr = op(val_arr, shift_arr) assert_equal(res_arr, res_scl)
MSeifert04/numpy
numpy/core/tests/test_scalarmath.py
numpy/core/info.py
# Added Fortran compiler support to config. Currently useful only for # try_compile call. try_run works but is untested for most of Fortran # compilers (they must define linker_exe first). # Pearu Peterson from __future__ import division, absolute_import, print_function import os, signal import warnings import sys import subprocess import textwrap from distutils.command.config import config as old_config from distutils.command.config import LANG_EXT from distutils import log from distutils.file_util import copy_file from distutils.ccompiler import CompileError, LinkError import distutils from numpy.distutils.exec_command import filepath_from_subprocess_output from numpy.distutils.mingw32ccompiler import generate_manifest from numpy.distutils.command.autodist import (check_gcc_function_attribute, check_gcc_function_attribute_with_intrinsics, check_gcc_variable_attribute, check_inline, check_restrict, check_compiler_gcc4) from numpy.distutils.compat import get_exception LANG_EXT['f77'] = '.f' LANG_EXT['f90'] = '.f90' class config(old_config): old_config.user_options += [ ('fcompiler=', None, "specify the Fortran compiler type"), ] def initialize_options(self): self.fcompiler = None old_config.initialize_options(self) def _check_compiler (self): old_config._check_compiler(self) from numpy.distutils.fcompiler import FCompiler, new_fcompiler if sys.platform == 'win32' and (self.compiler.compiler_type in ('msvc', 'intelw', 'intelemw')): # XXX: hack to circumvent a python 2.6 bug with msvc9compiler: # initialize call query_vcvarsall, which throws an IOError, and # causes an error along the way without much information. We try to # catch it here, hoping it is early enough, and print an helpful # message instead of Error: None. if not self.compiler.initialized: try: self.compiler.initialize() except IOError: e = get_exception() msg = textwrap.dedent("""\ Could not initialize compiler instance: do you have Visual Studio installed? If you are trying to build with MinGW, please use "python setup.py build -c mingw32" instead. If you have Visual Studio installed, check it is correctly installed, and the right version (VS 2008 for python 2.6, 2.7 and 3.2, VS 2010 for >= 3.3). Original exception was: %s, and the Compiler class was %s ============================================================================""") \ % (e, self.compiler.__class__.__name__) print(textwrap.dedent("""\ ============================================================================""")) raise distutils.errors.DistutilsPlatformError(msg) # After MSVC is initialized, add an explicit /MANIFEST to linker # flags. See issues gh-4245 and gh-4101 for details. Also # relevant are issues 4431 and 16296 on the Python bug tracker. from distutils import msvc9compiler if msvc9compiler.get_build_version() >= 10: for ldflags in [self.compiler.ldflags_shared, self.compiler.ldflags_shared_debug]: if '/MANIFEST' not in ldflags: ldflags.append('/MANIFEST') if not isinstance(self.fcompiler, FCompiler): self.fcompiler = new_fcompiler(compiler=self.fcompiler, dry_run=self.dry_run, force=1, c_compiler=self.compiler) if self.fcompiler is not None: self.fcompiler.customize(self.distribution) if self.fcompiler.get_version(): self.fcompiler.customize_cmd(self) self.fcompiler.show_customization() def _wrap_method(self, mth, lang, args): from distutils.ccompiler import CompileError from distutils.errors import DistutilsExecError save_compiler = self.compiler if lang in ['f77', 'f90']: self.compiler = self.fcompiler try: ret = mth(*((self,)+args)) except (DistutilsExecError, CompileError): str(get_exception()) self.compiler = save_compiler raise CompileError self.compiler = save_compiler return ret def _compile (self, body, headers, include_dirs, lang): src, obj = self._wrap_method(old_config._compile, lang, (body, headers, include_dirs, lang)) # _compile in unixcompiler.py sometimes creates .d dependency files. # Clean them up. self.temp_files.append(obj + '.d') return src, obj def _link (self, body, headers, include_dirs, libraries, library_dirs, lang): if self.compiler.compiler_type=='msvc': libraries = (libraries or [])[:] library_dirs = (library_dirs or [])[:] if lang in ['f77', 'f90']: lang = 'c' # always use system linker when using MSVC compiler if self.fcompiler: for d in self.fcompiler.library_dirs or []: # correct path when compiling in Cygwin but with # normal Win Python if d.startswith('/usr/lib'): try: d = subprocess.check_output(['cygpath', '-w', d]) except (OSError, subprocess.CalledProcessError): pass else: d = filepath_from_subprocess_output(d) library_dirs.append(d) for libname in self.fcompiler.libraries or []: if libname not in libraries: libraries.append(libname) for libname in libraries: if libname.startswith('msvc'): continue fileexists = False for libdir in library_dirs or []: libfile = os.path.join(libdir, '%s.lib' % (libname)) if os.path.isfile(libfile): fileexists = True break if fileexists: continue # make g77-compiled static libs available to MSVC fileexists = False for libdir in library_dirs: libfile = os.path.join(libdir, 'lib%s.a' % (libname)) if os.path.isfile(libfile): # copy libname.a file to name.lib so that MSVC linker # can find it libfile2 = os.path.join(libdir, '%s.lib' % (libname)) copy_file(libfile, libfile2) self.temp_files.append(libfile2) fileexists = True break if fileexists: continue log.warn('could not find library %r in directories %s' \ % (libname, library_dirs)) elif self.compiler.compiler_type == 'mingw32': generate_manifest(self) return self._wrap_method(old_config._link, lang, (body, headers, include_dirs, libraries, library_dirs, lang)) def check_header(self, header, include_dirs=None, library_dirs=None, lang='c'): self._check_compiler() return self.try_compile( "/* we need a dummy line to make distutils happy */", [header], include_dirs) def check_decl(self, symbol, headers=None, include_dirs=None): self._check_compiler() body = textwrap.dedent(""" int main(void) { #ifndef %s (void) %s; #endif ; return 0; }""") % (symbol, symbol) return self.try_compile(body, headers, include_dirs) def check_macro_true(self, symbol, headers=None, include_dirs=None): self._check_compiler() body = textwrap.dedent(""" int main(void) { #if %s #else #error false or undefined macro #endif ; return 0; }""") % (symbol,) return self.try_compile(body, headers, include_dirs) def check_type(self, type_name, headers=None, include_dirs=None, library_dirs=None): """Check type availability. Return True if the type can be compiled, False otherwise""" self._check_compiler() # First check the type can be compiled body = textwrap.dedent(r""" int main(void) { if ((%(name)s *) 0) return 0; if (sizeof (%(name)s)) return 0; } """) % {'name': type_name} st = False try: try: self._compile(body % {'type': type_name}, headers, include_dirs, 'c') st = True except distutils.errors.CompileError: st = False finally: self._clean() return st def check_type_size(self, type_name, headers=None, include_dirs=None, library_dirs=None, expected=None): """Check size of a given type.""" self._check_compiler() # First check the type can be compiled body = textwrap.dedent(r""" typedef %(type)s npy_check_sizeof_type; int main (void) { static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)]; test_array [0] = 0 ; return 0; } """) self._compile(body % {'type': type_name}, headers, include_dirs, 'c') self._clean() if expected: body = textwrap.dedent(r""" typedef %(type)s npy_check_sizeof_type; int main (void) { static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) == %(size)s)]; test_array [0] = 0 ; return 0; } """) for size in expected: try: self._compile(body % {'type': type_name, 'size': size}, headers, include_dirs, 'c') self._clean() return size except CompileError: pass # this fails to *compile* if size > sizeof(type) body = textwrap.dedent(r""" typedef %(type)s npy_check_sizeof_type; int main (void) { static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) <= %(size)s)]; test_array [0] = 0 ; return 0; } """) # The principle is simple: we first find low and high bounds of size # for the type, where low/high are looked up on a log scale. Then, we # do a binary search to find the exact size between low and high low = 0 mid = 0 while True: try: self._compile(body % {'type': type_name, 'size': mid}, headers, include_dirs, 'c') self._clean() break except CompileError: #log.info("failure to test for bound %d" % mid) low = mid + 1 mid = 2 * mid + 1 high = mid # Binary search: while low != high: mid = (high - low) // 2 + low try: self._compile(body % {'type': type_name, 'size': mid}, headers, include_dirs, 'c') self._clean() high = mid except CompileError: low = mid + 1 return low def check_func(self, func, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None): # clean up distutils's config a bit: add void to main(), and # return a value. self._check_compiler() body = [] if decl: if type(decl) == str: body.append(decl) else: body.append("int %s (void);" % func) # Handle MSVC intrinsics: force MS compiler to make a function call. # Useful to test for some functions when built with optimization on, to # avoid build error because the intrinsic and our 'fake' test # declaration do not match. body.append("#ifdef _MSC_VER") body.append("#pragma function(%s)" % func) body.append("#endif") body.append("int main (void) {") if call: if call_args is None: call_args = '' body.append(" %s(%s);" % (func, call_args)) else: body.append(" %s;" % func) body.append(" return 0;") body.append("}") body = '\n'.join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) def check_funcs_once(self, funcs, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None): """Check a list of functions at once. This is useful to speed up things, since all the functions in the funcs list will be put in one compilation unit. Arguments --------- funcs : seq list of functions to test include_dirs : seq list of header paths libraries : seq list of libraries to link the code snippet to library_dirs : seq list of library paths decl : dict for every (key, value), the declaration in the value will be used for function in key. If a function is not in the dictionary, no declaration will be used. call : dict for every item (f, value), if the value is True, a call will be done to the function f. """ self._check_compiler() body = [] if decl: for f, v in decl.items(): if v: body.append("int %s (void);" % f) # Handle MS intrinsics. See check_func for more info. body.append("#ifdef _MSC_VER") for func in funcs: body.append("#pragma function(%s)" % func) body.append("#endif") body.append("int main (void) {") if call: for f in funcs: if f in call and call[f]: if not (call_args and f in call_args and call_args[f]): args = '' else: args = call_args[f] body.append(" %s(%s);" % (f, args)) else: body.append(" %s;" % f) else: for f in funcs: body.append(" %s;" % f) body.append(" return 0;") body.append("}") body = '\n'.join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) def check_inline(self): """Return the inline keyword recognized by the compiler, empty string otherwise.""" return check_inline(self) def check_restrict(self): """Return the restrict keyword recognized by the compiler, empty string otherwise.""" return check_restrict(self) def check_compiler_gcc4(self): """Return True if the C compiler is gcc >= 4.""" return check_compiler_gcc4(self) def check_gcc_function_attribute(self, attribute, name): return check_gcc_function_attribute(self, attribute, name) def check_gcc_function_attribute_with_intrinsics(self, attribute, name, code, include): return check_gcc_function_attribute_with_intrinsics(self, attribute, name, code, include) def check_gcc_variable_attribute(self, attribute): return check_gcc_variable_attribute(self, attribute) def get_output(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c", use_tee=None): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Returns the exit status code of the program and its output. """ # 2008-11-16, RemoveMe warnings.warn("\n+++++++++++++++++++++++++++++++++++++++++++++++++\n" "Usage of get_output is deprecated: please do not \n" "use it anymore, and avoid configuration checks \n" "involving running executable on the target machine.\n" "+++++++++++++++++++++++++++++++++++++++++++++++++\n", DeprecationWarning, stacklevel=2) self._check_compiler() exitcode, output = 255, '' try: grabber = GrabStdout() try: src, obj, exe = self._link(body, headers, include_dirs, libraries, library_dirs, lang) grabber.restore() except Exception: output = grabber.data grabber.restore() raise exe = os.path.join('.', exe) try: # specify cwd arg for consistency with # historic usage pattern of exec_command() # also, note that exe appears to be a string, # which exec_command() handled, but we now # use a list for check_output() -- this assumes # that exe is always a single command output = subprocess.check_output([exe], cwd='.') except subprocess.CalledProcessError as exc: exitstatus = exc.returncode output = '' except OSError: # preserve the EnvironmentError exit status # used historically in exec_command() exitstatus = 127 output = '' else: output = filepath_from_subprocess_output(output) if hasattr(os, 'WEXITSTATUS'): exitcode = os.WEXITSTATUS(exitstatus) if os.WIFSIGNALED(exitstatus): sig = os.WTERMSIG(exitstatus) log.error('subprocess exited with signal %d' % (sig,)) if sig == signal.SIGINT: # control-C raise KeyboardInterrupt else: exitcode = exitstatus log.info("success!") except (CompileError, LinkError): log.info("failure.") self._clean() return exitcode, output class GrabStdout(object): def __init__(self): self.sys_stdout = sys.stdout self.data = '' sys.stdout = self def write (self, data): self.sys_stdout.write(data) self.data += data def flush (self): self.sys_stdout.flush() def restore(self): sys.stdout = self.sys_stdout
from __future__ import division, absolute_import, print_function import sys import warnings import itertools import operator import platform import pytest import numpy as np from numpy.testing import ( assert_, assert_equal, assert_raises, assert_almost_equal, assert_array_equal, IS_PYPY, suppress_warnings, _gen_alignment_data, assert_warns ) types = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc, np.int_, np.uint, np.longlong, np.ulonglong, np.single, np.double, np.longdouble, np.csingle, np.cdouble, np.clongdouble] floating_types = np.floating.__subclasses__() complex_floating_types = np.complexfloating.__subclasses__() # This compares scalarmath against ufuncs. class TestTypes(object): def test_types(self): for atype in types: a = atype(1) assert_(a == 1, "error with %r: got %r" % (atype, a)) def test_type_add(self): # list of types for k, atype in enumerate(types): a_scalar = atype(3) a_array = np.array([3], dtype=atype) for l, btype in enumerate(types): b_scalar = btype(1) b_array = np.array([1], dtype=btype) c_scalar = a_scalar + b_scalar c_array = a_array + b_array # It was comparing the type numbers, but the new ufunc # function-finding mechanism finds the lowest function # to which both inputs can be cast - which produces 'l' # when you do 'q' + 'b'. The old function finding mechanism # skipped ahead based on the first argument, but that # does not produce properly symmetric results... assert_equal(c_scalar.dtype, c_array.dtype, "error with types (%d/'%c' + %d/'%c')" % (k, np.dtype(atype).char, l, np.dtype(btype).char)) def test_type_create(self): for k, atype in enumerate(types): a = np.array([1, 2, 3], atype) b = atype([1, 2, 3]) assert_equal(a, b) def test_leak(self): # test leak of scalar objects # a leak would show up in valgrind as still-reachable of ~2.6MB for i in range(200000): np.add(1, 1) class TestBaseMath(object): def test_blocked(self): # test alignments offsets for simd instructions # alignments for vz + 2 * (vs - 1) + 1 for dt, sz in [(np.float32, 11), (np.float64, 7), (np.int32, 11)]: for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt, type='binary', max_size=sz): exp1 = np.ones_like(inp1) inp1[...] = np.ones_like(inp1) inp2[...] = np.zeros_like(inp2) assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg) assert_almost_equal(np.add(inp1, 2), exp1 + 2, err_msg=msg) assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg) np.add(inp1, inp2, out=out) assert_almost_equal(out, exp1, err_msg=msg) inp2[...] += np.arange(inp2.size, dtype=dt) + 1 assert_almost_equal(np.square(inp2), np.multiply(inp2, inp2), err_msg=msg) # skip true divide for ints if dt != np.int32 or (sys.version_info.major < 3 and not sys.py3kwarning): assert_almost_equal(np.reciprocal(inp2), np.divide(1, inp2), err_msg=msg) inp1[...] = np.ones_like(inp1) np.add(inp1, 2, out=out) assert_almost_equal(out, exp1 + 2, err_msg=msg) inp2[...] = np.ones_like(inp2) np.add(2, inp2, out=out) assert_almost_equal(out, exp1 + 2, err_msg=msg) def test_lower_align(self): # check data that is not aligned to element size # i.e doubles are aligned to 4 bytes on i386 d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) o = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) assert_almost_equal(d + d, d * 2) np.add(d, d, out=o) np.add(np.ones_like(d), d, out=o) np.add(d, np.ones_like(d), out=o) np.add(np.ones_like(d), d) np.add(d, np.ones_like(d)) class TestPower(object): def test_small_types(self): for t in [np.int8, np.int16, np.float16]: a = t(3) b = a ** 4 assert_(b == 81, "error with %r: got %r" % (t, b)) def test_large_types(self): for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]: a = t(51) b = a ** 4 msg = "error with %r: got %r" % (t, b) if np.issubdtype(t, np.integer): assert_(b == 6765201, msg) else: assert_almost_equal(b, 6765201, err_msg=msg) def test_integers_to_negative_integer_power(self): # Note that the combination of uint64 with a signed integer # has common type np.float64. The other combinations should all # raise a ValueError for integer ** negative integer. exp = [np.array(-1, dt)[()] for dt in 'bhilq'] # 1 ** -1 possible special case base = [np.array(1, dt)[()] for dt in 'bhilqBHILQ'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, 1.) # -1 ** -1 possible special case base = [np.array(-1, dt)[()] for dt in 'bhilq'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, -1.) # 2 ** -1 perhaps generic base = [np.array(2, dt)[()] for dt in 'bhilqBHILQ'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, .5) def test_mixed_types(self): typelist = [np.int8, np.int16, np.float16, np.float32, np.float64, np.int8, np.int16, np.int32, np.int64] for t1 in typelist: for t2 in typelist: a = t1(3) b = t2(2) result = a**b msg = ("error with %r and %r:" "got %r, expected %r") % (t1, t2, result, 9) if np.issubdtype(np.dtype(result), np.integer): assert_(result == 9, msg) else: assert_almost_equal(result, 9, err_msg=msg) def test_modular_power(self): # modular power is not implemented, so ensure it errors a = 5 b = 4 c = 10 expected = pow(a, b, c) # noqa: F841 for t in (np.int32, np.float32, np.complex64): # note that 3-operand power only dispatches on the first argument assert_raises(TypeError, operator.pow, t(a), b, c) assert_raises(TypeError, operator.pow, np.array(t(a)), b, c) def floordiv_and_mod(x, y): return (x // y, x % y) def _signs(dt): if dt in np.typecodes['UnsignedInteger']: return (+1,) else: return (+1, -1) class TestModulus(object): def test_modulus_basic(self): dt = np.typecodes['AllInteger'] + np.typecodes['Float'] for op in [floordiv_and_mod, divmod]: for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product(_signs(dt1), _signs(dt2)): fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (op.__name__, dt1, dt2, sg1, sg2) a = np.array(sg1*71, dtype=dt1)[()] b = np.array(sg2*19, dtype=dt2)[()] div, rem = op(a, b) assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg) def test_float_modulus_exact(self): # test that float results are exact for small integers. This also # holds for the same integers scaled by powers of two. nlst = list(range(-127, 0)) plst = list(range(1, 128)) dividend = nlst + [0] + plst divisor = nlst + plst arg = list(itertools.product(dividend, divisor)) tgt = list(divmod(*t) for t in arg) a, b = np.array(arg, dtype=int).T # convert exact integer results from Python to float so that # signed zero can be used, it is checked. tgtdiv, tgtrem = np.array(tgt, dtype=float).T tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv) tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem) for op in [floordiv_and_mod, divmod]: for dt in np.typecodes['Float']: msg = 'op: %s, dtype: %s' % (op.__name__, dt) fa = a.astype(dt) fb = b.astype(dt) # use list comprehension so a_ and b_ are scalars div, rem = zip(*[op(a_, b_) for a_, b_ in zip(fa, fb)]) assert_equal(div, tgtdiv, err_msg=msg) assert_equal(rem, tgtrem, err_msg=msg) def test_float_modulus_roundoff(self): # gh-6127 dt = np.typecodes['Float'] for op in [floordiv_and_mod, divmod]: for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product((+1, -1), (+1, -1)): fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (op.__name__, dt1, dt2, sg1, sg2) a = np.array(sg1*78*6e-8, dtype=dt1)[()] b = np.array(sg2*6e-8, dtype=dt2)[()] div, rem = op(a, b) # Equal assertion should hold when fmod is used assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg) def test_float_modulus_corner_cases(self): # Check remainder magnitude. for dt in np.typecodes['Float']: b = np.array(1.0, dtype=dt) a = np.nextafter(np.array(0.0, dtype=dt), -b) rem = operator.mod(a, b) assert_(rem <= b, 'dt: %s' % dt) rem = operator.mod(-a, -b) assert_(rem >= -b, 'dt: %s' % dt) # Check nans, inf with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in remainder") for dt in np.typecodes['Float']: fone = np.array(1.0, dtype=dt) fzer = np.array(0.0, dtype=dt) finf = np.array(np.inf, dtype=dt) fnan = np.array(np.nan, dtype=dt) rem = operator.mod(fone, fzer) assert_(np.isnan(rem), 'dt: %s' % dt) # MSVC 2008 returns NaN here, so disable the check. #rem = operator.mod(fone, finf) #assert_(rem == fone, 'dt: %s' % dt) rem = operator.mod(fone, fnan) assert_(np.isnan(rem), 'dt: %s' % dt) rem = operator.mod(finf, fone) assert_(np.isnan(rem), 'dt: %s' % dt) class TestComplexDivision(object): def test_zero_division(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: a = t(0.0) b = t(1.0) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.nan)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.nan)) assert_(np.isnan(b/a)) b = t(0.) assert_(np.isnan(b/a)) def test_signed_zeros(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = ( (( 0.0,-1.0), ( 0.0, 1.0), (-1.0,-0.0)), (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), (( 0.0,-1.0), (-0.0,-1.0), ( 1.0, 0.0)), (( 0.0,-1.0), (-0.0, 1.0), (-1.0, 0.0)), (( 0.0, 1.0), ( 0.0,-1.0), (-1.0, 0.0)), (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), ((-0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), ((-0.0, 1.0), ( 0.0,-1.0), (-1.0,-0.0)) ) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1]) def test_branches(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = list() # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by else condition as neither are == 0 data.append((( 2.0, 1.0), ( 2.0, 1.0), (1.0, 0.0))) # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by if condition as both are == 0 # is performed in test_zero_division(), so this is skipped # trigger else if branch: real(fabs(denom)) < imag(fabs(denom)) data.append((( 1.0, 2.0), ( 1.0, 2.0), (1.0, 0.0))) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1]) class TestConversion(object): def test_int_from_long(self): l = [1e6, 1e12, 1e18, -1e6, -1e12, -1e18] li = [10**6, 10**12, 10**18, -10**6, -10**12, -10**18] for T in [None, np.float64, np.int64]: a = np.array(l, dtype=T) assert_equal([int(_m) for _m in a], li) a = np.array(l[:3], dtype=np.uint64) assert_equal([int(_m) for _m in a], li[:3]) def test_iinfo_long_values(self): for code in 'bBhH': res = np.array(np.iinfo(code).max + 1, dtype=code) tgt = np.iinfo(code).min assert_(res == tgt) for code in np.typecodes['AllInteger']: res = np.array(np.iinfo(code).max, dtype=code) tgt = np.iinfo(code).max assert_(res == tgt) for code in np.typecodes['AllInteger']: res = np.typeDict[code](np.iinfo(code).max) tgt = np.iinfo(code).max assert_(res == tgt) def test_int_raise_behaviour(self): def overflow_error_func(dtype): np.typeDict[dtype](np.iinfo(dtype).max + 1) for code in 'lLqQ': assert_raises(OverflowError, overflow_error_func, code) def test_int_from_infinite_longdouble(self): # gh-627 x = np.longdouble(np.inf) assert_raises(OverflowError, int, x) with suppress_warnings() as sup: sup.record(np.ComplexWarning) x = np.clongdouble(np.inf) assert_raises(OverflowError, int, x) assert_equal(len(sup.log), 1) @pytest.mark.skipif(not IS_PYPY, reason="Test is PyPy only (gh-9972)") def test_int_from_infinite_longdouble___int__(self): x = np.longdouble(np.inf) assert_raises(OverflowError, x.__int__) with suppress_warnings() as sup: sup.record(np.ComplexWarning) x = np.clongdouble(np.inf) assert_raises(OverflowError, x.__int__) assert_equal(len(sup.log), 1) @pytest.mark.skipif(np.finfo(np.double) == np.finfo(np.longdouble), reason="long double is same as double") @pytest.mark.skipif(platform.machine().startswith("ppc"), reason="IBM double double") def test_int_from_huge_longdouble(self): # Produce a longdouble that would overflow a double, # use exponent that avoids bug in Darwin pow function. exp = np.finfo(np.double).maxexp - 1 huge_ld = 2 * 1234 * np.longdouble(2) ** exp huge_i = 2 * 1234 * 2 ** exp assert_(huge_ld != np.inf) assert_equal(int(huge_ld), huge_i) def test_int_from_longdouble(self): x = np.longdouble(1.5) assert_equal(int(x), 1) x = np.longdouble(-10.5) assert_equal(int(x), -10) def test_numpy_scalar_relational_operators(self): # All integer for dt1 in np.typecodes['AllInteger']: assert_(1 > np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not 1 < np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,)) for dt2 in np.typecodes['AllInteger']: assert_(np.array(1, dtype=dt1)[()] > np.array(0, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(0, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) #Unsigned integers for dt1 in 'BHILQP': assert_(-1 < np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not -1 > np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(-1 != np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) #unsigned vs signed for dt2 in 'bhilqp': assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(np.array(1, dtype=dt1)[()] != np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) #Signed integers and floats for dt1 in 'bhlqp' + np.typecodes['Float']: assert_(1 > np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not 1 < np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(-1 == np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) for dt2 in 'bhlqp' + np.typecodes['Float']: assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(np.array(-1, dtype=dt1)[()] == np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) def test_scalar_comparison_to_none(self): # Scalars should just return False and not give a warnings. # The comparisons are flagged by pep8, ignore that. with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', FutureWarning) assert_(not np.float32(1) == None) assert_(not np.str_('test') == None) # This is dubious (see below): assert_(not np.datetime64('NaT') == None) assert_(np.float32(1) != None) assert_(np.str_('test') != None) # This is dubious (see below): assert_(np.datetime64('NaT') != None) assert_(len(w) == 0) # For documentation purposes, this is why the datetime is dubious. # At the time of deprecation this was no behaviour change, but # it has to be considered when the deprecations are done. assert_(np.equal(np.datetime64('NaT'), None)) #class TestRepr(object): # def test_repr(self): # for t in types: # val = t(1197346475.0137341) # val_repr = repr(val) # val2 = eval(val_repr) # assert_equal( val, val2 ) class TestRepr(object): def _test_type_repr(self, t): finfo = np.finfo(t) last_fraction_bit_idx = finfo.nexp + finfo.nmant last_exponent_bit_idx = finfo.nexp storage_bytes = np.dtype(t).itemsize*8 # could add some more types to the list below for which in ['small denorm', 'small norm']: # Values from https://en.wikipedia.org/wiki/IEEE_754 constr = np.array([0x00]*storage_bytes, dtype=np.uint8) if which == 'small denorm': byte = last_fraction_bit_idx // 8 bytebit = 7-(last_fraction_bit_idx % 8) constr[byte] = 1 << bytebit elif which == 'small norm': byte = last_exponent_bit_idx // 8 bytebit = 7-(last_exponent_bit_idx % 8) constr[byte] = 1 << bytebit else: raise ValueError('hmm') val = constr.view(t)[0] val_repr = repr(val) val2 = t(eval(val_repr)) if not (val2 == 0 and val < 1e-100): assert_equal(val, val2) def test_float_repr(self): # long double test cannot work, because eval goes through a python # float for t in [np.float32, np.float64]: self._test_type_repr(t) if not IS_PYPY: # sys.getsizeof() is not valid on PyPy class TestSizeOf(object): def test_equal_nbytes(self): for type in types: x = type(0) assert_(sys.getsizeof(x) > x.nbytes) def test_error(self): d = np.float32() assert_raises(TypeError, d.__sizeof__, "a") class TestMultiply(object): def test_seq_repeat(self): # Test that basic sequences get repeated when multiplied with # numpy integers. And errors are raised when multiplied with others. # Some of this behaviour may be controversial and could be open for # change. accepted_types = set(np.typecodes["AllInteger"]) deprecated_types = {'?'} forbidden_types = ( set(np.typecodes["All"]) - accepted_types - deprecated_types) forbidden_types -= {'V'} # can't default-construct void scalars for seq_type in (list, tuple): seq = seq_type([1, 2, 3]) for numpy_type in accepted_types: i = np.dtype(numpy_type).type(2) assert_equal(seq * i, seq * int(i)) assert_equal(i * seq, int(i) * seq) for numpy_type in deprecated_types: i = np.dtype(numpy_type).type() assert_equal( assert_warns(DeprecationWarning, operator.mul, seq, i), seq * int(i)) assert_equal( assert_warns(DeprecationWarning, operator.mul, i, seq), int(i) * seq) for numpy_type in forbidden_types: i = np.dtype(numpy_type).type() assert_raises(TypeError, operator.mul, seq, i) assert_raises(TypeError, operator.mul, i, seq) def test_no_seq_repeat_basic_array_like(self): # Test that an array-like which does not know how to be multiplied # does not attempt sequence repeat (raise TypeError). # See also gh-7428. class ArrayLike(object): def __init__(self, arr): self.arr = arr def __array__(self): return self.arr # Test for simple ArrayLike above and memoryviews (original report) for arr_like in (ArrayLike(np.ones(3)), memoryview(np.ones(3))): assert_array_equal(arr_like * np.float32(3.), np.full(3, 3.)) assert_array_equal(np.float32(3.) * arr_like, np.full(3, 3.)) assert_array_equal(arr_like * np.int_(3), np.full(3, 3)) assert_array_equal(np.int_(3) * arr_like, np.full(3, 3)) class TestNegative(object): def test_exceptions(self): a = np.ones((), dtype=np.bool_)[()] assert_raises(TypeError, operator.neg, a) def test_result(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] with suppress_warnings() as sup: sup.filter(RuntimeWarning) for dt in types: a = np.ones((), dtype=dt)[()] assert_equal(operator.neg(a) + a, 0) class TestSubtract(object): def test_exceptions(self): a = np.ones((), dtype=np.bool_)[()] assert_raises(TypeError, operator.sub, a, a) def test_result(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] with suppress_warnings() as sup: sup.filter(RuntimeWarning) for dt in types: a = np.ones((), dtype=dt)[()] assert_equal(operator.sub(a, a), 0) class TestAbs(object): def _test_abs_func(self, absfunc): for tp in floating_types + complex_floating_types: x = tp(-1.5) assert_equal(absfunc(x), 1.5) x = tp(0.0) res = absfunc(x) # assert_equal() checks zero signedness assert_equal(res, 0.0) x = tp(-0.0) res = absfunc(x) assert_equal(res, 0.0) x = tp(np.finfo(tp).max) assert_equal(absfunc(x), x.real) x = tp(np.finfo(tp).tiny) assert_equal(absfunc(x), x.real) x = tp(np.finfo(tp).min) assert_equal(absfunc(x), -x.real) def test_builtin_abs(self): self._test_abs_func(abs) def test_numpy_abs(self): self._test_abs_func(np.abs) class TestBitShifts(object): @pytest.mark.parametrize('type_code', np.typecodes['AllInteger']) @pytest.mark.parametrize('op', [operator.rshift, operator.lshift], ids=['>>', '<<']) def test_shift_all_bits(self, type_code, op): """ Shifts where the shift amount is the width of the type or wider """ # gh-2449 dt = np.dtype(type_code) nbits = dt.itemsize * 8 for val in [5, -5]: for shift in [nbits, nbits + 4]: val_scl = dt.type(val) shift_scl = dt.type(shift) res_scl = op(val_scl, shift_scl) if val_scl < 0 and op is operator.rshift: # sign bit is preserved assert_equal(res_scl, -1) else: assert_equal(res_scl, 0) # Result on scalars should be the same as on arrays val_arr = np.array([val]*32, dtype=dt) shift_arr = np.array([shift]*32, dtype=dt) res_arr = op(val_arr, shift_arr) assert_equal(res_arr, res_scl)
MSeifert04/numpy
numpy/core/tests/test_scalarmath.py
numpy/distutils/command/config.py
from __future__ import division, absolute_import, print_function import os import re import sys import subprocess from numpy.distutils.fcompiler import FCompiler from numpy.distutils.exec_command import find_executable from numpy.distutils.misc_util import make_temp_file from distutils import log compilers = ['IBMFCompiler'] class IBMFCompiler(FCompiler): compiler_type = 'ibm' description = 'IBM XL Fortran Compiler' version_pattern = r'(xlf\(1\)\s*|)IBM XL Fortran ((Advanced Edition |)Version |Enterprise Edition V|for AIX, V)(?P<version>[^\s*]*)' #IBM XL Fortran Enterprise Edition V10.1 for AIX \nVersion: 10.01.0000.0004 executables = { 'version_cmd' : ["<F77>", "-qversion"], 'compiler_f77' : ["xlf"], 'compiler_fix' : ["xlf90", "-qfixed"], 'compiler_f90' : ["xlf90"], 'linker_so' : ["xlf95"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } def get_version(self,*args,**kwds): version = FCompiler.get_version(self,*args,**kwds) if version is None and sys.platform.startswith('aix'): # use lslpp to find out xlf version lslpp = find_executable('lslpp') xlf = find_executable('xlf') if os.path.exists(xlf) and os.path.exists(lslpp): try: o = subprocess.check_output([lslpp, '-Lc', 'xlfcmp']) except (OSError, subprocess.CalledProcessError): pass else: m = re.search(r'xlfcmp:(?P<version>\d+([.]\d+)+)', o) if m: version = m.group('version') xlf_dir = '/etc/opt/ibmcmp/xlf' if version is None and os.path.isdir(xlf_dir): # linux: # If the output of xlf does not contain version info # (that's the case with xlf 8.1, for instance) then # let's try another method: l = sorted(os.listdir(xlf_dir)) l.reverse() l = [d for d in l if os.path.isfile(os.path.join(xlf_dir, d, 'xlf.cfg'))] if l: from distutils.version import LooseVersion self.version = version = LooseVersion(l[0]) return version def get_flags(self): return ['-qextname'] def get_flags_debug(self): return ['-g'] def get_flags_linker_so(self): opt = [] if sys.platform=='darwin': opt.append('-Wl,-bundle,-flat_namespace,-undefined,suppress') else: opt.append('-bshared') version = self.get_version(ok_status=[0, 40]) if version is not None: if sys.platform.startswith('aix'): xlf_cfg = '/etc/xlf.cfg' else: xlf_cfg = '/etc/opt/ibmcmp/xlf/%s/xlf.cfg' % version fo, new_cfg = make_temp_file(suffix='_xlf.cfg') log.info('Creating '+new_cfg) with open(xlf_cfg, 'r') as fi: crt1_match = re.compile(r'\s*crt\s*[=]\s*(?P<path>.*)/crt1.o').match for line in fi: m = crt1_match(line) if m: fo.write('crt = %s/bundle1.o\n' % (m.group('path'))) else: fo.write(line) fo.close() opt.append('-F'+new_cfg) return opt def get_flags_opt(self): return ['-O3'] if __name__ == '__main__': from numpy.distutils import customized_fcompiler log.set_verbosity(2) print(customized_fcompiler(compiler='ibm').get_version())
from __future__ import division, absolute_import, print_function import sys import warnings import itertools import operator import platform import pytest import numpy as np from numpy.testing import ( assert_, assert_equal, assert_raises, assert_almost_equal, assert_array_equal, IS_PYPY, suppress_warnings, _gen_alignment_data, assert_warns ) types = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc, np.int_, np.uint, np.longlong, np.ulonglong, np.single, np.double, np.longdouble, np.csingle, np.cdouble, np.clongdouble] floating_types = np.floating.__subclasses__() complex_floating_types = np.complexfloating.__subclasses__() # This compares scalarmath against ufuncs. class TestTypes(object): def test_types(self): for atype in types: a = atype(1) assert_(a == 1, "error with %r: got %r" % (atype, a)) def test_type_add(self): # list of types for k, atype in enumerate(types): a_scalar = atype(3) a_array = np.array([3], dtype=atype) for l, btype in enumerate(types): b_scalar = btype(1) b_array = np.array([1], dtype=btype) c_scalar = a_scalar + b_scalar c_array = a_array + b_array # It was comparing the type numbers, but the new ufunc # function-finding mechanism finds the lowest function # to which both inputs can be cast - which produces 'l' # when you do 'q' + 'b'. The old function finding mechanism # skipped ahead based on the first argument, but that # does not produce properly symmetric results... assert_equal(c_scalar.dtype, c_array.dtype, "error with types (%d/'%c' + %d/'%c')" % (k, np.dtype(atype).char, l, np.dtype(btype).char)) def test_type_create(self): for k, atype in enumerate(types): a = np.array([1, 2, 3], atype) b = atype([1, 2, 3]) assert_equal(a, b) def test_leak(self): # test leak of scalar objects # a leak would show up in valgrind as still-reachable of ~2.6MB for i in range(200000): np.add(1, 1) class TestBaseMath(object): def test_blocked(self): # test alignments offsets for simd instructions # alignments for vz + 2 * (vs - 1) + 1 for dt, sz in [(np.float32, 11), (np.float64, 7), (np.int32, 11)]: for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt, type='binary', max_size=sz): exp1 = np.ones_like(inp1) inp1[...] = np.ones_like(inp1) inp2[...] = np.zeros_like(inp2) assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg) assert_almost_equal(np.add(inp1, 2), exp1 + 2, err_msg=msg) assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg) np.add(inp1, inp2, out=out) assert_almost_equal(out, exp1, err_msg=msg) inp2[...] += np.arange(inp2.size, dtype=dt) + 1 assert_almost_equal(np.square(inp2), np.multiply(inp2, inp2), err_msg=msg) # skip true divide for ints if dt != np.int32 or (sys.version_info.major < 3 and not sys.py3kwarning): assert_almost_equal(np.reciprocal(inp2), np.divide(1, inp2), err_msg=msg) inp1[...] = np.ones_like(inp1) np.add(inp1, 2, out=out) assert_almost_equal(out, exp1 + 2, err_msg=msg) inp2[...] = np.ones_like(inp2) np.add(2, inp2, out=out) assert_almost_equal(out, exp1 + 2, err_msg=msg) def test_lower_align(self): # check data that is not aligned to element size # i.e doubles are aligned to 4 bytes on i386 d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) o = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) assert_almost_equal(d + d, d * 2) np.add(d, d, out=o) np.add(np.ones_like(d), d, out=o) np.add(d, np.ones_like(d), out=o) np.add(np.ones_like(d), d) np.add(d, np.ones_like(d)) class TestPower(object): def test_small_types(self): for t in [np.int8, np.int16, np.float16]: a = t(3) b = a ** 4 assert_(b == 81, "error with %r: got %r" % (t, b)) def test_large_types(self): for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]: a = t(51) b = a ** 4 msg = "error with %r: got %r" % (t, b) if np.issubdtype(t, np.integer): assert_(b == 6765201, msg) else: assert_almost_equal(b, 6765201, err_msg=msg) def test_integers_to_negative_integer_power(self): # Note that the combination of uint64 with a signed integer # has common type np.float64. The other combinations should all # raise a ValueError for integer ** negative integer. exp = [np.array(-1, dt)[()] for dt in 'bhilq'] # 1 ** -1 possible special case base = [np.array(1, dt)[()] for dt in 'bhilqBHILQ'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, 1.) # -1 ** -1 possible special case base = [np.array(-1, dt)[()] for dt in 'bhilq'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, -1.) # 2 ** -1 perhaps generic base = [np.array(2, dt)[()] for dt in 'bhilqBHILQ'] for i1, i2 in itertools.product(base, exp): if i1.dtype != np.uint64: assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, .5) def test_mixed_types(self): typelist = [np.int8, np.int16, np.float16, np.float32, np.float64, np.int8, np.int16, np.int32, np.int64] for t1 in typelist: for t2 in typelist: a = t1(3) b = t2(2) result = a**b msg = ("error with %r and %r:" "got %r, expected %r") % (t1, t2, result, 9) if np.issubdtype(np.dtype(result), np.integer): assert_(result == 9, msg) else: assert_almost_equal(result, 9, err_msg=msg) def test_modular_power(self): # modular power is not implemented, so ensure it errors a = 5 b = 4 c = 10 expected = pow(a, b, c) # noqa: F841 for t in (np.int32, np.float32, np.complex64): # note that 3-operand power only dispatches on the first argument assert_raises(TypeError, operator.pow, t(a), b, c) assert_raises(TypeError, operator.pow, np.array(t(a)), b, c) def floordiv_and_mod(x, y): return (x // y, x % y) def _signs(dt): if dt in np.typecodes['UnsignedInteger']: return (+1,) else: return (+1, -1) class TestModulus(object): def test_modulus_basic(self): dt = np.typecodes['AllInteger'] + np.typecodes['Float'] for op in [floordiv_and_mod, divmod]: for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product(_signs(dt1), _signs(dt2)): fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (op.__name__, dt1, dt2, sg1, sg2) a = np.array(sg1*71, dtype=dt1)[()] b = np.array(sg2*19, dtype=dt2)[()] div, rem = op(a, b) assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg) def test_float_modulus_exact(self): # test that float results are exact for small integers. This also # holds for the same integers scaled by powers of two. nlst = list(range(-127, 0)) plst = list(range(1, 128)) dividend = nlst + [0] + plst divisor = nlst + plst arg = list(itertools.product(dividend, divisor)) tgt = list(divmod(*t) for t in arg) a, b = np.array(arg, dtype=int).T # convert exact integer results from Python to float so that # signed zero can be used, it is checked. tgtdiv, tgtrem = np.array(tgt, dtype=float).T tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv) tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem) for op in [floordiv_and_mod, divmod]: for dt in np.typecodes['Float']: msg = 'op: %s, dtype: %s' % (op.__name__, dt) fa = a.astype(dt) fb = b.astype(dt) # use list comprehension so a_ and b_ are scalars div, rem = zip(*[op(a_, b_) for a_, b_ in zip(fa, fb)]) assert_equal(div, tgtdiv, err_msg=msg) assert_equal(rem, tgtrem, err_msg=msg) def test_float_modulus_roundoff(self): # gh-6127 dt = np.typecodes['Float'] for op in [floordiv_and_mod, divmod]: for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product((+1, -1), (+1, -1)): fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (op.__name__, dt1, dt2, sg1, sg2) a = np.array(sg1*78*6e-8, dtype=dt1)[()] b = np.array(sg2*6e-8, dtype=dt2)[()] div, rem = op(a, b) # Equal assertion should hold when fmod is used assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg) def test_float_modulus_corner_cases(self): # Check remainder magnitude. for dt in np.typecodes['Float']: b = np.array(1.0, dtype=dt) a = np.nextafter(np.array(0.0, dtype=dt), -b) rem = operator.mod(a, b) assert_(rem <= b, 'dt: %s' % dt) rem = operator.mod(-a, -b) assert_(rem >= -b, 'dt: %s' % dt) # Check nans, inf with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in remainder") for dt in np.typecodes['Float']: fone = np.array(1.0, dtype=dt) fzer = np.array(0.0, dtype=dt) finf = np.array(np.inf, dtype=dt) fnan = np.array(np.nan, dtype=dt) rem = operator.mod(fone, fzer) assert_(np.isnan(rem), 'dt: %s' % dt) # MSVC 2008 returns NaN here, so disable the check. #rem = operator.mod(fone, finf) #assert_(rem == fone, 'dt: %s' % dt) rem = operator.mod(fone, fnan) assert_(np.isnan(rem), 'dt: %s' % dt) rem = operator.mod(finf, fone) assert_(np.isnan(rem), 'dt: %s' % dt) class TestComplexDivision(object): def test_zero_division(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: a = t(0.0) b = t(1.0) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.nan)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.nan)) assert_(np.isnan(b/a)) b = t(0.) assert_(np.isnan(b/a)) def test_signed_zeros(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = ( (( 0.0,-1.0), ( 0.0, 1.0), (-1.0,-0.0)), (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), (( 0.0,-1.0), (-0.0,-1.0), ( 1.0, 0.0)), (( 0.0,-1.0), (-0.0, 1.0), (-1.0, 0.0)), (( 0.0, 1.0), ( 0.0,-1.0), (-1.0, 0.0)), (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), ((-0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), ((-0.0, 1.0), ( 0.0,-1.0), (-1.0,-0.0)) ) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1]) def test_branches(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = list() # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by else condition as neither are == 0 data.append((( 2.0, 1.0), ( 2.0, 1.0), (1.0, 0.0))) # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by if condition as both are == 0 # is performed in test_zero_division(), so this is skipped # trigger else if branch: real(fabs(denom)) < imag(fabs(denom)) data.append((( 1.0, 2.0), ( 1.0, 2.0), (1.0, 0.0))) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1]) class TestConversion(object): def test_int_from_long(self): l = [1e6, 1e12, 1e18, -1e6, -1e12, -1e18] li = [10**6, 10**12, 10**18, -10**6, -10**12, -10**18] for T in [None, np.float64, np.int64]: a = np.array(l, dtype=T) assert_equal([int(_m) for _m in a], li) a = np.array(l[:3], dtype=np.uint64) assert_equal([int(_m) for _m in a], li[:3]) def test_iinfo_long_values(self): for code in 'bBhH': res = np.array(np.iinfo(code).max + 1, dtype=code) tgt = np.iinfo(code).min assert_(res == tgt) for code in np.typecodes['AllInteger']: res = np.array(np.iinfo(code).max, dtype=code) tgt = np.iinfo(code).max assert_(res == tgt) for code in np.typecodes['AllInteger']: res = np.typeDict[code](np.iinfo(code).max) tgt = np.iinfo(code).max assert_(res == tgt) def test_int_raise_behaviour(self): def overflow_error_func(dtype): np.typeDict[dtype](np.iinfo(dtype).max + 1) for code in 'lLqQ': assert_raises(OverflowError, overflow_error_func, code) def test_int_from_infinite_longdouble(self): # gh-627 x = np.longdouble(np.inf) assert_raises(OverflowError, int, x) with suppress_warnings() as sup: sup.record(np.ComplexWarning) x = np.clongdouble(np.inf) assert_raises(OverflowError, int, x) assert_equal(len(sup.log), 1) @pytest.mark.skipif(not IS_PYPY, reason="Test is PyPy only (gh-9972)") def test_int_from_infinite_longdouble___int__(self): x = np.longdouble(np.inf) assert_raises(OverflowError, x.__int__) with suppress_warnings() as sup: sup.record(np.ComplexWarning) x = np.clongdouble(np.inf) assert_raises(OverflowError, x.__int__) assert_equal(len(sup.log), 1) @pytest.mark.skipif(np.finfo(np.double) == np.finfo(np.longdouble), reason="long double is same as double") @pytest.mark.skipif(platform.machine().startswith("ppc"), reason="IBM double double") def test_int_from_huge_longdouble(self): # Produce a longdouble that would overflow a double, # use exponent that avoids bug in Darwin pow function. exp = np.finfo(np.double).maxexp - 1 huge_ld = 2 * 1234 * np.longdouble(2) ** exp huge_i = 2 * 1234 * 2 ** exp assert_(huge_ld != np.inf) assert_equal(int(huge_ld), huge_i) def test_int_from_longdouble(self): x = np.longdouble(1.5) assert_equal(int(x), 1) x = np.longdouble(-10.5) assert_equal(int(x), -10) def test_numpy_scalar_relational_operators(self): # All integer for dt1 in np.typecodes['AllInteger']: assert_(1 > np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not 1 < np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,)) for dt2 in np.typecodes['AllInteger']: assert_(np.array(1, dtype=dt1)[()] > np.array(0, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(0, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) #Unsigned integers for dt1 in 'BHILQP': assert_(-1 < np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not -1 > np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(-1 != np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,)) #unsigned vs signed for dt2 in 'bhilqp': assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(np.array(1, dtype=dt1)[()] != np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) #Signed integers and floats for dt1 in 'bhlqp' + np.typecodes['Float']: assert_(1 > np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(not 1 < np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) assert_(-1 == np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,)) for dt2 in 'bhlqp' + np.typecodes['Float']: assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) assert_(np.array(-1, dtype=dt1)[()] == np.array(-1, dtype=dt2)[()], "type %s and %s failed" % (dt1, dt2)) def test_scalar_comparison_to_none(self): # Scalars should just return False and not give a warnings. # The comparisons are flagged by pep8, ignore that. with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', FutureWarning) assert_(not np.float32(1) == None) assert_(not np.str_('test') == None) # This is dubious (see below): assert_(not np.datetime64('NaT') == None) assert_(np.float32(1) != None) assert_(np.str_('test') != None) # This is dubious (see below): assert_(np.datetime64('NaT') != None) assert_(len(w) == 0) # For documentation purposes, this is why the datetime is dubious. # At the time of deprecation this was no behaviour change, but # it has to be considered when the deprecations are done. assert_(np.equal(np.datetime64('NaT'), None)) #class TestRepr(object): # def test_repr(self): # for t in types: # val = t(1197346475.0137341) # val_repr = repr(val) # val2 = eval(val_repr) # assert_equal( val, val2 ) class TestRepr(object): def _test_type_repr(self, t): finfo = np.finfo(t) last_fraction_bit_idx = finfo.nexp + finfo.nmant last_exponent_bit_idx = finfo.nexp storage_bytes = np.dtype(t).itemsize*8 # could add some more types to the list below for which in ['small denorm', 'small norm']: # Values from https://en.wikipedia.org/wiki/IEEE_754 constr = np.array([0x00]*storage_bytes, dtype=np.uint8) if which == 'small denorm': byte = last_fraction_bit_idx // 8 bytebit = 7-(last_fraction_bit_idx % 8) constr[byte] = 1 << bytebit elif which == 'small norm': byte = last_exponent_bit_idx // 8 bytebit = 7-(last_exponent_bit_idx % 8) constr[byte] = 1 << bytebit else: raise ValueError('hmm') val = constr.view(t)[0] val_repr = repr(val) val2 = t(eval(val_repr)) if not (val2 == 0 and val < 1e-100): assert_equal(val, val2) def test_float_repr(self): # long double test cannot work, because eval goes through a python # float for t in [np.float32, np.float64]: self._test_type_repr(t) if not IS_PYPY: # sys.getsizeof() is not valid on PyPy class TestSizeOf(object): def test_equal_nbytes(self): for type in types: x = type(0) assert_(sys.getsizeof(x) > x.nbytes) def test_error(self): d = np.float32() assert_raises(TypeError, d.__sizeof__, "a") class TestMultiply(object): def test_seq_repeat(self): # Test that basic sequences get repeated when multiplied with # numpy integers. And errors are raised when multiplied with others. # Some of this behaviour may be controversial and could be open for # change. accepted_types = set(np.typecodes["AllInteger"]) deprecated_types = {'?'} forbidden_types = ( set(np.typecodes["All"]) - accepted_types - deprecated_types) forbidden_types -= {'V'} # can't default-construct void scalars for seq_type in (list, tuple): seq = seq_type([1, 2, 3]) for numpy_type in accepted_types: i = np.dtype(numpy_type).type(2) assert_equal(seq * i, seq * int(i)) assert_equal(i * seq, int(i) * seq) for numpy_type in deprecated_types: i = np.dtype(numpy_type).type() assert_equal( assert_warns(DeprecationWarning, operator.mul, seq, i), seq * int(i)) assert_equal( assert_warns(DeprecationWarning, operator.mul, i, seq), int(i) * seq) for numpy_type in forbidden_types: i = np.dtype(numpy_type).type() assert_raises(TypeError, operator.mul, seq, i) assert_raises(TypeError, operator.mul, i, seq) def test_no_seq_repeat_basic_array_like(self): # Test that an array-like which does not know how to be multiplied # does not attempt sequence repeat (raise TypeError). # See also gh-7428. class ArrayLike(object): def __init__(self, arr): self.arr = arr def __array__(self): return self.arr # Test for simple ArrayLike above and memoryviews (original report) for arr_like in (ArrayLike(np.ones(3)), memoryview(np.ones(3))): assert_array_equal(arr_like * np.float32(3.), np.full(3, 3.)) assert_array_equal(np.float32(3.) * arr_like, np.full(3, 3.)) assert_array_equal(arr_like * np.int_(3), np.full(3, 3)) assert_array_equal(np.int_(3) * arr_like, np.full(3, 3)) class TestNegative(object): def test_exceptions(self): a = np.ones((), dtype=np.bool_)[()] assert_raises(TypeError, operator.neg, a) def test_result(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] with suppress_warnings() as sup: sup.filter(RuntimeWarning) for dt in types: a = np.ones((), dtype=dt)[()] assert_equal(operator.neg(a) + a, 0) class TestSubtract(object): def test_exceptions(self): a = np.ones((), dtype=np.bool_)[()] assert_raises(TypeError, operator.sub, a, a) def test_result(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] with suppress_warnings() as sup: sup.filter(RuntimeWarning) for dt in types: a = np.ones((), dtype=dt)[()] assert_equal(operator.sub(a, a), 0) class TestAbs(object): def _test_abs_func(self, absfunc): for tp in floating_types + complex_floating_types: x = tp(-1.5) assert_equal(absfunc(x), 1.5) x = tp(0.0) res = absfunc(x) # assert_equal() checks zero signedness assert_equal(res, 0.0) x = tp(-0.0) res = absfunc(x) assert_equal(res, 0.0) x = tp(np.finfo(tp).max) assert_equal(absfunc(x), x.real) x = tp(np.finfo(tp).tiny) assert_equal(absfunc(x), x.real) x = tp(np.finfo(tp).min) assert_equal(absfunc(x), -x.real) def test_builtin_abs(self): self._test_abs_func(abs) def test_numpy_abs(self): self._test_abs_func(np.abs) class TestBitShifts(object): @pytest.mark.parametrize('type_code', np.typecodes['AllInteger']) @pytest.mark.parametrize('op', [operator.rshift, operator.lshift], ids=['>>', '<<']) def test_shift_all_bits(self, type_code, op): """ Shifts where the shift amount is the width of the type or wider """ # gh-2449 dt = np.dtype(type_code) nbits = dt.itemsize * 8 for val in [5, -5]: for shift in [nbits, nbits + 4]: val_scl = dt.type(val) shift_scl = dt.type(shift) res_scl = op(val_scl, shift_scl) if val_scl < 0 and op is operator.rshift: # sign bit is preserved assert_equal(res_scl, -1) else: assert_equal(res_scl, 0) # Result on scalars should be the same as on arrays val_arr = np.array([val]*32, dtype=dt) shift_arr = np.array([shift]*32, dtype=dt) res_arr = op(val_arr, shift_arr) assert_equal(res_arr, res_scl)
MSeifert04/numpy
numpy/core/tests/test_scalarmath.py
numpy/distutils/fcompiler/ibm.py
"""Support for monitoring juicenet/juicepoint/juicebox based EVSE switches.""" from homeassistant.components.switch import SwitchEntity from .const import DOMAIN, JUICENET_API, JUICENET_COORDINATOR from .entity import JuiceNetDevice async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the JuiceNet switches.""" entities = [] juicenet_data = hass.data[DOMAIN][config_entry.entry_id] api = juicenet_data[JUICENET_API] coordinator = juicenet_data[JUICENET_COORDINATOR] for device in api.devices: entities.append(JuiceNetChargeNowSwitch(device, coordinator)) async_add_entities(entities) class JuiceNetChargeNowSwitch(JuiceNetDevice, SwitchEntity): """Implementation of a JuiceNet switch.""" def __init__(self, device, coordinator): """Initialise the switch.""" super().__init__(device, "charge_now", coordinator) @property def name(self): """Return the name of the device.""" return f"{self.device.name} Charge Now" @property def is_on(self): """Return true if switch is on.""" return self.device.override_time != 0 async def async_turn_on(self, **kwargs): """Charge now.""" await self.device.set_override(True) async def async_turn_off(self, **kwargs): """Don't charge now.""" await self.device.set_override(False)
"""The tests for the notify smtp platform.""" from os import path import re from unittest.mock import patch import pytest from homeassistant import config as hass_config import homeassistant.components.notify as notify from homeassistant.components.smtp import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """Verify we can reload the notify service.""" with patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "recipient": "test@example.com", "sender": "test@example.com", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @pytest.fixture def message(): """Return MockSMTP object with test data.""" mailer = MockSMTP( "localhost", 25, 5, "test@test.com", 1, "testuser", "testpass", ["recip1@example.com", "testrecip@test.com"], "Home Assistant", 0, ) yield mailer HTML = """ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"></head> <body> <div> <h1>Intruder alert at apartment!!</h1> </div> <div> <img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/> </div> </body> </html>""" EMAIL_DATA = [ ( "Test msg", {"images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]}, "Content-Type: multipart/related", ), ] @pytest.mark.parametrize( "message_data, data, content_type", EMAIL_DATA, ids=[ "Tests when sending text message and images.", "Tests when sending text message, HTML Template and images.", "Tests when image does not exist at mentioned location.", "Tests when image type cannot be detected or is of wrong type.", ], ) def test_send_message(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """Verify if we can send simple text message.""" expected = ( '^Content-Type: text/plain; charset="us-ascii"\n' "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 7bit\n" "Subject: Home Assistant\n" "To: recip1@example.com,testrecip@test.com\n" "From: Home Assistant <test@test.com>\n" "X-Mailer: Home Assistant\n" "Date: [^\n]+\n" "Message-Id: <[^@]+@[^>]+>\n" "\n" "Test msg$" ) sample_email = "<mock@mock>" message_data = "Test msg" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data) assert re.search(expected, result)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/juicenet/switch.py
"""Support for Melissa Climate A/C.""" import logging from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( FAN_AUTO, FAN_HIGH, FAN_LOW, FAN_MEDIUM, HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_FAN_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, PRECISION_WHOLE, TEMP_CELSIUS from . import DATA_MELISSA _LOGGER = logging.getLogger(__name__) SUPPORT_FLAGS = SUPPORT_FAN_MODE | SUPPORT_TARGET_TEMPERATURE OP_MODES = [ HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_OFF, ] FAN_MODES = [FAN_AUTO, FAN_HIGH, FAN_MEDIUM, FAN_LOW] async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Iterate through and add all Melissa devices.""" api = hass.data[DATA_MELISSA] devices = (await api.async_fetch_devices()).values() all_devices = [] for device in devices: if device["type"] == "melissa": all_devices.append(MelissaClimate(api, device["serial_number"], device)) async_add_entities(all_devices) class MelissaClimate(ClimateEntity): """Representation of a Melissa Climate device.""" def __init__(self, api, serial_number, init_data): """Initialize the climate device.""" self._name = init_data["name"] self._api = api self._serial_number = serial_number self._data = init_data["controller_log"] self._state = None self._cur_settings = None @property def name(self): """Return the name of the thermostat, if any.""" return self._name @property def fan_mode(self): """Return the current fan mode.""" if self._cur_settings is not None: return self.melissa_fan_to_hass(self._cur_settings[self._api.FAN]) @property def current_temperature(self): """Return the current temperature.""" if self._data: return self._data[self._api.TEMP] @property def current_humidity(self): """Return the current humidity value.""" if self._data: return self._data[self._api.HUMIDITY] @property def target_temperature_step(self): """Return the supported step of target temperature.""" return PRECISION_WHOLE @property def hvac_mode(self): """Return the current operation mode.""" if self._cur_settings is None: return None is_on = self._cur_settings[self._api.STATE] in ( self._api.STATE_ON, self._api.STATE_IDLE, ) if not is_on: return HVAC_MODE_OFF return self.melissa_op_to_hass(self._cur_settings[self._api.MODE]) @property def hvac_modes(self): """Return the list of available operation modes.""" return OP_MODES @property def fan_modes(self): """List of available fan modes.""" return FAN_MODES @property def target_temperature(self): """Return the temperature we try to reach.""" if self._cur_settings is None: return None return self._cur_settings[self._api.TEMP] @property def temperature_unit(self): """Return the unit of measurement which this thermostat uses.""" return TEMP_CELSIUS @property def min_temp(self): """Return the minimum supported temperature for the thermostat.""" return 16 @property def max_temp(self): """Return the maximum supported temperature for the thermostat.""" return 30 @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS async def async_set_temperature(self, **kwargs): """Set new target temperature.""" temp = kwargs.get(ATTR_TEMPERATURE) await self.async_send({self._api.TEMP: temp}) async def async_set_fan_mode(self, fan_mode): """Set fan mode.""" melissa_fan_mode = self.hass_fan_to_melissa(fan_mode) await self.async_send({self._api.FAN: melissa_fan_mode}) async def async_set_hvac_mode(self, hvac_mode): """Set operation mode.""" if hvac_mode == HVAC_MODE_OFF: await self.async_send({self._api.STATE: self._api.STATE_OFF}) return mode = self.hass_mode_to_melissa(hvac_mode) await self.async_send( {self._api.MODE: mode, self._api.STATE: self._api.STATE_ON} ) async def async_send(self, value): """Send action to service.""" try: old_value = self._cur_settings.copy() self._cur_settings.update(value) except AttributeError: old_value = None if not await self._api.async_send( self._serial_number, "melissa", self._cur_settings ): self._cur_settings = old_value async def async_update(self): """Get latest data from Melissa.""" try: self._data = (await self._api.async_status(cached=True))[ self._serial_number ] self._cur_settings = ( await self._api.async_cur_settings(self._serial_number) )["controller"]["_relation"]["command_log"] except KeyError: _LOGGER.warning("Unable to update entity %s", self.entity_id) def melissa_op_to_hass(self, mode): """Translate Melissa modes to hass states.""" if mode == self._api.MODE_HEAT: return HVAC_MODE_HEAT if mode == self._api.MODE_COOL: return HVAC_MODE_COOL if mode == self._api.MODE_DRY: return HVAC_MODE_DRY if mode == self._api.MODE_FAN: return HVAC_MODE_FAN_ONLY _LOGGER.warning("Operation mode %s could not be mapped to hass", mode) return None def melissa_fan_to_hass(self, fan): """Translate Melissa fan modes to hass modes.""" if fan == self._api.FAN_AUTO: return HVAC_MODE_AUTO if fan == self._api.FAN_LOW: return FAN_LOW if fan == self._api.FAN_MEDIUM: return FAN_MEDIUM if fan == self._api.FAN_HIGH: return FAN_HIGH _LOGGER.warning("Fan mode %s could not be mapped to hass", fan) return None def hass_mode_to_melissa(self, mode): """Translate hass states to melissa modes.""" if mode == HVAC_MODE_HEAT: return self._api.MODE_HEAT if mode == HVAC_MODE_COOL: return self._api.MODE_COOL if mode == HVAC_MODE_DRY: return self._api.MODE_DRY if mode == HVAC_MODE_FAN_ONLY: return self._api.MODE_FAN _LOGGER.warning("Melissa have no setting for %s mode", mode) def hass_fan_to_melissa(self, fan): """Translate hass fan modes to melissa modes.""" if fan == HVAC_MODE_AUTO: return self._api.FAN_AUTO if fan == FAN_LOW: return self._api.FAN_LOW if fan == FAN_MEDIUM: return self._api.FAN_MEDIUM if fan == FAN_HIGH: return self._api.FAN_HIGH _LOGGER.warning("Melissa have no setting for %s fan mode", fan)
"""The tests for the notify smtp platform.""" from os import path import re from unittest.mock import patch import pytest from homeassistant import config as hass_config import homeassistant.components.notify as notify from homeassistant.components.smtp import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """Verify we can reload the notify service.""" with patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "recipient": "test@example.com", "sender": "test@example.com", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @pytest.fixture def message(): """Return MockSMTP object with test data.""" mailer = MockSMTP( "localhost", 25, 5, "test@test.com", 1, "testuser", "testpass", ["recip1@example.com", "testrecip@test.com"], "Home Assistant", 0, ) yield mailer HTML = """ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"></head> <body> <div> <h1>Intruder alert at apartment!!</h1> </div> <div> <img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/> </div> </body> </html>""" EMAIL_DATA = [ ( "Test msg", {"images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]}, "Content-Type: multipart/related", ), ] @pytest.mark.parametrize( "message_data, data, content_type", EMAIL_DATA, ids=[ "Tests when sending text message and images.", "Tests when sending text message, HTML Template and images.", "Tests when image does not exist at mentioned location.", "Tests when image type cannot be detected or is of wrong type.", ], ) def test_send_message(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """Verify if we can send simple text message.""" expected = ( '^Content-Type: text/plain; charset="us-ascii"\n' "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 7bit\n" "Subject: Home Assistant\n" "To: recip1@example.com,testrecip@test.com\n" "From: Home Assistant <test@test.com>\n" "X-Mailer: Home Assistant\n" "Date: [^\n]+\n" "Message-Id: <[^@]+@[^>]+>\n" "\n" "Test msg$" ) sample_email = "<mock@mock>" message_data = "Test msg" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data) assert re.search(expected, result)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/melissa/climate.py
"""Support for VELUX KLF 200 devices.""" import logging from pyvlx import PyVLX, PyVLXException import voluptuous as vol from homeassistant.const import CONF_HOST, CONF_PASSWORD, EVENT_HOMEASSISTANT_STOP from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv DOMAIN = "velux" DATA_VELUX = "data_velux" SUPPORTED_DOMAINS = ["cover", "scene"] _LOGGER = logging.getLogger(__name__) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( {vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string} ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Set up the velux component.""" try: hass.data[DATA_VELUX] = VeluxModule(hass, config[DOMAIN]) hass.data[DATA_VELUX].setup() await hass.data[DATA_VELUX].async_start() except PyVLXException as ex: _LOGGER.exception("Can't connect to velux interface: %s", ex) return False for component in SUPPORTED_DOMAINS: hass.async_create_task( discovery.async_load_platform(hass, component, DOMAIN, {}, config) ) return True class VeluxModule: """Abstraction for velux component.""" def __init__(self, hass, domain_config): """Initialize for velux component.""" self.pyvlx = None self._hass = hass self._domain_config = domain_config def setup(self): """Velux component setup.""" async def on_hass_stop(event): """Close connection when hass stops.""" _LOGGER.debug("Velux interface terminated") await self.pyvlx.disconnect() async def async_reboot_gateway(service_call): await self.pyvlx.reboot_gateway() self._hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop) host = self._domain_config.get(CONF_HOST) password = self._domain_config.get(CONF_PASSWORD) self.pyvlx = PyVLX(host=host, password=password) self._hass.services.async_register( DOMAIN, "reboot_gateway", async_reboot_gateway ) async def async_start(self): """Start velux component.""" _LOGGER.debug("Velux interface started") await self.pyvlx.load_scenes() await self.pyvlx.load_nodes()
"""The tests for the notify smtp platform.""" from os import path import re from unittest.mock import patch import pytest from homeassistant import config as hass_config import homeassistant.components.notify as notify from homeassistant.components.smtp import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """Verify we can reload the notify service.""" with patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "recipient": "test@example.com", "sender": "test@example.com", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @pytest.fixture def message(): """Return MockSMTP object with test data.""" mailer = MockSMTP( "localhost", 25, 5, "test@test.com", 1, "testuser", "testpass", ["recip1@example.com", "testrecip@test.com"], "Home Assistant", 0, ) yield mailer HTML = """ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"></head> <body> <div> <h1>Intruder alert at apartment!!</h1> </div> <div> <img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/> </div> </body> </html>""" EMAIL_DATA = [ ( "Test msg", {"images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]}, "Content-Type: multipart/related", ), ] @pytest.mark.parametrize( "message_data, data, content_type", EMAIL_DATA, ids=[ "Tests when sending text message and images.", "Tests when sending text message, HTML Template and images.", "Tests when image does not exist at mentioned location.", "Tests when image type cannot be detected or is of wrong type.", ], ) def test_send_message(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """Verify if we can send simple text message.""" expected = ( '^Content-Type: text/plain; charset="us-ascii"\n' "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 7bit\n" "Subject: Home Assistant\n" "To: recip1@example.com,testrecip@test.com\n" "From: Home Assistant <test@test.com>\n" "X-Mailer: Home Assistant\n" "Date: [^\n]+\n" "Message-Id: <[^@]+@[^>]+>\n" "\n" "Test msg$" ) sample_email = "<mock@mock>" message_data = "Test msg" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data) assert re.search(expected, result)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/velux/__init__.py
"""Insteon base entity.""" import functools import logging from pyinsteon import devices from homeassistant.core import callback from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, ) from homeassistant.helpers.entity import Entity from .const import ( DOMAIN, SIGNAL_ADD_DEFAULT_LINKS, SIGNAL_LOAD_ALDB, SIGNAL_PRINT_ALDB, SIGNAL_REMOVE_ENTITY, SIGNAL_SAVE_DEVICES, STATE_NAME_LABEL_MAP, ) from .utils import print_aldb_to_log _LOGGER = logging.getLogger(__name__) class InsteonEntity(Entity): """INSTEON abstract base entity.""" def __init__(self, device, group): """Initialize the INSTEON binary sensor.""" self._insteon_device_group = device.groups[group] self._insteon_device = device def __hash__(self): """Return the hash of the Insteon Entity.""" return hash(self._insteon_device) @property def should_poll(self): """No polling needed.""" return False @property def address(self): """Return the address of the node.""" return str(self._insteon_device.address) @property def group(self): """Return the INSTEON group that the entity responds to.""" return self._insteon_device_group.group @property def unique_id(self) -> str: """Return a unique ID.""" if self._insteon_device_group.group == 0x01: uid = self._insteon_device.id else: uid = f"{self._insteon_device.id}_{self._insteon_device_group.group}" return uid @property def name(self): """Return the name of the node (used for Entity_ID).""" # Set a base description description = self._insteon_device.description if description is None: description = "Unknown Device" # Get an extension label if there is one extension = self._get_label() if extension: extension = f" {extension}" return f"{description} {self._insteon_device.address}{extension}" @property def device_state_attributes(self): """Provide attributes for display on device card.""" return {"insteon_address": self.address, "insteon_group": self.group} @property def device_info(self): """Return device information.""" return { "identifiers": {(DOMAIN, str(self._insteon_device.address))}, "name": f"{self._insteon_device.description} {self._insteon_device.address}", "model": f"{self._insteon_device.model} ({self._insteon_device.cat!r}, 0x{self._insteon_device.subcat:02x})", "sw_version": f"{self._insteon_device.firmware:02x} Engine Version: {self._insteon_device.engine_version}", "manufacturer": "Smart Home", "via_device": (DOMAIN, str(devices.modem.address)), } @callback def async_entity_update(self, name, address, value, group): """Receive notification from transport that new data exists.""" _LOGGER.debug( "Received update for device %s group %d value %s", address, group, value, ) self.async_write_ha_state() async def async_added_to_hass(self): """Register INSTEON update events.""" _LOGGER.debug( "Tracking updates for device %s group %d name %s", self.address, self.group, self._insteon_device_group.name, ) self._insteon_device_group.subscribe(self.async_entity_update) load_signal = f"{self.entity_id}_{SIGNAL_LOAD_ALDB}" self.async_on_remove( async_dispatcher_connect(self.hass, load_signal, self._async_read_aldb) ) print_signal = f"{self.entity_id}_{SIGNAL_PRINT_ALDB}" async_dispatcher_connect(self.hass, print_signal, self._print_aldb) default_links_signal = f"{self.entity_id}_{SIGNAL_ADD_DEFAULT_LINKS}" async_dispatcher_connect( self.hass, default_links_signal, self._async_add_default_links ) remove_signal = f"{self._insteon_device.address.id}_{SIGNAL_REMOVE_ENTITY}" self.async_on_remove( async_dispatcher_connect( self.hass, remove_signal, functools.partial(self.async_remove, force_remove=True), ) ) async def async_will_remove_from_hass(self): """Unsubscribe to INSTEON update events.""" _LOGGER.debug( "Remove tracking updates for device %s group %d name %s", self.address, self.group, self._insteon_device_group.name, ) self._insteon_device_group.unsubscribe(self.async_entity_update) async def _async_read_aldb(self, reload): """Call device load process and print to log.""" await self._insteon_device.aldb.async_load(refresh=reload) self._print_aldb() async_dispatcher_send(self.hass, SIGNAL_SAVE_DEVICES) def _print_aldb(self): """Print the device ALDB to the log file.""" print_aldb_to_log(self._insteon_device.aldb) def _get_label(self): """Get the device label for grouped devices.""" label = "" if len(self._insteon_device.groups) > 1: if self._insteon_device_group.name in STATE_NAME_LABEL_MAP: label = STATE_NAME_LABEL_MAP[self._insteon_device_group.name] else: label = f"Group {self.group:d}" return label async def _async_add_default_links(self): """Add default links between the device and the modem.""" await self._insteon_device.async_add_default_links()
"""The tests for the notify smtp platform.""" from os import path import re from unittest.mock import patch import pytest from homeassistant import config as hass_config import homeassistant.components.notify as notify from homeassistant.components.smtp import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """Verify we can reload the notify service.""" with patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "recipient": "test@example.com", "sender": "test@example.com", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @pytest.fixture def message(): """Return MockSMTP object with test data.""" mailer = MockSMTP( "localhost", 25, 5, "test@test.com", 1, "testuser", "testpass", ["recip1@example.com", "testrecip@test.com"], "Home Assistant", 0, ) yield mailer HTML = """ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"></head> <body> <div> <h1>Intruder alert at apartment!!</h1> </div> <div> <img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/> </div> </body> </html>""" EMAIL_DATA = [ ( "Test msg", {"images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]}, "Content-Type: multipart/related", ), ] @pytest.mark.parametrize( "message_data, data, content_type", EMAIL_DATA, ids=[ "Tests when sending text message and images.", "Tests when sending text message, HTML Template and images.", "Tests when image does not exist at mentioned location.", "Tests when image type cannot be detected or is of wrong type.", ], ) def test_send_message(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """Verify if we can send simple text message.""" expected = ( '^Content-Type: text/plain; charset="us-ascii"\n' "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 7bit\n" "Subject: Home Assistant\n" "To: recip1@example.com,testrecip@test.com\n" "From: Home Assistant <test@test.com>\n" "X-Mailer: Home Assistant\n" "Date: [^\n]+\n" "Message-Id: <[^@]+@[^>]+>\n" "\n" "Test msg$" ) sample_email = "<mock@mock>" message_data = "Test msg" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data) assert re.search(expected, result)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/insteon/insteon_entity.py
"""Config flow to configure the Toon component.""" import logging from typing import Any, Dict, List, Optional from toonapi import Agreement, Toon, ToonError import voluptuous as vol from homeassistant import config_entries from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.config_entry_oauth2_flow import AbstractOAuth2FlowHandler from .const import CONF_AGREEMENT, CONF_AGREEMENT_ID, CONF_MIGRATE, DOMAIN class ToonFlowHandler(AbstractOAuth2FlowHandler, domain=DOMAIN): """Handle a Toon config flow.""" CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_PUSH DOMAIN = DOMAIN VERSION = 2 agreements: Optional[List[Agreement]] = None data: Optional[Dict[str, Any]] = None @property def logger(self) -> logging.Logger: """Return logger.""" return logging.getLogger(__name__) async def async_oauth_create_entry(self, data: Dict[str, Any]) -> Dict[str, Any]: """Test connection and load up agreements.""" self.data = data toon = Toon( token=self.data["token"]["access_token"], session=async_get_clientsession(self.hass), ) try: self.agreements = await toon.agreements() except ToonError: return self.async_abort(reason="connection_error") if not self.agreements: return self.async_abort(reason="no_agreements") return await self.async_step_agreement() async def async_step_import( self, config: Optional[Dict[str, Any]] = None ) -> Dict[str, Any]: """Start a configuration flow based on imported data. This step is merely here to trigger "discovery" when the `toon` integration is listed in the user configuration, or when migrating from the version 1 schema. """ if config is not None and CONF_MIGRATE in config: self.context.update({CONF_MIGRATE: config[CONF_MIGRATE]}) else: await self._async_handle_discovery_without_unique_id() return await self.async_step_user() async def async_step_agreement( self, user_input: Dict[str, Any] = None ) -> Dict[str, Any]: """Select Toon agreement to add.""" if len(self.agreements) == 1: return await self._create_entry(self.agreements[0]) agreements_list = [ f"{agreement.street} {agreement.house_number}, {agreement.city}" for agreement in self.agreements ] if user_input is None: return self.async_show_form( step_id="agreement", data_schema=vol.Schema( {vol.Required(CONF_AGREEMENT): vol.In(agreements_list)} ), ) agreement_index = agreements_list.index(user_input[CONF_AGREEMENT]) return await self._create_entry(self.agreements[agreement_index]) async def _create_entry(self, agreement: Agreement) -> Dict[str, Any]: if CONF_MIGRATE in self.context: await self.hass.config_entries.async_remove(self.context[CONF_MIGRATE]) await self.async_set_unique_id(agreement.agreement_id) self._abort_if_unique_id_configured() self.data[CONF_AGREEMENT_ID] = agreement.agreement_id return self.async_create_entry( title=f"{agreement.street} {agreement.house_number}, {agreement.city}", data=self.data, )
"""The tests for the notify smtp platform.""" from os import path import re from unittest.mock import patch import pytest from homeassistant import config as hass_config import homeassistant.components.notify as notify from homeassistant.components.smtp import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """Verify we can reload the notify service.""" with patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "recipient": "test@example.com", "sender": "test@example.com", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @pytest.fixture def message(): """Return MockSMTP object with test data.""" mailer = MockSMTP( "localhost", 25, 5, "test@test.com", 1, "testuser", "testpass", ["recip1@example.com", "testrecip@test.com"], "Home Assistant", 0, ) yield mailer HTML = """ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"></head> <body> <div> <h1>Intruder alert at apartment!!</h1> </div> <div> <img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/> </div> </body> </html>""" EMAIL_DATA = [ ( "Test msg", {"images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]}, "Content-Type: multipart/related", ), ] @pytest.mark.parametrize( "message_data, data, content_type", EMAIL_DATA, ids=[ "Tests when sending text message and images.", "Tests when sending text message, HTML Template and images.", "Tests when image does not exist at mentioned location.", "Tests when image type cannot be detected or is of wrong type.", ], ) def test_send_message(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """Verify if we can send simple text message.""" expected = ( '^Content-Type: text/plain; charset="us-ascii"\n' "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 7bit\n" "Subject: Home Assistant\n" "To: recip1@example.com,testrecip@test.com\n" "From: Home Assistant <test@test.com>\n" "X-Mailer: Home Assistant\n" "Date: [^\n]+\n" "Message-Id: <[^@]+@[^>]+>\n" "\n" "Test msg$" ) sample_email = "<mock@mock>" message_data = "Test msg" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data) assert re.search(expected, result)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/toon/config_flow.py
"""Support for Bond fans.""" import logging import math from typing import Any, Callable, List, Optional, Tuple from bond_api import Action, BPUPSubscriptions, DeviceType, Direction from homeassistant.components.fan import ( DIRECTION_FORWARD, DIRECTION_REVERSE, SUPPORT_DIRECTION, SUPPORT_SET_SPEED, FanEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import Entity from homeassistant.util.percentage import ( percentage_to_ranged_value, ranged_value_to_percentage, ) from .const import BPUP_SUBS, DOMAIN, HUB from .entity import BondEntity from .utils import BondDevice, BondHub _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], ) -> None: """Set up Bond fan devices.""" data = hass.data[DOMAIN][entry.entry_id] hub: BondHub = data[HUB] bpup_subs: BPUPSubscriptions = data[BPUP_SUBS] fans = [ BondFan(hub, device, bpup_subs) for device in hub.devices if DeviceType.is_fan(device.type) ] async_add_entities(fans, True) class BondFan(BondEntity, FanEntity): """Representation of a Bond fan.""" def __init__(self, hub: BondHub, device: BondDevice, bpup_subs: BPUPSubscriptions): """Create HA entity representing Bond fan.""" super().__init__(hub, device, bpup_subs) self._power: Optional[bool] = None self._speed: Optional[int] = None self._direction: Optional[int] = None def _apply_state(self, state: dict): self._power = state.get("power") self._speed = state.get("speed") self._direction = state.get("direction") @property def supported_features(self) -> int: """Flag supported features.""" features = 0 if self._device.supports_speed(): features |= SUPPORT_SET_SPEED if self._device.supports_direction(): features |= SUPPORT_DIRECTION return features @property def _speed_range(self) -> Tuple[int, int]: """Return the range of speeds.""" return (1, self._device.props.get("max_speed", 3)) @property def percentage(self) -> Optional[str]: """Return the current speed percentage for the fan.""" if not self._speed or not self._power: return 0 return ranged_value_to_percentage(self._speed_range, self._speed) @property def current_direction(self) -> Optional[str]: """Return fan rotation direction.""" direction = None if self._direction == Direction.FORWARD: direction = DIRECTION_FORWARD elif self._direction == Direction.REVERSE: direction = DIRECTION_REVERSE return direction async def async_set_percentage(self, percentage: int) -> None: """Set the desired speed for the fan.""" _LOGGER.debug("async_set_percentage called with percentage %s", percentage) if percentage == 0: await self.async_turn_off() return bond_speed = math.ceil( percentage_to_ranged_value(self._speed_range, percentage) ) _LOGGER.debug( "async_set_percentage converted percentage %s to bond speed %s", percentage, bond_speed, ) await self._hub.bond.action( self._device.device_id, Action.set_speed(bond_speed) ) async def async_turn_on( self, speed: Optional[str] = None, percentage: Optional[int] = None, preset_mode: Optional[str] = None, **kwargs, ) -> None: """Turn on the fan.""" _LOGGER.debug("Fan async_turn_on called with percentage %s", percentage) if percentage is not None: await self.async_set_percentage(percentage) else: await self._hub.bond.action(self._device.device_id, Action.turn_on()) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the fan off.""" await self._hub.bond.action(self._device.device_id, Action.turn_off()) async def async_set_direction(self, direction: str): """Set fan rotation direction.""" bond_direction = ( Direction.REVERSE if direction == DIRECTION_REVERSE else Direction.FORWARD ) await self._hub.bond.action( self._device.device_id, Action.set_direction(bond_direction) )
"""The tests for the notify smtp platform.""" from os import path import re from unittest.mock import patch import pytest from homeassistant import config as hass_config import homeassistant.components.notify as notify from homeassistant.components.smtp import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """Verify we can reload the notify service.""" with patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "recipient": "test@example.com", "sender": "test@example.com", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @pytest.fixture def message(): """Return MockSMTP object with test data.""" mailer = MockSMTP( "localhost", 25, 5, "test@test.com", 1, "testuser", "testpass", ["recip1@example.com", "testrecip@test.com"], "Home Assistant", 0, ) yield mailer HTML = """ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"></head> <body> <div> <h1>Intruder alert at apartment!!</h1> </div> <div> <img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/> </div> </body> </html>""" EMAIL_DATA = [ ( "Test msg", {"images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]}, "Content-Type: multipart/related", ), ] @pytest.mark.parametrize( "message_data, data, content_type", EMAIL_DATA, ids=[ "Tests when sending text message and images.", "Tests when sending text message, HTML Template and images.", "Tests when image does not exist at mentioned location.", "Tests when image type cannot be detected or is of wrong type.", ], ) def test_send_message(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """Verify if we can send simple text message.""" expected = ( '^Content-Type: text/plain; charset="us-ascii"\n' "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 7bit\n" "Subject: Home Assistant\n" "To: recip1@example.com,testrecip@test.com\n" "From: Home Assistant <test@test.com>\n" "X-Mailer: Home Assistant\n" "Date: [^\n]+\n" "Message-Id: <[^@]+@[^>]+>\n" "\n" "Test msg$" ) sample_email = "<mock@mock>" message_data = "Test msg" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data) assert re.search(expected, result)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/bond/fan.py
"""Support for Netgear LTE binary sensors.""" from homeassistant.components.binary_sensor import DOMAIN, BinarySensorEntity from homeassistant.exceptions import PlatformNotReady from . import CONF_MONITORED_CONDITIONS, DATA_KEY, LTEEntity from .sensor_types import BINARY_SENSOR_CLASSES async def async_setup_platform(hass, config, async_add_entities, discovery_info): """Set up Netgear LTE binary sensor devices.""" if discovery_info is None: return modem_data = hass.data[DATA_KEY].get_modem_data(discovery_info) if not modem_data or not modem_data.data: raise PlatformNotReady binary_sensor_conf = discovery_info[DOMAIN] monitored_conditions = binary_sensor_conf[CONF_MONITORED_CONDITIONS] binary_sensors = [] for sensor_type in monitored_conditions: binary_sensors.append(LTEBinarySensor(modem_data, sensor_type)) async_add_entities(binary_sensors) class LTEBinarySensor(LTEEntity, BinarySensorEntity): """Netgear LTE binary sensor entity.""" @property def is_on(self): """Return true if the binary sensor is on.""" return getattr(self.modem_data.data, self.sensor_type) @property def device_class(self): """Return the class of binary sensor.""" return BINARY_SENSOR_CLASSES[self.sensor_type]
"""The tests for the notify smtp platform.""" from os import path import re from unittest.mock import patch import pytest from homeassistant import config as hass_config import homeassistant.components.notify as notify from homeassistant.components.smtp import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """Verify we can reload the notify service.""" with patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "recipient": "test@example.com", "sender": "test@example.com", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @pytest.fixture def message(): """Return MockSMTP object with test data.""" mailer = MockSMTP( "localhost", 25, 5, "test@test.com", 1, "testuser", "testpass", ["recip1@example.com", "testrecip@test.com"], "Home Assistant", 0, ) yield mailer HTML = """ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"></head> <body> <div> <h1>Intruder alert at apartment!!</h1> </div> <div> <img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/> </div> </body> </html>""" EMAIL_DATA = [ ( "Test msg", {"images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]}, "Content-Type: multipart/related", ), ] @pytest.mark.parametrize( "message_data, data, content_type", EMAIL_DATA, ids=[ "Tests when sending text message and images.", "Tests when sending text message, HTML Template and images.", "Tests when image does not exist at mentioned location.", "Tests when image type cannot be detected or is of wrong type.", ], ) def test_send_message(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """Verify if we can send simple text message.""" expected = ( '^Content-Type: text/plain; charset="us-ascii"\n' "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 7bit\n" "Subject: Home Assistant\n" "To: recip1@example.com,testrecip@test.com\n" "From: Home Assistant <test@test.com>\n" "X-Mailer: Home Assistant\n" "Date: [^\n]+\n" "Message-Id: <[^@]+@[^>]+>\n" "\n" "Test msg$" ) sample_email = "<mock@mock>" message_data = "Test msg" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data) assert re.search(expected, result)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/netgear_lte/binary_sensor.py
"""Event parser and human readable log generator.""" from datetime import timedelta from itertools import groupby import json import re import sqlalchemy from sqlalchemy.orm import aliased from sqlalchemy.sql.expression import literal import voluptuous as vol from homeassistant.components.automation import EVENT_AUTOMATION_TRIGGERED from homeassistant.components.history import sqlalchemy_filter_from_include_exclude_conf from homeassistant.components.http import HomeAssistantView from homeassistant.components.recorder.models import ( Events, States, process_timestamp_to_utc_isoformat, ) from homeassistant.components.recorder.util import session_scope from homeassistant.components.script import EVENT_SCRIPT_STARTED from homeassistant.const import ( ATTR_DOMAIN, ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, ATTR_ICON, ATTR_NAME, ATTR_SERVICE, EVENT_CALL_SERVICE, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, EVENT_LOGBOOK_ENTRY, EVENT_STATE_CHANGED, HTTP_BAD_REQUEST, ) from homeassistant.core import DOMAIN as HA_DOMAIN, callback, split_entity_id from homeassistant.exceptions import InvalidEntityFormatError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entityfilter import ( INCLUDE_EXCLUDE_BASE_FILTER_SCHEMA, convert_include_exclude_filter, generate_filter, ) from homeassistant.helpers.integration_platform import ( async_process_integration_platforms, ) from homeassistant.loader import bind_hass import homeassistant.util.dt as dt_util ENTITY_ID_JSON_TEMPLATE = '"entity_id": "{}"' ENTITY_ID_JSON_EXTRACT = re.compile('"entity_id": "([^"]+)"') DOMAIN_JSON_EXTRACT = re.compile('"domain": "([^"]+)"') ICON_JSON_EXTRACT = re.compile('"icon": "([^"]+)"') ATTR_MESSAGE = "message" CONTINUOUS_DOMAINS = ["proximity", "sensor"] DOMAIN = "logbook" GROUP_BY_MINUTES = 15 EMPTY_JSON_OBJECT = "{}" UNIT_OF_MEASUREMENT_JSON = '"unit_of_measurement":' HA_DOMAIN_ENTITY_ID = f"{HA_DOMAIN}." CONFIG_SCHEMA = vol.Schema( {DOMAIN: INCLUDE_EXCLUDE_BASE_FILTER_SCHEMA}, extra=vol.ALLOW_EXTRA ) HOMEASSISTANT_EVENTS = [ EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, ] ALL_EVENT_TYPES_EXCEPT_STATE_CHANGED = [ EVENT_LOGBOOK_ENTRY, EVENT_CALL_SERVICE, *HOMEASSISTANT_EVENTS, ] ALL_EVENT_TYPES = [ EVENT_STATE_CHANGED, *ALL_EVENT_TYPES_EXCEPT_STATE_CHANGED, ] EVENT_COLUMNS = [ Events.event_type, Events.event_data, Events.time_fired, Events.context_id, Events.context_user_id, Events.context_parent_id, ] SCRIPT_AUTOMATION_EVENTS = [EVENT_AUTOMATION_TRIGGERED, EVENT_SCRIPT_STARTED] LOG_MESSAGE_SCHEMA = vol.Schema( { vol.Required(ATTR_NAME): cv.string, vol.Required(ATTR_MESSAGE): cv.template, vol.Optional(ATTR_DOMAIN): cv.slug, vol.Optional(ATTR_ENTITY_ID): cv.entity_id, } ) @bind_hass def log_entry(hass, name, message, domain=None, entity_id=None, context=None): """Add an entry to the logbook.""" hass.add_job(async_log_entry, hass, name, message, domain, entity_id, context) @bind_hass def async_log_entry(hass, name, message, domain=None, entity_id=None, context=None): """Add an entry to the logbook.""" data = {ATTR_NAME: name, ATTR_MESSAGE: message} if domain is not None: data[ATTR_DOMAIN] = domain if entity_id is not None: data[ATTR_ENTITY_ID] = entity_id hass.bus.async_fire(EVENT_LOGBOOK_ENTRY, data, context=context) async def async_setup(hass, config): """Logbook setup.""" hass.data[DOMAIN] = {} @callback def log_message(service): """Handle sending notification message service calls.""" message = service.data[ATTR_MESSAGE] name = service.data[ATTR_NAME] domain = service.data.get(ATTR_DOMAIN) entity_id = service.data.get(ATTR_ENTITY_ID) if entity_id is None and domain is None: # If there is no entity_id or # domain, the event will get filtered # away so we use the "logbook" domain domain = DOMAIN message.hass = hass message = message.async_render(parse_result=False) async_log_entry(hass, name, message, domain, entity_id) hass.components.frontend.async_register_built_in_panel( "logbook", "logbook", "hass:format-list-bulleted-type" ) conf = config.get(DOMAIN, {}) if conf: filters = sqlalchemy_filter_from_include_exclude_conf(conf) entities_filter = convert_include_exclude_filter(conf) else: filters = None entities_filter = None hass.http.register_view(LogbookView(conf, filters, entities_filter)) hass.services.async_register(DOMAIN, "log", log_message, schema=LOG_MESSAGE_SCHEMA) await async_process_integration_platforms(hass, DOMAIN, _process_logbook_platform) return True async def _process_logbook_platform(hass, domain, platform): """Process a logbook platform.""" @callback def _async_describe_event(domain, event_name, describe_callback): """Teach logbook how to describe a new event.""" hass.data[DOMAIN][event_name] = (domain, describe_callback) platform.async_describe_events(hass, _async_describe_event) class LogbookView(HomeAssistantView): """Handle logbook view requests.""" url = "/api/logbook" name = "api:logbook" extra_urls = ["/api/logbook/{datetime}"] def __init__(self, config, filters, entities_filter): """Initialize the logbook view.""" self.config = config self.filters = filters self.entities_filter = entities_filter async def get(self, request, datetime=None): """Retrieve logbook entries.""" if datetime: datetime = dt_util.parse_datetime(datetime) if datetime is None: return self.json_message("Invalid datetime", HTTP_BAD_REQUEST) else: datetime = dt_util.start_of_local_day() period = request.query.get("period") if period is None: period = 1 else: period = int(period) entity_ids = request.query.get("entity") if entity_ids: try: entity_ids = cv.entity_ids(entity_ids) except vol.Invalid: raise InvalidEntityFormatError( f"Invalid entity id(s) encountered: {entity_ids}. " "Format should be <domain>.<object_id>" ) from vol.Invalid end_time = request.query.get("end_time") if end_time is None: start_day = dt_util.as_utc(datetime) - timedelta(days=period - 1) end_day = start_day + timedelta(days=period) else: start_day = datetime end_day = dt_util.parse_datetime(end_time) if end_day is None: return self.json_message("Invalid end_time", HTTP_BAD_REQUEST) hass = request.app["hass"] entity_matches_only = "entity_matches_only" in request.query def json_events(): """Fetch events and generate JSON.""" return self.json( _get_events( hass, start_day, end_day, entity_ids, self.filters, self.entities_filter, entity_matches_only, ) ) return await hass.async_add_executor_job(json_events) def humanify(hass, events, entity_attr_cache, context_lookup): """Generate a converted list of events into Entry objects. Will try to group events if possible: - if 2+ sensor updates in GROUP_BY_MINUTES, show last - if Home Assistant stop and start happen in same minute call it restarted """ external_events = hass.data.get(DOMAIN, {}) # Group events in batches of GROUP_BY_MINUTES for _, g_events in groupby( events, lambda event: event.time_fired_minute // GROUP_BY_MINUTES ): events_batch = list(g_events) # Keep track of last sensor states last_sensor_event = {} # Group HA start/stop events # Maps minute of event to 1: stop, 2: stop + start start_stop_events = {} # Process events for event in events_batch: if event.event_type == EVENT_STATE_CHANGED: if event.domain in CONTINUOUS_DOMAINS: last_sensor_event[event.entity_id] = event elif event.event_type == EVENT_HOMEASSISTANT_STOP: if event.time_fired_minute in start_stop_events: continue start_stop_events[event.time_fired_minute] = 1 elif event.event_type == EVENT_HOMEASSISTANT_START: if event.time_fired_minute not in start_stop_events: continue start_stop_events[event.time_fired_minute] = 2 # Yield entries for event in events_batch: if event.event_type == EVENT_STATE_CHANGED: entity_id = event.entity_id domain = event.domain if ( domain in CONTINUOUS_DOMAINS and event != last_sensor_event[entity_id] ): # Skip all but the last sensor state continue data = { "when": event.time_fired_isoformat, "name": _entity_name_from_event( entity_id, event, entity_attr_cache ), "state": event.state, "entity_id": entity_id, } icon = event.attributes_icon if icon: data["icon"] = icon if event.context_user_id: data["context_user_id"] = event.context_user_id _augment_data_with_context( data, entity_id, event, context_lookup, entity_attr_cache, external_events, ) yield data elif event.event_type in external_events: domain, describe_event = external_events[event.event_type] data = describe_event(event) data["when"] = event.time_fired_isoformat data["domain"] = domain if event.context_user_id: data["context_user_id"] = event.context_user_id _augment_data_with_context( data, data.get(ATTR_ENTITY_ID), event, context_lookup, entity_attr_cache, external_events, ) yield data elif event.event_type == EVENT_HOMEASSISTANT_START: if start_stop_events.get(event.time_fired_minute) == 2: continue yield { "when": event.time_fired_isoformat, "name": "Home Assistant", "message": "started", "domain": HA_DOMAIN, } elif event.event_type == EVENT_HOMEASSISTANT_STOP: if start_stop_events.get(event.time_fired_minute) == 2: action = "restarted" else: action = "stopped" yield { "when": event.time_fired_isoformat, "name": "Home Assistant", "message": action, "domain": HA_DOMAIN, } elif event.event_type == EVENT_LOGBOOK_ENTRY: event_data = event.data domain = event_data.get(ATTR_DOMAIN) entity_id = event_data.get(ATTR_ENTITY_ID) if domain is None and entity_id is not None: try: domain = split_entity_id(str(entity_id))[0] except IndexError: pass data = { "when": event.time_fired_isoformat, "name": event_data.get(ATTR_NAME), "message": event_data.get(ATTR_MESSAGE), "domain": domain, "entity_id": entity_id, } if event.context_user_id: data["context_user_id"] = event.context_user_id _augment_data_with_context( data, entity_id, event, context_lookup, entity_attr_cache, external_events, ) yield data def _get_events( hass, start_day, end_day, entity_ids=None, filters=None, entities_filter=None, entity_matches_only=False, ): """Get events for a period of time.""" entity_attr_cache = EntityAttributeCache(hass) context_lookup = {None: None} def yield_events(query): """Yield Events that are not filtered away.""" for row in query.yield_per(1000): event = LazyEventPartialState(row) context_lookup.setdefault(event.context_id, event) if event.event_type == EVENT_CALL_SERVICE: continue if event.event_type == EVENT_STATE_CHANGED or _keep_event( hass, event, entities_filter ): yield event if entity_ids is not None: entities_filter = generate_filter([], entity_ids, [], []) with session_scope(hass=hass) as session: old_state = aliased(States, name="old_state") if entity_ids is not None: query = _generate_events_query_without_states(session) query = _apply_event_time_filter(query, start_day, end_day) query = _apply_event_types_filter( hass, query, ALL_EVENT_TYPES_EXCEPT_STATE_CHANGED ) if entity_matches_only: # When entity_matches_only is provided, contexts and events that do not # contain the entity_ids are not included in the logbook response. query = _apply_event_entity_id_matchers(query, entity_ids) query = query.union_all( _generate_states_query( session, start_day, end_day, old_state, entity_ids ) ) else: query = _generate_events_query(session) query = _apply_event_time_filter(query, start_day, end_day) query = _apply_events_types_and_states_filter( hass, query, old_state ).filter( (States.last_updated == States.last_changed) | (Events.event_type != EVENT_STATE_CHANGED) ) if filters: query = query.filter( filters.entity_filter() | (Events.event_type != EVENT_STATE_CHANGED) ) query = query.order_by(Events.time_fired) return list( humanify(hass, yield_events(query), entity_attr_cache, context_lookup) ) def _generate_events_query(session): return session.query( *EVENT_COLUMNS, States.state, States.entity_id, States.domain, States.attributes, ) def _generate_events_query_without_states(session): return session.query( *EVENT_COLUMNS, literal(None).label("state"), literal(None).label("entity_id"), literal(None).label("domain"), literal(None).label("attributes"), ) def _generate_states_query(session, start_day, end_day, old_state, entity_ids): return ( _generate_events_query(session) .outerjoin(Events, (States.event_id == Events.event_id)) .outerjoin(old_state, (States.old_state_id == old_state.state_id)) .filter(_missing_state_matcher(old_state)) .filter(_continuous_entity_matcher()) .filter((States.last_updated > start_day) & (States.last_updated < end_day)) .filter( (States.last_updated == States.last_changed) & States.entity_id.in_(entity_ids) ) ) def _apply_events_types_and_states_filter(hass, query, old_state): events_query = ( query.outerjoin(States, (Events.event_id == States.event_id)) .outerjoin(old_state, (States.old_state_id == old_state.state_id)) .filter( (Events.event_type != EVENT_STATE_CHANGED) | _missing_state_matcher(old_state) ) .filter( (Events.event_type != EVENT_STATE_CHANGED) | _continuous_entity_matcher() ) ) return _apply_event_types_filter(hass, events_query, ALL_EVENT_TYPES) def _missing_state_matcher(old_state): # The below removes state change events that do not have # and old_state or the old_state is missing (newly added entities) # or the new_state is missing (removed entities) return sqlalchemy.and_( old_state.state_id.isnot(None), (States.state != old_state.state), States.state.isnot(None), ) def _continuous_entity_matcher(): # # Prefilter out continuous domains that have # ATTR_UNIT_OF_MEASUREMENT as its much faster in sql. # return sqlalchemy.or_( sqlalchemy.not_(States.domain.in_(CONTINUOUS_DOMAINS)), sqlalchemy.not_(States.attributes.contains(UNIT_OF_MEASUREMENT_JSON)), ) def _apply_event_time_filter(events_query, start_day, end_day): return events_query.filter( (Events.time_fired > start_day) & (Events.time_fired < end_day) ) def _apply_event_types_filter(hass, query, event_types): return query.filter( Events.event_type.in_(event_types + list(hass.data.get(DOMAIN, {}))) ) def _apply_event_entity_id_matchers(events_query, entity_ids): return events_query.filter( sqlalchemy.or_( *[ Events.event_data.contains(ENTITY_ID_JSON_TEMPLATE.format(entity_id)) for entity_id in entity_ids ] ) ) def _keep_event(hass, event, entities_filter): if event.event_type in HOMEASSISTANT_EVENTS: return entities_filter is None or entities_filter(HA_DOMAIN_ENTITY_ID) entity_id = event.data_entity_id if entity_id: return entities_filter is None or entities_filter(entity_id) if event.event_type in hass.data[DOMAIN]: # If the entity_id isn't described, use the domain that describes # the event for filtering. domain = hass.data[DOMAIN][event.event_type][0] else: domain = event.data_domain if domain is None: return False return entities_filter is None or entities_filter(f"{domain}.") def _augment_data_with_context( data, entity_id, event, context_lookup, entity_attr_cache, external_events ): context_event = context_lookup.get(event.context_id) if not context_event: return if event == context_event: # This is the first event with the given ID. Was it directly caused by # a parent event? if event.context_parent_id: context_event = context_lookup.get(event.context_parent_id) # Ensure the (parent) context_event exists and is not the root cause of # this log entry. if not context_event or event == context_event: return event_type = context_event.event_type context_entity_id = context_event.entity_id # State change if context_entity_id: data["context_entity_id"] = context_entity_id data["context_entity_id_name"] = _entity_name_from_event( context_entity_id, context_event, entity_attr_cache ) data["context_event_type"] = event_type return event_data = context_event.data # Call service if event_type == EVENT_CALL_SERVICE: event_data = context_event.data data["context_domain"] = event_data.get(ATTR_DOMAIN) data["context_service"] = event_data.get(ATTR_SERVICE) data["context_event_type"] = event_type return if not entity_id: return attr_entity_id = event_data.get(ATTR_ENTITY_ID) if not attr_entity_id or ( event_type in SCRIPT_AUTOMATION_EVENTS and attr_entity_id == entity_id ): return if context_event == event: return data["context_entity_id"] = attr_entity_id data["context_entity_id_name"] = _entity_name_from_event( attr_entity_id, context_event, entity_attr_cache ) data["context_event_type"] = event_type if event_type in external_events: domain, describe_event = external_events[event_type] data["context_domain"] = domain name = describe_event(context_event).get(ATTR_NAME) if name: data["context_name"] = name def _entity_name_from_event(entity_id, event, entity_attr_cache): """Extract the entity name from the event using the cache if possible.""" return entity_attr_cache.get( entity_id, ATTR_FRIENDLY_NAME, event ) or split_entity_id(entity_id)[1].replace("_", " ") class LazyEventPartialState: """A lazy version of core Event with limited State joined in.""" __slots__ = [ "_row", "_event_data", "_time_fired_isoformat", "_attributes", "event_type", "entity_id", "state", "domain", "context_id", "context_user_id", "context_parent_id", "time_fired_minute", ] def __init__(self, row): """Init the lazy event.""" self._row = row self._event_data = None self._time_fired_isoformat = None self._attributes = None self.event_type = self._row.event_type self.entity_id = self._row.entity_id self.state = self._row.state self.domain = self._row.domain self.context_id = self._row.context_id self.context_user_id = self._row.context_user_id self.context_parent_id = self._row.context_parent_id self.time_fired_minute = self._row.time_fired.minute @property def attributes_icon(self): """Extract the icon from the decoded attributes or json.""" if self._attributes: return self._attributes.get(ATTR_ICON) result = ICON_JSON_EXTRACT.search(self._row.attributes) return result and result.group(1) @property def data_entity_id(self): """Extract the entity id from the decoded data or json.""" if self._event_data: return self._event_data.get(ATTR_ENTITY_ID) result = ENTITY_ID_JSON_EXTRACT.search(self._row.event_data) return result and result.group(1) @property def data_domain(self): """Extract the domain from the decoded data or json.""" if self._event_data: return self._event_data.get(ATTR_DOMAIN) result = DOMAIN_JSON_EXTRACT.search(self._row.event_data) return result and result.group(1) @property def attributes(self): """State attributes.""" if not self._attributes: if ( self._row.attributes is None or self._row.attributes == EMPTY_JSON_OBJECT ): self._attributes = {} else: self._attributes = json.loads(self._row.attributes) return self._attributes @property def data(self): """Event data.""" if not self._event_data: if self._row.event_data == EMPTY_JSON_OBJECT: self._event_data = {} else: self._event_data = json.loads(self._row.event_data) return self._event_data @property def time_fired_isoformat(self): """Time event was fired in utc isoformat.""" if not self._time_fired_isoformat: self._time_fired_isoformat = process_timestamp_to_utc_isoformat( self._row.time_fired or dt_util.utcnow() ) return self._time_fired_isoformat class EntityAttributeCache: """A cache to lookup static entity_id attribute. This class should not be used to lookup attributes that are expected to change state. """ def __init__(self, hass): """Init the cache.""" self._hass = hass self._cache = {} def get(self, entity_id, attribute, event): """Lookup an attribute for an entity or get it from the cache.""" if entity_id in self._cache: if attribute in self._cache[entity_id]: return self._cache[entity_id][attribute] else: self._cache[entity_id] = {} current_state = self._hass.states.get(entity_id) if current_state: # Try the current state as its faster than decoding the # attributes self._cache[entity_id][attribute] = current_state.attributes.get(attribute) else: # If the entity has been removed, decode the attributes # instead self._cache[entity_id][attribute] = event.attributes.get(attribute) return self._cache[entity_id][attribute]
"""The tests for the notify smtp platform.""" from os import path import re from unittest.mock import patch import pytest from homeassistant import config as hass_config import homeassistant.components.notify as notify from homeassistant.components.smtp import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """Verify we can reload the notify service.""" with patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "recipient": "test@example.com", "sender": "test@example.com", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @pytest.fixture def message(): """Return MockSMTP object with test data.""" mailer = MockSMTP( "localhost", 25, 5, "test@test.com", 1, "testuser", "testpass", ["recip1@example.com", "testrecip@test.com"], "Home Assistant", 0, ) yield mailer HTML = """ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"></head> <body> <div> <h1>Intruder alert at apartment!!</h1> </div> <div> <img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/> </div> </body> </html>""" EMAIL_DATA = [ ( "Test msg", {"images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]}, "Content-Type: multipart/related", ), ] @pytest.mark.parametrize( "message_data, data, content_type", EMAIL_DATA, ids=[ "Tests when sending text message and images.", "Tests when sending text message, HTML Template and images.", "Tests when image does not exist at mentioned location.", "Tests when image type cannot be detected or is of wrong type.", ], ) def test_send_message(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """Verify if we can send simple text message.""" expected = ( '^Content-Type: text/plain; charset="us-ascii"\n' "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 7bit\n" "Subject: Home Assistant\n" "To: recip1@example.com,testrecip@test.com\n" "From: Home Assistant <test@test.com>\n" "X-Mailer: Home Assistant\n" "Date: [^\n]+\n" "Message-Id: <[^@]+@[^>]+>\n" "\n" "Test msg$" ) sample_email = "<mock@mock>" message_data = "Test msg" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data) assert re.search(expected, result)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/logbook/__init__.py
"""Support for Envisalink-based alarm control panels (Honeywell/DSC).""" import logging import voluptuous as vol from homeassistant.components.alarm_control_panel import ( FORMAT_NUMBER, AlarmControlPanelEntity, ) from homeassistant.components.alarm_control_panel.const import ( SUPPORT_ALARM_ARM_AWAY, SUPPORT_ALARM_ARM_HOME, SUPPORT_ALARM_ARM_NIGHT, SUPPORT_ALARM_TRIGGER, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_CODE, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_NIGHT, STATE_ALARM_DISARMED, STATE_ALARM_PENDING, STATE_ALARM_TRIGGERED, STATE_UNKNOWN, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import ( CONF_PANIC, CONF_PARTITIONNAME, DATA_EVL, DOMAIN, PARTITION_SCHEMA, SIGNAL_KEYPAD_UPDATE, SIGNAL_PARTITION_UPDATE, EnvisalinkDevice, ) _LOGGER = logging.getLogger(__name__) SERVICE_ALARM_KEYPRESS = "alarm_keypress" ATTR_KEYPRESS = "keypress" ALARM_KEYPRESS_SCHEMA = vol.Schema( { vol.Required(ATTR_ENTITY_ID): cv.entity_ids, vol.Required(ATTR_KEYPRESS): cv.string, } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Perform the setup for Envisalink alarm panels.""" configured_partitions = discovery_info["partitions"] code = discovery_info[CONF_CODE] panic_type = discovery_info[CONF_PANIC] devices = [] for part_num in configured_partitions: device_config_data = PARTITION_SCHEMA(configured_partitions[part_num]) device = EnvisalinkAlarm( hass, part_num, device_config_data[CONF_PARTITIONNAME], code, panic_type, hass.data[DATA_EVL].alarm_state["partition"][part_num], hass.data[DATA_EVL], ) devices.append(device) async_add_entities(devices) @callback def alarm_keypress_handler(service): """Map services to methods on Alarm.""" entity_ids = service.data.get(ATTR_ENTITY_ID) keypress = service.data.get(ATTR_KEYPRESS) target_devices = [ device for device in devices if device.entity_id in entity_ids ] for device in target_devices: device.async_alarm_keypress(keypress) hass.services.async_register( DOMAIN, SERVICE_ALARM_KEYPRESS, alarm_keypress_handler, schema=ALARM_KEYPRESS_SCHEMA, ) return True class EnvisalinkAlarm(EnvisalinkDevice, AlarmControlPanelEntity): """Representation of an Envisalink-based alarm panel.""" def __init__( self, hass, partition_number, alarm_name, code, panic_type, info, controller ): """Initialize the alarm panel.""" self._partition_number = partition_number self._code = code self._panic_type = panic_type _LOGGER.debug("Setting up alarm: %s", alarm_name) super().__init__(alarm_name, info, controller) async def async_added_to_hass(self): """Register callbacks.""" self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_KEYPAD_UPDATE, self._update_callback ) ) self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_PARTITION_UPDATE, self._update_callback ) ) @callback def _update_callback(self, partition): """Update Home Assistant state, if needed.""" if partition is None or int(partition) == self._partition_number: self.async_write_ha_state() @property def code_format(self): """Regex for code format or None if no code is required.""" if self._code: return None return FORMAT_NUMBER @property def state(self): """Return the state of the device.""" state = STATE_UNKNOWN if self._info["status"]["alarm"]: state = STATE_ALARM_TRIGGERED elif self._info["status"]["armed_zero_entry_delay"]: state = STATE_ALARM_ARMED_NIGHT elif self._info["status"]["armed_away"]: state = STATE_ALARM_ARMED_AWAY elif self._info["status"]["armed_stay"]: state = STATE_ALARM_ARMED_HOME elif self._info["status"]["exit_delay"]: state = STATE_ALARM_PENDING elif self._info["status"]["entry_delay"]: state = STATE_ALARM_PENDING elif self._info["status"]["alpha"]: state = STATE_ALARM_DISARMED return state @property def supported_features(self) -> int: """Return the list of supported features.""" return ( SUPPORT_ALARM_ARM_HOME | SUPPORT_ALARM_ARM_AWAY | SUPPORT_ALARM_ARM_NIGHT | SUPPORT_ALARM_TRIGGER ) async def async_alarm_disarm(self, code=None): """Send disarm command.""" if code: self.hass.data[DATA_EVL].disarm_partition(str(code), self._partition_number) else: self.hass.data[DATA_EVL].disarm_partition( str(self._code), self._partition_number ) async def async_alarm_arm_home(self, code=None): """Send arm home command.""" if code: self.hass.data[DATA_EVL].arm_stay_partition( str(code), self._partition_number ) else: self.hass.data[DATA_EVL].arm_stay_partition( str(self._code), self._partition_number ) async def async_alarm_arm_away(self, code=None): """Send arm away command.""" if code: self.hass.data[DATA_EVL].arm_away_partition( str(code), self._partition_number ) else: self.hass.data[DATA_EVL].arm_away_partition( str(self._code), self._partition_number ) async def async_alarm_trigger(self, code=None): """Alarm trigger command. Will be used to trigger a panic alarm.""" self.hass.data[DATA_EVL].panic_alarm(self._panic_type) async def async_alarm_arm_night(self, code=None): """Send arm night command.""" self.hass.data[DATA_EVL].arm_night_partition( str(code) if code else str(self._code), self._partition_number ) @callback def async_alarm_keypress(self, keypress=None): """Send custom keypress.""" if keypress: self.hass.data[DATA_EVL].keypresses_to_partition( self._partition_number, keypress )
"""The tests for the notify smtp platform.""" from os import path import re from unittest.mock import patch import pytest from homeassistant import config as hass_config import homeassistant.components.notify as notify from homeassistant.components.smtp import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """Verify we can reload the notify service.""" with patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "recipient": "test@example.com", "sender": "test@example.com", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @pytest.fixture def message(): """Return MockSMTP object with test data.""" mailer = MockSMTP( "localhost", 25, 5, "test@test.com", 1, "testuser", "testpass", ["recip1@example.com", "testrecip@test.com"], "Home Assistant", 0, ) yield mailer HTML = """ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"></head> <body> <div> <h1>Intruder alert at apartment!!</h1> </div> <div> <img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/> </div> </body> </html>""" EMAIL_DATA = [ ( "Test msg", {"images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]}, "Content-Type: multipart/related", ), ] @pytest.mark.parametrize( "message_data, data, content_type", EMAIL_DATA, ids=[ "Tests when sending text message and images.", "Tests when sending text message, HTML Template and images.", "Tests when image does not exist at mentioned location.", "Tests when image type cannot be detected or is of wrong type.", ], ) def test_send_message(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """Verify if we can send simple text message.""" expected = ( '^Content-Type: text/plain; charset="us-ascii"\n' "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 7bit\n" "Subject: Home Assistant\n" "To: recip1@example.com,testrecip@test.com\n" "From: Home Assistant <test@test.com>\n" "X-Mailer: Home Assistant\n" "Date: [^\n]+\n" "Message-Id: <[^@]+@[^>]+>\n" "\n" "Test msg$" ) sample_email = "<mock@mock>" message_data = "Test msg" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data) assert re.search(expected, result)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/envisalink/alarm_control_panel.py
"""Support for file notification.""" import os import voluptuous as vol from homeassistant.components.notify import ( ATTR_TITLE, ATTR_TITLE_DEFAULT, PLATFORM_SCHEMA, BaseNotificationService, ) from homeassistant.const import CONF_FILENAME import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util CONF_TIMESTAMP = "timestamp" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_FILENAME): cv.string, vol.Optional(CONF_TIMESTAMP, default=False): cv.boolean, } ) def get_service(hass, config, discovery_info=None): """Get the file notification service.""" filename = config[CONF_FILENAME] timestamp = config[CONF_TIMESTAMP] return FileNotificationService(hass, filename, timestamp) class FileNotificationService(BaseNotificationService): """Implement the notification service for the File service.""" def __init__(self, hass, filename, add_timestamp): """Initialize the service.""" self.filepath = os.path.join(hass.config.config_dir, filename) self.add_timestamp = add_timestamp def send_message(self, message="", **kwargs): """Send a message to a file.""" with open(self.filepath, "a") as file: if os.stat(self.filepath).st_size == 0: title = f"{kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)} notifications (Log started: {dt_util.utcnow().isoformat()})\n{'-' * 80}\n" file.write(title) if self.add_timestamp: text = f"{dt_util.utcnow().isoformat()} {message}\n" else: text = f"{message}\n" file.write(text)
"""The tests for the notify smtp platform.""" from os import path import re from unittest.mock import patch import pytest from homeassistant import config as hass_config import homeassistant.components.notify as notify from homeassistant.components.smtp import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """Verify we can reload the notify service.""" with patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "recipient": "test@example.com", "sender": "test@example.com", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @pytest.fixture def message(): """Return MockSMTP object with test data.""" mailer = MockSMTP( "localhost", 25, 5, "test@test.com", 1, "testuser", "testpass", ["recip1@example.com", "testrecip@test.com"], "Home Assistant", 0, ) yield mailer HTML = """ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"></head> <body> <div> <h1>Intruder alert at apartment!!</h1> </div> <div> <img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/> </div> </body> </html>""" EMAIL_DATA = [ ( "Test msg", {"images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]}, "Content-Type: multipart/related", ), ] @pytest.mark.parametrize( "message_data, data, content_type", EMAIL_DATA, ids=[ "Tests when sending text message and images.", "Tests when sending text message, HTML Template and images.", "Tests when image does not exist at mentioned location.", "Tests when image type cannot be detected or is of wrong type.", ], ) def test_send_message(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """Verify if we can send simple text message.""" expected = ( '^Content-Type: text/plain; charset="us-ascii"\n' "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 7bit\n" "Subject: Home Assistant\n" "To: recip1@example.com,testrecip@test.com\n" "From: Home Assistant <test@test.com>\n" "X-Mailer: Home Assistant\n" "Date: [^\n]+\n" "Message-Id: <[^@]+@[^>]+>\n" "\n" "Test msg$" ) sample_email = "<mock@mock>" message_data = "Test msg" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data) assert re.search(expected, result)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/file/notify.py
"""Config flow for Islamic Prayer Times integration.""" import voluptuous as vol from homeassistant import config_entries from homeassistant.core import callback # pylint: disable=unused-import from .const import CALC_METHODS, CONF_CALC_METHOD, DEFAULT_CALC_METHOD, DOMAIN, NAME class IslamicPrayerFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle the Islamic Prayer config flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL @staticmethod @callback def async_get_options_flow(config_entry): """Get the options flow for this handler.""" return IslamicPrayerOptionsFlowHandler(config_entry) async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" if self._async_current_entries(): return self.async_abort(reason="single_instance_allowed") if user_input is None: return self.async_show_form(step_id="user") return self.async_create_entry(title=NAME, data=user_input) async def async_step_import(self, import_config): """Import from config.""" return await self.async_step_user(user_input=import_config) class IslamicPrayerOptionsFlowHandler(config_entries.OptionsFlow): """Handle Islamic Prayer client options.""" def __init__(self, config_entry): """Initialize options flow.""" self.config_entry = config_entry async def async_step_init(self, user_input=None): """Manage options.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) options = { vol.Optional( CONF_CALC_METHOD, default=self.config_entry.options.get( CONF_CALC_METHOD, DEFAULT_CALC_METHOD ), ): vol.In(CALC_METHODS) } return self.async_show_form(step_id="init", data_schema=vol.Schema(options))
"""The tests for the notify smtp platform.""" from os import path import re from unittest.mock import patch import pytest from homeassistant import config as hass_config import homeassistant.components.notify as notify from homeassistant.components.smtp import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """Verify we can reload the notify service.""" with patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "recipient": "test@example.com", "sender": "test@example.com", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @pytest.fixture def message(): """Return MockSMTP object with test data.""" mailer = MockSMTP( "localhost", 25, 5, "test@test.com", 1, "testuser", "testpass", ["recip1@example.com", "testrecip@test.com"], "Home Assistant", 0, ) yield mailer HTML = """ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"></head> <body> <div> <h1>Intruder alert at apartment!!</h1> </div> <div> <img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/> </div> </body> </html>""" EMAIL_DATA = [ ( "Test msg", {"images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]}, "Content-Type: multipart/related", ), ] @pytest.mark.parametrize( "message_data, data, content_type", EMAIL_DATA, ids=[ "Tests when sending text message and images.", "Tests when sending text message, HTML Template and images.", "Tests when image does not exist at mentioned location.", "Tests when image type cannot be detected or is of wrong type.", ], ) def test_send_message(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """Verify if we can send simple text message.""" expected = ( '^Content-Type: text/plain; charset="us-ascii"\n' "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 7bit\n" "Subject: Home Assistant\n" "To: recip1@example.com,testrecip@test.com\n" "From: Home Assistant <test@test.com>\n" "X-Mailer: Home Assistant\n" "Date: [^\n]+\n" "Message-Id: <[^@]+@[^>]+>\n" "\n" "Test msg$" ) sample_email = "<mock@mock>" message_data = "Test msg" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data) assert re.search(expected, result)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/islamic_prayer_times/config_flow.py
"""ONVIF event abstraction.""" import asyncio import datetime as dt from typing import Callable, Dict, List, Optional, Set from httpx import RemoteProtocolError, TransportError from onvif import ONVIFCamera, ONVIFService from zeep.exceptions import Fault from homeassistant.core import CALLBACK_TYPE, CoreState, HomeAssistant, callback from homeassistant.helpers.event import async_call_later from homeassistant.util import dt as dt_util from .const import LOGGER from .models import Event from .parsers import PARSERS UNHANDLED_TOPICS = set() SUBSCRIPTION_ERRORS = ( Fault, asyncio.TimeoutError, TransportError, ) class EventManager: """ONVIF Event Manager.""" def __init__(self, hass: HomeAssistant, device: ONVIFCamera, unique_id: str): """Initialize event manager.""" self.hass: HomeAssistant = hass self.device: ONVIFCamera = device self.unique_id: str = unique_id self.started: bool = False self._subscription: ONVIFService = None self._events: Dict[str, Event] = {} self._listeners: List[CALLBACK_TYPE] = [] self._unsub_refresh: Optional[CALLBACK_TYPE] = None super().__init__() @property def platforms(self) -> Set[str]: """Return platforms to setup.""" return {event.platform for event in self._events.values()} @callback def async_add_listener(self, update_callback: CALLBACK_TYPE) -> Callable[[], None]: """Listen for data updates.""" # This is the first listener, set up polling. if not self._listeners: self.async_schedule_pull() self._listeners.append(update_callback) @callback def remove_listener() -> None: """Remove update listener.""" self.async_remove_listener(update_callback) return remove_listener @callback def async_remove_listener(self, update_callback: CALLBACK_TYPE) -> None: """Remove data update.""" if update_callback in self._listeners: self._listeners.remove(update_callback) if not self._listeners and self._unsub_refresh: self._unsub_refresh() self._unsub_refresh = None async def async_start(self) -> bool: """Start polling events.""" if await self.device.create_pullpoint_subscription(): # Create subscription manager self._subscription = self.device.create_subscription_service( "PullPointSubscription" ) # Renew immediately await self.async_renew() # Initialize events pullpoint = self.device.create_pullpoint_service() try: await pullpoint.SetSynchronizationPoint() except SUBSCRIPTION_ERRORS: pass response = await pullpoint.PullMessages( {"MessageLimit": 100, "Timeout": dt.timedelta(seconds=5)} ) # Parse event initialization await self.async_parse_messages(response.NotificationMessage) self.started = True return True return False async def async_stop(self) -> None: """Unsubscribe from events.""" self._listeners = [] self.started = False if not self._subscription: return await self._subscription.Unsubscribe() self._subscription = None async def async_restart(self, _now: dt = None) -> None: """Restart the subscription assuming the camera rebooted.""" if not self.started: return if self._subscription: try: await self._subscription.Unsubscribe() except SUBSCRIPTION_ERRORS: pass # Ignored. The subscription may no longer exist. self._subscription = None try: restarted = await self.async_start() except SUBSCRIPTION_ERRORS: restarted = False if not restarted: LOGGER.warning( "Failed to restart ONVIF PullPoint subscription for '%s'. Retrying...", self.unique_id, ) # Try again in a minute self._unsub_refresh = async_call_later(self.hass, 60, self.async_restart) elif self._listeners: LOGGER.debug( "Restarted ONVIF PullPoint subscription for '%s'", self.unique_id ) self.async_schedule_pull() async def async_renew(self) -> None: """Renew subscription.""" if not self._subscription: return termination_time = ( (dt_util.utcnow() + dt.timedelta(days=1)) .isoformat(timespec="seconds") .replace("+00:00", "Z") ) await self._subscription.Renew(termination_time) def async_schedule_pull(self) -> None: """Schedule async_pull_messages to run.""" self._unsub_refresh = async_call_later(self.hass, 1, self.async_pull_messages) async def async_pull_messages(self, _now: dt = None) -> None: """Pull messages from device.""" if self.hass.state == CoreState.running: try: pullpoint = self.device.create_pullpoint_service() response = await pullpoint.PullMessages( {"MessageLimit": 100, "Timeout": dt.timedelta(seconds=60)} ) # Renew subscription if less than two hours is left if ( dt_util.as_utc(response.TerminationTime) - dt_util.utcnow() ).total_seconds() < 7200: await self.async_renew() except RemoteProtocolError: # Likley a shutdown event, nothing to see here return except SUBSCRIPTION_ERRORS as err: LOGGER.warning( "Failed to fetch ONVIF PullPoint subscription messages for '%s': %s", self.unique_id, err, ) # Treat errors as if the camera restarted. Assume that the pullpoint # subscription is no longer valid. self._unsub_refresh = None await self.async_restart() return # Parse response await self.async_parse_messages(response.NotificationMessage) # Update entities for update_callback in self._listeners: update_callback() # Reschedule another pull if self._listeners: self.async_schedule_pull() # pylint: disable=protected-access async def async_parse_messages(self, messages) -> None: """Parse notification message.""" for msg in messages: # Guard against empty message if not msg.Topic: continue topic = msg.Topic._value_1 parser = PARSERS.get(topic) if not parser: if topic not in UNHANDLED_TOPICS: LOGGER.info( "No registered handler for event from %s: %s", self.unique_id, msg, ) UNHANDLED_TOPICS.add(topic) continue event = await parser(self.unique_id, msg) if not event: LOGGER.warning("Unable to parse event from %s: %s", self.unique_id, msg) return self._events[event.uid] = event def get_uid(self, uid) -> Event: """Retrieve event for given id.""" return self._events[uid] def get_platform(self, platform) -> List[Event]: """Retrieve events for given platform.""" return [event for event in self._events.values() if event.platform == platform]
"""The tests for the notify smtp platform.""" from os import path import re from unittest.mock import patch import pytest from homeassistant import config as hass_config import homeassistant.components.notify as notify from homeassistant.components.smtp import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """Verify we can reload the notify service.""" with patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "recipient": "test@example.com", "sender": "test@example.com", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @pytest.fixture def message(): """Return MockSMTP object with test data.""" mailer = MockSMTP( "localhost", 25, 5, "test@test.com", 1, "testuser", "testpass", ["recip1@example.com", "testrecip@test.com"], "Home Assistant", 0, ) yield mailer HTML = """ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"></head> <body> <div> <h1>Intruder alert at apartment!!</h1> </div> <div> <img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/> </div> </body> </html>""" EMAIL_DATA = [ ( "Test msg", {"images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]}, "Content-Type: multipart/related", ), ] @pytest.mark.parametrize( "message_data, data, content_type", EMAIL_DATA, ids=[ "Tests when sending text message and images.", "Tests when sending text message, HTML Template and images.", "Tests when image does not exist at mentioned location.", "Tests when image type cannot be detected or is of wrong type.", ], ) def test_send_message(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """Verify if we can send simple text message.""" expected = ( '^Content-Type: text/plain; charset="us-ascii"\n' "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 7bit\n" "Subject: Home Assistant\n" "To: recip1@example.com,testrecip@test.com\n" "From: Home Assistant <test@test.com>\n" "X-Mailer: Home Assistant\n" "Date: [^\n]+\n" "Message-Id: <[^@]+@[^>]+>\n" "\n" "Test msg$" ) sample_email = "<mock@mock>" message_data = "Test msg" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data) assert re.search(expected, result)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/onvif/event.py
"""Support for USCIS Case Status.""" from datetime import timedelta import logging import uscisstatus import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME from homeassistant.helpers import config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "USCIS" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required("case_id"): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the platform in Home Assistant and Case Information.""" uscis = UscisSensor(config["case_id"], config[CONF_NAME]) uscis.update() if uscis.valid_case_id: add_entities([uscis]) else: _LOGGER.error("Setup USCIS Sensor Fail check if your Case ID is Valid") class UscisSensor(Entity): """USCIS Sensor will check case status on daily basis.""" MIN_TIME_BETWEEN_UPDATES = timedelta(hours=24) CURRENT_STATUS = "current_status" LAST_CASE_UPDATE = "last_update_date" def __init__(self, case, name): """Initialize the sensor.""" self._state = None self._case_id = case self._attributes = None self.valid_case_id = None self._name = name @property def name(self): """Return the name.""" return self._name @property def state(self): """Return the state.""" return self._state @property def device_state_attributes(self): """Return the state attributes.""" return self._attributes @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Fetch data from the USCIS website and update state attributes.""" try: status = uscisstatus.get_case_status(self._case_id) self._attributes = {self.CURRENT_STATUS: status["status"]} self._state = status["date"] self.valid_case_id = True except ValueError: _LOGGER("Please Check that you have valid USCIS case id") self.valid_case_id = False
"""The tests for the notify smtp platform.""" from os import path import re from unittest.mock import patch import pytest from homeassistant import config as hass_config import homeassistant.components.notify as notify from homeassistant.components.smtp import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """Verify we can reload the notify service.""" with patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "recipient": "test@example.com", "sender": "test@example.com", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch( "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid" ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @pytest.fixture def message(): """Return MockSMTP object with test data.""" mailer = MockSMTP( "localhost", 25, 5, "test@test.com", 1, "testuser", "testpass", ["recip1@example.com", "testrecip@test.com"], "Home Assistant", 0, ) yield mailer HTML = """ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"></head> <body> <div> <h1>Intruder alert at apartment!!</h1> </div> <div> <img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/> </div> </body> </html>""" EMAIL_DATA = [ ( "Test msg", {"images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]}, "Content-Type: multipart/related", ), ] @pytest.mark.parametrize( "message_data, data, content_type", EMAIL_DATA, ids=[ "Tests when sending text message and images.", "Tests when sending text message, HTML Template and images.", "Tests when image does not exist at mentioned location.", "Tests when image type cannot be detected or is of wrong type.", ], ) def test_send_message(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """Verify if we can send simple text message.""" expected = ( '^Content-Type: text/plain; charset="us-ascii"\n' "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 7bit\n" "Subject: Home Assistant\n" "To: recip1@example.com,testrecip@test.com\n" "From: Home Assistant <test@test.com>\n" "X-Mailer: Home Assistant\n" "Date: [^\n]+\n" "Message-Id: <[^@]+@[^>]+>\n" "\n" "Test msg$" ) sample_email = "<mock@mock>" message_data = "Test msg" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data) assert re.search(expected, result)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/uscis/sensor.py